Sign In

next

Package Overview
Dependencies
Maintainers
4
Versions
3895
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next - npm Package Compare versions

Comparing version
16.3.1-canary.11
to
16.3.1-canary.12
+11
dist/bundle-analyz...3YrKiZrT98GTaBzv_9H8A/_buildManifest.js
self.__BUILD_MANIFEST = {
"__rewrites": {
"afterFiles": [],
"beforeFiles": [],
"fallback": []
},
"sortedPages": [
"/_app",
"/_error"
]
};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()
self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()
self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()
---
title: Client-side data fetching
description: Fetch data in Client Components with a data-fetching library, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/guides/interactive-apps
- app/getting-started/caching
---
Many apps can provide responsive interactions without a client data-fetching library. If a Client Component only needs to read server data once, [pass it a Promise and unwrap it with React's `use()`](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-api).
This avoids adding a library for data that never revalidates on the client. See [Building interactive apps](/docs/app/guides/interactive-apps) for patterns using Server Functions, transitions, optimistic UI, and pending feedback.
Use a client data-fetching library such as [SWR](https://swr.vercel.app), [TanStack Query](https://tanstack.com/query), or [Apollo Client](https://www.apollographql.com/docs/react) when Client Components need a shared browser cache. These libraries can add focus revalidation, interval polling, request deduplication, or optimistic updates across components.
## Choose a client fetching pattern
First decide whether the initial view needs data from the server or can wait for a browser request after hydration. Client data-fetching libraries support three common patterns:
| Pattern | SWR | TanStack Query | When data becomes available |
| ----------------------- | ------------------------------ | --------------------- | -------------------------------------- |
| Inline loading states | `useSWR` | `useQuery` | Browser request after hydration |
| Suspense loading states | `useSWR` with `suspense: true` | `useSuspenseQuery` | Browser request after hydration |
| Provided by the server | `<SWRConfig fallback>` | `<HydrationBoundary>` | Initial render or streamed from server |
Use inline loading states when each component should render its own loading UI. Use [Suspense](/docs/app/getting-started/fetching-data#streaming) to define loading UI at a boundary and coordinate which parts of the interface reveal together or progressively. For client-only fetching, choose the pattern that matches the loading experience you want. Suspense coordinates rendering, while the data library and component structure determine when requests start.
For browser-driven interactions such as autocomplete, you can use either client-only pattern. The initial result waits for hydration and a browser request, which is often the right tradeoff for data that is not needed until an interaction.
Provide initial data from a [Server Component](/docs/app/getting-started/server-and-client-components) when the server knows what the initial render needs. The value can be included in the initial render or streamed through Suspense. The library receives it in the React Server Component payload and can continue managing it in the browser.
## Cache server data with Cache Components (optional)
Providing initial data and caching it on the server are independent choices. Add Cache Components when the server read or rendered view should be reused. When both are enabled, three cache layers can hold related data:
| Layer | What it stores | Freshness control |
| ---------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Next.js server cache | Cached data and Server Component output | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `revalidate` and `expire` |
| Next.js client cache | React Server Component payloads for visited and prefetched routes | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` |
| Client data-fetching library | Browser data stored under an SWR key or TanStack query key | The library's revalidation options and mutations |
Next.js [prefetching](/docs/app/guides/prefetching) can place a route's React Server Component payload in the client cache before navigation.
The cache layers keep independent freshness policies and do not need matching durations. Cache identities and mutation invalidation must stay coordinated across layers.
## Coordinate mutations
Server Components, data-fetching libraries, and mutations manage different parts of the data flow:
- **Server Components** provide the initial data, scoped to the segment that owns it.
- **The data-fetching library** stores the browser value under a shared cache identity.
- **Mutations** can update the browser cache immediately and invalidate cached server data so the next render can read a fresh value.
An optimistic update should restore the previous browser value if the write fails. If the server read is not cached, there is no server tag to invalidate.
After a mutation, invalidate any cached server read that provided the initial data:
| Method | Use when | Next server read |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------ |
| [`updateTag(tag)`](/docs/app/api-reference/functions/updateTag) | A Server Action must make its update visible immediately | Waits for fresh data |
| [`revalidateTag(tag, 'max')`](/docs/app/api-reference/functions/revalidateTag) | The update is passive or stale data is acceptable | Serves stale data while revalidating |
| [`revalidateTag(tag, { expire: 0 })`](/docs/app/api-reference/functions/revalidateTag) | A webhook or external system requires immediate expiration | Waits for fresh data |
## Apply these patterns with SWR or TanStack Query
- [Client-side data fetching with SWR](/docs/app/guides/client-side-data-fetching/swr)
- [Client-side data fetching with TanStack Query](/docs/app/guides/client-side-data-fetching/tanstack-query)
See both patterns in the live [`next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev) and its [source code](https://github.com/vercel-labs/next-spa-patterns).
---
title: How to fetch client-side data with SWR
nav_title: SWR
description: Fetch client-side data with SWR, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/getting-started/caching
- app/api-reference/directives/use-cache
- app/api-reference/file-conventions/route
- app/api-reference/functions/updateTag
---
Use [SWR](https://swr.vercel.app) to fetch data in Client Components, provide initial data from Server Components, and coordinate browser mutations with cached server data. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) to choose a pattern.
## Fetch data on the client
SWR can fetch entirely in the browser when the initial view can wait for a browser request after hydration. Choose an [inline or Suspense loading state](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) based on where the loading UI should appear. In these examples, `query` starts empty and updates from client state after hydration.
Use `useSWR` when the component should render its own loading and error states. A conditional key delays the request until the interaction provides an input:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isLoading,
} = useSWR(
query ? `/api/products?query=${encodeURIComponent(query)}` : null,
fetcher
)
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isLoading) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
## Use Suspense for client data
Use `suspense: true` when the nearest Suspense boundary should define the loading UI. Keep the interactive shell outside the boundary so it remains available while the results load:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { Suspense } from 'react'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSWR(
`/api/products?query=${encodeURIComponent(query)}`,
fetcher,
{ suspense: true }
)
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
With an unconditional key, SWR defines `data` after Suspense resolves. Handle request errors with the nearest [error boundary](/docs/app/getting-started/error-handling#nested-error-boundaries).
The `isLoading` value is `true` when a request is running and there is no loaded data to display. The `isValidating` value is `true` whenever a request is running, including background revalidation.
With `suspense: true`, Suspense handles the initial no-data state. Later revalidation for the same key keeps the current data rendered instead of showing the Suspense fallback again. Use `isValidating` to provide background refresh feedback. Learn more about [SWR loading states](https://swr.vercel.app/docs/advanced/understanding#combining-with-isloading-and-isvalidating-for-better-ux).
Learn more: [SWR data fetching](https://swr.vercel.app/docs/data-fetching).
> **Good to know:** Independent Suspense reads can start in parallel when they render in sibling components. Multiple Suspense reads in one component run sequentially. Learn more about [network waterfalls](/docs/app/guides/migrating/from-create-react-app#network-waterfalls) and [SWR Suspense](https://swr.vercel.app/docs/suspense).
## Provide initial data from a Server Component
Use the [server-provided data pattern](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) when the initial render needs the data and SWR should continue managing it in the browser. With SWR 2.3.0 and React 19, a Server Component can provide fallback data before the client takes over.
Scope `<SWRConfig>` to the route segment that owns the data. The provider keeps the `fallback` close to its consumer and avoids adding feature data to a shared layout:
```tsx filename="app/products/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}
```
The fallback and Client Component must use the same SWR key. Define the key once so both call sites share the same identity:
```ts filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => `/api/products/${id}`,
}
```
```js filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => `/api/products/${id}`,
}
```
In the page example, the Promise returned by `params.then()` keeps the fallback visible until the route parameters resolve. `ProductData` then creates a separate, unawaited `getProduct(id)` Promise for the SWR `fallback`. React passes that Promise through the React Server Component payload, and the component reading the matching key suspends until the data resolves.
The Client Component reads the data with `useSWR` using the same key:
```tsx filename="app/products/[id]/product-view.tsx" switcher
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }: { id: string }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}
```
```jsx filename="app/products/[id]/product-view.js" switcher
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
async function fetcher(url) {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}
```
> **Good to know:** The `fallback` key and the `useSWR` key must match exactly. If they drift, SWR ignores the fallback value and fetches on the client.
The `fallback` provides the hook's initial value. By default, SWR treats fallback data as stale and starts a browser revalidation after hydration.
SWR does not provide a time-based freshness window for fallback data. Setting `revalidateIfStale: false` skips revalidation when the hook mounts with cached data. This setting applies to every mount, unlike TanStack Query's `staleTime`.
Focus, reconnect, polling, and `mutate` can still revalidate the key. To refresh on a schedule, set [`refreshInterval`](https://swr.vercel.app/docs/revalidation#revalidate-on-interval).
The SWR key points to a [Route Handler](/docs/app/api-reference/file-conventions/route) with a `GET` method. The Route Handler can call the same `getProduct` function that provides the fallback, while the browser uses the URL for revalidation and polling.
Learn more: [SWR arguments and keys](https://swr.vercel.app/docs/arguments) and [SWR with Next.js App Router](https://swr.vercel.app/docs/with-nextjs).
## Cache server-provided data with Cache Components
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) in `next.config.ts` before using this pattern. You can then cache the server data used as the SWR fallback. Add [`use cache`](/docs/app/api-reference/directives/use-cache), choose a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile, and apply [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so mutations can invalidate it:
```ts filename="app/products/[id]/data.ts" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id: string) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
```js filename="app/products/[id]/data.js" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
This example uses `cacheLife('max')` because writes invalidate the product tag. Within the cache profile, `stale` controls how long the Next.js client cache can reuse a prefetched payload, while `revalidate` and `expire` control the server cache. Choose a shorter profile when the server value should refresh with time.
SWR owns a separate browser cache, so its revalidation options do not need to match `cacheLife`.
When the same mutation updates the browser cache and invalidates cached server data, you may define both identities in one shared contract:
```diff filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => `/api/products/${id}`,
+ tag: (id: string) => `product:${id}`,
}
```
```diff filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => `/api/products/${id}`,
+ tag: (id) => `product:${id}`,
}
```
The server function can then call `cacheTag(productCache.tag(id))`. Keep this contract free of server-only and client-only imports so both cache layers can reuse it.
## Coordinate server and client caches after mutations
The fallback provides the initial value. After hydration, SWR manages the browser cache and revalidation. For reused data, keep the SWR key and server tag in the same cache contract:
```ts filename="app/activity/activity-cache.ts" switcher
export const activityCache = {
key: '/api/activity/unread',
tag: (userId: string) => `activity:${userId}`,
}
```
```js filename="app/activity/activity-cache.js" switcher
export const activityCache = {
key: '/api/activity/unread',
tag: (userId) => `activity:${userId}`,
}
```
Use the same key for the fallback, the Client Component read, and the mutation. With SWR, pass the write to [`mutate`](https://swr.vercel.app/docs/mutation) and provide `optimisticData`. SWR shows the optimistic value immediately and rolls it back if the write fails. This example keeps the optimistic value after the action succeeds because the final value is known:
```tsx filename="app/activity/mark-read-button.tsx" switcher
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}
```
```jsx filename="app/activity/mark-read-button.js" switcher
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}
```
The Server Action writes to the database and expires the tagged server data with [`updateTag`](/docs/app/api-reference/functions/updateTag). Tag the cached server query with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so the tag matches:
```ts filename="app/activity/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
```js filename="app/activity/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
The optimistic SWR value updates the current screen. `updateTag` ensures the next cached server read returns fresh activity.
> **Good to know:** Call `updateTag` when a Server Action changes a cached read that must reflect the write immediately. An uncached read does not have a server tag to update. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching#coordinate-mutations) for other invalidation behaviors.
See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/swr) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/swr). Learn more about [SWR mutation and optimistic updates](https://swr.vercel.app/docs/mutation) and the [SWR documentation](https://swr.vercel.app/docs/getting-started).
---
title: How to fetch client-side data with TanStack Query
nav_title: TanStack Query
description: Fetch client-side data with TanStack Query, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/getting-started/caching
- app/api-reference/directives/use-cache
- app/api-reference/file-conventions/route
- app/api-reference/functions/updateTag
---
Use [TanStack Query](https://tanstack.com/query) to fetch data in Client Components, provide initial data from Server Components, and coordinate browser mutations with cached server data. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) to choose a pattern.
## Set up the provider
Wrap the routes that use TanStack Query in a `QueryClientProvider`. Create a new query client for each server render and reuse one query client in the browser:
```tsx filename="app/products/providers.tsx"
'use client'
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
let browserQueryClient: QueryClient | undefined
function getQueryClient() {
// Keep server requests isolated and preserve the browser cache across renders.
if (typeof window === 'undefined') return new QueryClient()
browserQueryClient ??= new QueryClient()
return browserQueryClient
}
export function Providers({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={getQueryClient()}>
{children}
</QueryClientProvider>
)
}
```
Render the provider from the nearest shared layout:
```tsx filename="app/products/layout.tsx"
import { Providers } from './providers'
export default function Layout({ children }: LayoutProps<'/products'>) {
return <Providers>{children}</Providers>
}
```
See the [complete provider setup in the demo source](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query) or learn about provider options in the [TanStack Query Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
## Fetch data on the client
TanStack Query can fetch entirely in the browser when the initial view can wait for a browser request after hydration. Choose an [inline or Suspense loading state](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) based on where the loading UI should appear. In these examples, `query` starts empty and updates from client state after hydration.
Use `useQuery` when the component should render its own loading and error states. The `enabled` option delays the request until the interaction provides an input:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { useQuery } from '@tanstack/react-query'
type Product = { id: string; name: string }
async function searchProducts(query: string): Promise<Product[]> {
const response = await fetch(
`/api/products?query=${encodeURIComponent(query)}`
)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isPending,
} = useQuery({
queryKey: ['product-search', query],
queryFn: () => searchProducts(query),
enabled: query.length > 0,
})
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isPending) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
Learn more: [TanStack Query queries](https://tanstack.com/query/latest/docs/framework/react/guides/queries).
## Use Suspense for client data
Use `useSuspenseQuery` when the nearest Suspense boundary should define the loading UI. Keep the interactive shell outside the boundary so it remains available while the results load:
```tsx filename="app/product-autocomplete.tsx"
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { Suspense } from 'react'
type Product = { id: string; name: string }
async function searchProducts(query: string): Promise<Product[]> {
const response = await fetch(
`/api/products?query=${encodeURIComponent(query)}`
)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSuspenseQuery({
queryKey: ['product-search', query],
queryFn: () => searchProducts(query),
})
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}
```
If the initial request fails, `useSuspenseQuery` propagates the error to the nearest [error boundary](/docs/app/getting-started/error-handling#nested-error-boundaries).
After a query has data, later refetches for the same query keep the cached data rendered instead of showing the Suspense fallback again. Use `isFetching` to provide background refresh feedback.
If the initial view needs the data, provide it from a Server Component as shown below.
> **Good to know:** Multiple `useSuspenseQuery` calls in one component run sequentially. Put independent queries in sibling components, or use [`useSuspenseQueries`](https://tanstack.com/query/latest/docs/framework/react/reference/useSuspenseQueries). Learn more about [request waterfalls](https://tanstack.com/query/latest/docs/framework/react/guides/request-waterfalls).
## Provide initial data from a Server Component
Use the [server-provided data pattern](/docs/app/guides/client-side-data-fetching#choose-a-client-fetching-pattern) when the initial render needs the data and TanStack Query should continue managing it in the browser. A Server Component can provide initial query data before the client takes over.
TanStack Query 5.40.0 or later can dehydrate pending queries. Start `prefetchQuery` without awaiting it, then pass the dehydrated state to `<HydrationBoundary>`. Override `queryFn` on the server because the Route Handler's relative URL only resolves in the browser:
```tsx filename="app/products/[id]/page.tsx" switcher
import { Suspense } from 'react'
import {
defaultShouldDehydrateQuery,
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
const queryClient = new QueryClient()
// Not awaited, so rendering is not blocked.
void queryClient.prefetchQuery({
...productCache.options(id),
queryFn: () => getProduct(id),
})
return (
<HydrationBoundary
state={dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
})}
>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { Suspense } from 'react'
import {
defaultShouldDehydrateQuery,
dehydrate,
HydrationBoundary,
QueryClient,
} from '@tanstack/react-query'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
const queryClient = new QueryClient()
// Not awaited, so rendering is not blocked.
void queryClient.prefetchQuery({
...productCache.options(id),
queryFn: () => getProduct(id),
})
return (
<HydrationBoundary
state={dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
})}
>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
The server and Client Component must use the same query key. Keep the key and query options together so both call sites share the same identity:
```ts filename="app/products/[id]/product-cache.ts" switcher
import { queryOptions } from '@tanstack/react-query'
export type Product = { id: string; name: string }
export const productCache = {
key: (id: string) => ['product', id] as const,
options: (id: string) =>
queryOptions({
queryKey: productCache.key(id),
queryFn: async (): Promise<Product> => {
const res = await fetch(`/api/products/${id}`)
if (!res.ok) throw new Error('Failed to fetch product')
return res.json()
},
staleTime: 30_000,
}),
}
```
```js filename="app/products/[id]/product-cache.js" switcher
import { queryOptions } from '@tanstack/react-query'
export const productCache = {
key: (id) => ['product', id],
options: (id) =>
queryOptions({
queryKey: productCache.key(id),
queryFn: async () => {
const res = await fetch(`/api/products/${id}`)
if (!res.ok) throw new Error('Failed to fetch product')
return res.json()
},
staleTime: 30_000,
}),
}
```
The query function fetches a [Route Handler](/docs/app/api-reference/file-conventions/route) so it can run on the client. The `staleTime` prevents an immediate client refetch by keeping the hydrated data fresh for 30 seconds. Choose a duration based on how quickly the data can change.
Larger features can place query options in a separate client-facing module as long as every caller imports the key from the same cache contract. Learn more about [TanStack Query defaults](https://tanstack.com/query/latest/docs/framework/react/guides/important-defaults).
As with SWR, `params.then()` resolves the `id` inside `<Suspense>`, and `ProductData` prefetches below the boundary.
The Client Component reads the same query key with `useSuspenseQuery` (or `useQuery` to render `isPending` and `error` states inline):
```tsx filename="app/products/[id]/product-view.tsx" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productCache } from './product-cache'
export function ProductView({ id }: { id: string }) {
const { data } = useSuspenseQuery(productCache.options(id))
return <h1>{data.name}</h1>
}
```
```jsx filename="app/products/[id]/product-view.js" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productCache } from './product-cache'
export function ProductView({ id }) {
const { data } = useSuspenseQuery(productCache.options(id))
return <h1>{data.name}</h1>
}
```
Learn more: [TanStack Query Advanced SSR](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
## Cache server-provided data with Cache Components
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) in `next.config.ts` before using this pattern. You can then cache the server data provided to TanStack Query. Add [`use cache`](/docs/app/api-reference/directives/use-cache), choose a [`cacheLife`](/docs/app/api-reference/functions/cacheLife) profile, and apply [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so mutations can invalidate it:
```ts filename="app/products/[id]/data.ts" switcher
import { cacheLife, cacheTag } from 'next/cache'
import type { Product } from './product-cache'
export async function getProduct(id: string): Promise<Product> {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
```js filename="app/products/[id]/data.js" switcher
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}
```
This example uses `cacheLife('max')` because writes invalidate the product tag. Within the cache profile, `stale` controls how long the Next.js client cache can reuse a prefetched payload, while `revalidate` and `expire` control the server cache. Choose a shorter profile when the server value should refresh with time.
TanStack Query owns a separate browser cache, so its `staleTime` does not need to match `cacheLife`.
With Cache Components enabled, Next.js also prerenders Client Components. Keep a query needed during the initial render behind [Suspense](/docs/app/getting-started/fetching-data#streaming). TanStack Query can read the current time while creating active query state, and the boundary lets Next.js defer that work instead of raising a [current-time prerender error](/docs/messages/blocking-prerender-current-time-client).
When the same mutation updates the browser cache and invalidates cached server data, you may define both identities in one shared contract:
```diff filename="app/products/[id]/product-cache.ts" switcher
export const productCache = {
key: (id: string) => ['product', id] as const,
+ tag: (id: string) => `product:${id}`,
// ...
}
```
```diff filename="app/products/[id]/product-cache.js" switcher
export const productCache = {
key: (id) => ['product', id],
+ tag: (id) => `product:${id}`,
// ...
}
```
The server function can then call `cacheTag(productCache.tag(id))`. Keep this contract free of server-only and client-only imports so both cache layers can reuse it.
> **Good to know:** TanStack Query's `dehydrate()` reads the current time during Cache Components prerendering. Use the [prerenderable hydration helper](#build-a-prerenderable-hydration-state) for cached initial data.
## Coordinate server and client caches after mutations
Hydration provides the initial client cache value. After hydration, TanStack Query owns the browser copy and its revalidation. For reused data, keep the query key and server tag in the same cache contract:
```ts filename="app/activity/activity-cache.ts" switcher
export const activityCache = {
key: ['activity', 'unread'] as const,
tag: (userId: string) => `activity:${userId}`,
}
```
```js filename="app/activity/activity-cache.js" switcher
export const activityCache = {
key: ['activity', 'unread'],
tag: (userId) => `activity:${userId}`,
}
```
On mutation, use `useMutation`'s [`onMutate`](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) callback to update the cache immediately and restore the previous value in `onError` if the write fails. This example keeps the optimistic value after the action succeeds because the final value is known:
```tsx filename="app/activity/mark-read-button.tsx" switcher
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const queryClient = useQueryClient()
const queryKey = activityCache.key
const markRead = useMutation({
mutationFn: markActivityReadAction,
onMutate: async () => {
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueryData(queryKey)
queryClient.setQueryData(queryKey, { count: 0 })
return { previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(queryKey, context?.previous)
},
})
return <button onClick={() => markRead.mutate()}>Mark read</button>
}
```
```jsx filename="app/activity/mark-read-button.js" switcher
'use client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const queryClient = useQueryClient()
const queryKey = activityCache.key
const markRead = useMutation({
mutationFn: markActivityReadAction,
onMutate: async () => {
await queryClient.cancelQueries({ queryKey })
const previous = queryClient.getQueryData(queryKey)
queryClient.setQueryData(queryKey, { count: 0 })
return { previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(queryKey, context?.previous)
},
})
return <button onClick={() => markRead.mutate()}>Mark read</button>
}
```
The Server Action writes to the database and expires the tagged server data with [`updateTag`](/docs/app/api-reference/functions/updateTag). Tag the cached server query with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) so the tag matches:
```ts filename="app/activity/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
```js filename="app/activity/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}
```
The optimistic query value updates the current screen. `updateTag` ensures the next cached server read returns fresh activity.
> **Good to know:** Call `updateTag` when a Server Action changes a cached read that must reflect the write immediately. An uncached read does not have a server tag to update. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching#coordinate-mutations) for other invalidation behaviors.
## Build a prerenderable hydration state
The TanStack Query pattern above uses `dehydrate()` to create the hydration state. With Cache Components, `dehydrate()` reads the current time (`Date.now()`) while prerendering and causes a [current-time prerender error](/docs/messages/blocking-prerender-current-time).
Instead, cache only that timestamp and build the dehydrated state by hand. Wrap the time read in [`use cache`](/docs/app/api-reference/directives/use-cache) with the same tags as the data reads. When a mutation invalidates those tags, the data and its timestamp advance together, so `<HydrationBoundary>` overwrites the client query on the next navigation:
```tsx filename="app/lib/hydrate.ts" switcher
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import {
defaultShouldDehydrateQuery,
QueryClient,
type DehydratedState,
type QueryKey,
} from '@tanstack/react-query'
type HydratedQuery = {
queryKey: QueryKey
data: unknown
}
type HydrationOptions = {
tags: string[]
}
async function getHydrationUpdatedAt(tags: string[]) {
'use cache'
cacheTag(...tags)
cacheLife('max')
return Date.now()
}
export async function dehydrate(
queries: HydratedQuery[],
options: HydrationOptions
): Promise<DehydratedState> {
const updatedAt = await getHydrationUpdatedAt(options.tags)
const queryClient = new QueryClient()
for (const query of queries) {
queryClient.setQueryData(query.queryKey, query.data, { updatedAt })
}
return {
mutations: [],
queries: queryClient
.getQueryCache()
.getAll()
.filter((query) => defaultShouldDehydrateQuery(query))
.map((query) => ({
dehydratedAt: updatedAt,
queryHash: query.queryHash,
queryKey: query.queryKey,
state: query.state,
...(query.meta ? { meta: query.meta } : {}),
})),
}
}
```
```js filename="app/lib/hydrate.js" switcher
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import { defaultShouldDehydrateQuery, QueryClient } from '@tanstack/react-query'
async function getHydrationUpdatedAt(tags) {
'use cache'
cacheTag(...tags)
cacheLife('max')
return Date.now()
}
export async function dehydrate(queries, options) {
const updatedAt = await getHydrationUpdatedAt(options.tags)
const queryClient = new QueryClient()
for (const query of queries) {
queryClient.setQueryData(query.queryKey, query.data, { updatedAt })
}
return {
mutations: [],
queries: queryClient
.getQueryCache()
.getAll()
.filter((query) => defaultShouldDehydrateQuery(query))
.map((query) => ({
dehydratedAt: updatedAt,
queryHash: query.queryHash,
queryKey: query.queryKey,
state: query.state,
...(query.meta ? { meta: query.meta } : {}),
})),
}
}
```
Await the helper in the segment that owns the data, passing the data and the same tags used on the underlying `getProduct` read. Hand the result to `<HydrationBoundary>` inside `ProductData`:
```tsx filename="app/products/[id]/page.tsx" switcher
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@/app/lib/hydrate'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
async function ProductData({ id }: { id: string }) {
const product = await getProduct(id)
const state = await dehydrate(
[{ queryKey: productCache.key(id), data: product }],
{ tags: [productCache.tag(id)] }
)
return (
<HydrationBoundary state={state}>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/products/[id]/page.js" switcher
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@/app/lib/hydrate'
import { getProduct } from './data'
import { productCache } from './product-cache'
import { ProductView } from './product-view'
async function ProductData({ id }) {
const product = await getProduct(id)
const state = await dehydrate(
[{ queryKey: productCache.key(id), data: product }],
{ tags: [productCache.tag(id)] }
)
return (
<HydrationBoundary state={state}>
<ProductView id={id} />
</HydrationBoundary>
)
}
```
> **Good to know:** The timestamp must advance whenever the hydrated data changes. The helper suits tag-driven server data because both use the same tags. For time-driven server data, derive the data and hydration timestamp from the same cached snapshot instead of maintaining unrelated time windows.
See the [live `next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev/react-query) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query). Learn more about [TanStack Query optimistic updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) and the [TanStack Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
---
title: The Server and Client Boundary
nav_title: Server and Client Boundary
description: Learn where Server and Client Components run in the App Router and how the boundary between them works.
related:
title: Next Steps
description: Learn how to apply this model and where the boundary is defined.
links:
- app/getting-started/server-and-client-components
- app/api-reference/directives/use-client
- app/getting-started/fetching-data
- app/guides/rendering-philosophy
---
React Server Components (RSC) split a component tree between server and client module graphs. This boundary determines where component code runs and whether that code ships to the browser. RSC keeps Server Components exclusively on the server and retains Client Components for interactive UI. Both compose in a single tree, which the server renders into the [RSC Payload](/docs/app/glossary#rsc-payload), a serialized description of the UI that carries references to the Client Components inside it.
Before RSC, React components followed what RSC now calls the Client Component model. React could render these components to HTML on the server, but the same code also shipped to the browser to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) that HTML. Hydration made the initial HTML interactive and required the component to produce matching output on the server and in the browser. Apps rendered entirely on the client could instead begin with an empty shell and mount the component tree in the browser.
```txt
Server Component
├─ Server Component
└─ Client Component
└─ Client Component
```
Each component's module belongs to the server [module graph](/docs/app/glossary#module-graph), the client module graph, or both. Next.js compiles a module used by both graphs separately for each environment.
During rendering, the server graph produces references to Client Components and serializes the props passed to them. The client graph does not import the server graph. The client graph receives the references and serialized props through the RSC Payload.
## Rendering environments
The component names suggest a clean split between server and browser, but rendering happens in both places. On the server, the Server Component tree produces the RSC Payload. Next.js uses the payload and Client Components to render HTML at build time or while handling a request.
When deciding where a component runs, consider both its server render and whether its code runs in the browser:
| | On the server | In the browser |
| -------------------- | ------------- | -------------- |
| **Server Component** | Yes | No |
| **Client Component** | Yes | Yes |
The word "Client" indicates that a Client Component also runs in the browser, alongside its server render.
On a direct visit, the following Client Component renders on the server and again in the browser during hydration. Its log appears in the terminal and the browser console. On a client-side navigation, the server sends the RSC Payload, and the component renders in the browser without server-rendered HTML.
```tsx filename="app/hello.tsx" switcher
'use client'
export default function Hello() {
console.log('Hello rendered') // on a direct visit: server, then browser
return <p>Hello</p>
}
```
```jsx filename="app/hello.js" switcher
'use client'
export default function Hello() {
console.log('Hello rendered') // on a direct visit: server, then browser
return <p>Hello</p>
}
```
Rendering a Client Component on the server produces HTML, but the component remains a Client Component.
Rendering Client Components to HTML predates RSC. Depending on the route, Next.js can generate or regenerate HTML:
- At build time with [Static Site Generation (SSG)](/docs/app/glossary#prerendering).
- After the build with [Incremental Static Regeneration (ISR)](/docs/app/glossary#incremental-static-regeneration-isr).
- For each request with server-side rendering (SSR).
RSC is a separate process that keeps Server Component code on the server and emits the RSC Payload instead of shipping that code. "Server-rendered" describes how Next.js produced the HTML. "Server Component" describes where the component code runs and whether that code ships to the browser.
> **Server Components and SEO**
>
> A crawler that reads only HTML sees the first response and runs none of your JavaScript. Both Server and Client Components contribute HTML to that response.
>
> SEO depends on whether the server render reaches the content. Content gated behind user interaction or an event does not appear in the HTML available to a crawler that does not run JavaScript.
See [Rendering Philosophy](/docs/app/guides/rendering-philosophy) for details about when a component renders, whether at build time or per request, statically or dynamically.
## How data enters the tree
Before RSC, Next.js applications typically gathered server data with functions such as `getStaticProps` or `getServerSideProps`, then passed it to the component tree as props. Data fetching happened before the tree rendered. The tree received data instead of fetching it during render.
```txt
Data
Loader or API
Props
Component tree
```
Because a Server Component runs only on the server, it can access resources such as a database, the filesystem, an internal service, or a secret. The component reads these resources during its own render, without an API route that exposes the data to the client first.
```tsx filename="app/page.tsx" switcher
import { PostList } from '@/app/ui/post-list'
import { getPosts } from '@/lib/data'
export default async function Page() {
const posts = await getPosts() // runs on the server, during render
return <PostList posts={posts} />
}
```
```jsx filename="app/page.js" switcher
import { PostList } from '@/app/ui/post-list'
import { getPosts } from '@/lib/data'
export default async function Page() {
const posts = await getPosts() // runs on the server, during render
return <PostList posts={posts} />
}
```
With RSC, a Server Component can fetch data while rendering. A separate data-loading step does not need to pass initial props to the component tree.
> **Good to know:** Because a Server Component can read secrets and server-only data directly, be deliberate about what you pass to Client Components.
>
> Props are serialized and sent to the browser. See [Data Security](/docs/app/guides/data-security#passing-data-from-server-to-client).
Server Components do not have to await all data before returning UI. To stream server-fetched data into a Client Component, start the request in a Server Component and pass the pending promise as a prop.
The Client Component reads the promise as a resource with [`use`](https://react.dev/reference/react/use#streaming-data-from-server-to-client). While the promise is pending, the nearest [Suspense](/docs/app/glossary#suspense-boundary) boundary shows its fallback. The Client Component renders when the promise resolves.
Because the request starts before the client runs, the Client Component does not need to fetch the same data after mount. You may still need to start a fetch in the browser when the requested data depends on client-only state or user interaction.
Identical `fetch` requests are [memoized during a server render](/docs/app/api-reference/functions/fetch#memoization). With [Cache Components](/docs/app/getting-started/caching), you can cache a data function or component and revalidate that entry independently of the rest of the page. For implementation patterns, see [Fetching Data](/docs/app/getting-started/fetching-data).
## State and interactivity
A Server Component's code never reaches the browser. The component can render again when Next.js renders the route, such as during a navigation, refresh, or after revalidation.
A Client Component's code does reach the browser. React hydrates the component on the initial load, and client-side updates can re-render it in the browser.
> **Good to know:** On the initial load, the RSC Payload ships with the HTML.
>
> Mutating Server Component DOM nodes directly can put the DOM out of sync with React's component tree.
>
> To update Server Component output, render the component again on the server. When the browser receives a new RSC Payload, React reconciles the component tree and updates the DOM. See [Streaming](/docs/app/guides/streaming#the-component-payload).
`useState`, `useEffect`, and event handlers require code that runs in the browser and responds to updates. Server Component code never reaches the browser, so it cannot use these client-side APIs.
Built-in browser and HTML behavior can provide interactivity without a Client Component. For example:
- A `<details>` element opens and closes.
- A `<form>` can submit through a [Server Function](/docs/app/guides/server-actions) passed to its `action` prop.
- A `<video controls>` element plays and pauses.
Use a Client Component when the behavior requires browser state that changes over time, such as a controlled input, live filter, or drag handle. A button or form does not require a Client Component when the browser provides all the required behavior.
For the practical list of what belongs in each environment, see [When to use Server and Client Components](/docs/app/getting-started/server-and-client-components#when-to-use-server-and-client-components).
## Crossing the boundary
You mark a Client Component with the [`'use client'`](/docs/app/api-reference/directives/use-client) directive. The directive draws a boundary in the module graph, and two rules determine what crosses it:
- **Code** crosses through imports. Whatever a Client Component imports is pulled into the [client bundle](/docs/app/glossary#client-bundles).
- **Data** crosses through props, and it must be [serializable](/docs/app/getting-started/server-and-client-components#passing-data-from-server-to-client-components), so functions like event handlers cannot cross.
> **Good to know:**
>
> Passing a function as a prop from a Server Component to a Client Component throws. An event handler like `onClick` cannot cross. A [Server Function](/docs/app/guides/server-actions) marked with `'use server'` crosses as a reference.
>
> A Server Function is not distinguishable from a plain function by its type. The TypeScript plugin allows a Client Component prop typed as a function when its name is `action` or ends in `Action`. The plugin flags other function props.
A rendered React element can cross the boundary because it is serializable data. Passing rendered output as `children` lets a Server Component nest inside a Client Component without importing the Server Component's code into the client graph.
```tsx filename="app/page.tsx" switcher
import { Cart } from '@/app/ui/cart'
import { Modal } from '@/app/ui/modal'
// Page and Cart are Server Components. Modal is a Client Component
export default function Page() {
return (
<Modal title={<div>Your cart</div>}>
<Cart />
</Modal>
)
}
```
```jsx filename="app/page.js" switcher
import { Cart } from '@/app/ui/cart'
import { Modal } from '@/app/ui/modal'
// Page and Cart are Server Components. Modal is a Client Component
export default function Page() {
return (
<Modal title={<div>Your cart</div>}>
<Cart />
</Modal>
)
}
```
The `children` prop behaves like any other prop. `Modal` receives `title` and `children` as serialized React elements, then renders them in the positions defined by its implementation.
```tsx filename="app/ui/modal.tsx" switcher
'use client'
import { useState, type ReactNode } from 'react'
export function Modal({
title,
children,
}: {
title: ReactNode
children: ReactNode
}) {
const [open, setOpen] = useState(true)
if (!open) return null
return (
<div role="dialog">
<header>
{title}
<button onClick={() => setOpen(false)}>Close</button>
</header>
{children}
</div>
)
}
```
```jsx filename="app/ui/modal.js" switcher
'use client'
import { useState } from 'react'
export function Modal({ title, children }) {
const [open, setOpen] = useState(true)
if (!open) return null
return (
<div role="dialog">
<header>
{title}
<button onClick={() => setOpen(false)}>Close</button>
</header>
{children}
</div>
)
}
```
Here, `Cart` runs on the server, and `Modal` only ever sees its output, never its code.
<details>
<summary>Owner and parent</summary>
In this example, `Page` shows two roles React keeps separate:
- The **owner** is the component whose source contains the JSX for a child. `Page` owns both `Modal` and `Cart`.
- The **parent** directly contains the child in the rendered tree. `Modal` is the parent of `Cart`.
Because `Cart`'s owner is a Server Component, `Cart` renders on the server. `Modal` is only the parent, so `Modal` receives `Cart`'s output to place but not its code to run. This separation lets a Client Component display a Server Component it never imported.
</details>
<details>
<summary>Compound components across the boundary</summary>
Compound components can expose subcomponents as static properties, such as `Menu.Item` or `Tabs.Panel`. This pattern works within one graph when all pieces are Server Components or all pieces are Client Components.
The pattern breaks when a static member crosses the boundary. A Server Component that imports a Client Component receives a client reference instead of the function. As a result, `Menu.Item` is `undefined`, and React throws "Element type is invalid."
Use a compound Client Component from another Client Component. To use its pieces from a Server Component, expose them as named exports instead of static properties.
</details>
You only need `'use client'` at the entry to a client subtree, not on every file inside it. Every module imported from that entry becomes part of the client module graph.
To leave a shared component unchanged, create a Client Component wrapper that imports it and place the directive on the wrapper. The wrapper keeps the shared module unchanged and puts the boundary closer to your application code. It also avoids adding the directive to every shared component that calls `useState` or `useEffect`.
If client code enters the server graph without a boundary, the compiler points to where you need the directive.
For more patterns, see [Interleaving Server and Client Components](/docs/app/getting-started/server-and-client-components#interleaving-server-and-client-components).
For the other directives used in Next.js, see the [directives](/docs/app/api-reference/directives) documentation.
+1
-2

@@ -23,3 +23,2 @@ "use strict";

const _generateroutesmanifest = require("../generate-routes-manifest");
const _ppr = require("../../server/lib/experimental/ppr");
const _apppaths = require("../../shared/lib/router/utils/app-paths");

@@ -177,3 +176,3 @@ const _nodehttp = /*#__PURE__*/ _interop_require_default(require("node:http"));

].map((pathPrefix)=>config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix);
const isAppPPREnabled = (0, _ppr.checkIsAppPPREnabled)(config.experimental.ppr);
const isAppPPREnabled = Boolean(config.cacheComponents);
// Generate routes manifest

@@ -180,0 +179,0 @@ const { routesManifest } = (0, _generateroutesmanifest.generateRoutesManifest)({

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/build/analyze/index.ts"],"sourcesContent":["import type { NextConfigComplete } from '../../server/config-shared'\nimport type { __ApiPreviewProps } from '../../server/api-utils'\n\nimport { setGlobal } from '../../trace'\nimport * as Log from '../output/log'\nimport * as path from 'node:path'\nimport loadConfig from '../../server/config'\nimport { PHASE_ANALYZE } from '../../shared/lib/constants'\nimport { turbopackAnalyze, type AnalyzeContext } from '../turbopack-analyze'\nimport { durationToString } from '../duration-to-string'\nimport { cp, writeFile, mkdir } from 'node:fs/promises'\nimport { discoverRoutes } from '../route-discovery'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport loadCustomRoutes from '../../lib/load-custom-routes'\nimport { generateRoutesManifest } from '../generate-routes-manifest'\nimport { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport http from 'node:http'\n\n// @ts-expect-error types are in @types/serve-handler\nimport serveHandler from 'next/dist/compiled/serve-handler'\nimport { Telemetry } from '../../telemetry/storage'\nimport { eventAnalyzeCompleted } from '../../telemetry/events'\nimport { traceGlobals } from '../../trace/shared'\nimport type { RoutesManifest } from '..'\nimport { Bundler } from '../../lib/bundler'\n\nexport type AnalyzeOptions = {\n dir: string\n reactProductionProfiling?: boolean\n noMangling?: boolean\n appDirOnly?: boolean\n output?: boolean\n port?: number\n}\n\nexport default async function analyze({\n dir,\n reactProductionProfiling = false,\n noMangling = false,\n appDirOnly = false,\n output = false,\n port = 4000,\n}: AnalyzeOptions): Promise<void> {\n try {\n // analyze is Turbopack-only. Mirror what parseBundlerArgs does for build/dev\n // so every process.env.TURBOPACK consumer in this run agrees with the bundler choice.\n process.env.TURBOPACK ??= '1'\n const config: NextConfigComplete = await loadConfig(PHASE_ANALYZE, dir, {\n silent: false,\n reactProductionProfiling,\n bundler: Bundler.Turbopack,\n })\n\n process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''\n\n const distDir = path.join(dir, '.next')\n const telemetry = new Telemetry({ distDir })\n setGlobal('phase', PHASE_ANALYZE)\n setGlobal('distDir', distDir)\n setGlobal('telemetry', telemetry)\n\n Log.info('Analyzing a production build...')\n\n const analyzeContext: AnalyzeContext = {\n config,\n dir,\n distDir,\n noMangling,\n appDirOnly,\n }\n\n const { duration: analyzeDuration, shutdownPromise } =\n await turbopackAnalyze(analyzeContext)\n\n const durationString = durationToString(analyzeDuration)\n const analyzeDir = path.join(distDir, 'diagnostics/analyze')\n\n await shutdownPromise\n\n const routes = await collectRoutesForAnalyze(dir, config, appDirOnly)\n\n await cp(path.join(__dirname, '../../bundle-analyzer'), analyzeDir, {\n recursive: true,\n })\n await mkdir(path.join(analyzeDir, 'data'), { recursive: true })\n await writeFile(\n path.join(analyzeDir, 'data', 'routes.json'),\n JSON.stringify(routes, null, 2)\n )\n\n let logMessage = `Analyze completed in ${durationString}.`\n if (output) {\n logMessage += ` Results written to ${analyzeDir}.\\nTo explore the analyze results interactively, run \\`next experimental-analyze\\` without \\`--output\\`.`\n }\n Log.event(logMessage)\n\n telemetry.record(\n eventAnalyzeCompleted({\n success: true,\n durationInSeconds: Math.round(analyzeDuration),\n totalPageCount: routes.length,\n })\n )\n\n if (!output) {\n await startServer(analyzeDir, port)\n }\n } catch (e) {\n const telemetry = traceGlobals.get('telemetry') as Telemetry | undefined\n if (telemetry) {\n telemetry.record(\n eventAnalyzeCompleted({\n success: false,\n })\n )\n }\n\n throw e\n }\n}\n\n/**\n * Collects all routes from the project for the bundle analyzer.\n * Returns a list of route paths (both static and dynamic).\n */\nasync function collectRoutesForAnalyze(\n dir: string,\n config: NextConfigComplete,\n appDirOnly: boolean\n): Promise<string[]> {\n const { pagesDir, appDir } = findPagesDir(dir)\n\n let appType: RoutesManifest['appType']\n if (pagesDir && appDir) {\n appType = 'hybrid'\n } else if (pagesDir) {\n appType = 'pages'\n } else if (appDir) {\n appType = 'app'\n } else {\n throw new Error('No pages or app directory found.')\n }\n\n const discovery = await discoverRoutes({\n appDir,\n pagesDir,\n pageExtensions: config.pageExtensions,\n isDev: false,\n baseDir: dir,\n isSrcDir: path.relative(dir, pagesDir || appDir || '').startsWith('src'),\n appDirOnly,\n })\n\n const pageKeys = {\n pages: Object.keys(discovery.mappedPages || {}),\n app: discovery.mappedAppPages\n ? Object.keys(discovery.mappedAppPages).map((key) =>\n normalizeAppPath(key)\n )\n : [],\n }\n\n // Load custom routes\n const { redirects, headers, onMatchHeaders, rewrites } =\n await loadCustomRoutes(config)\n\n // Compute restricted redirect paths\n const restrictedRedirectPaths = ['/_next'].map((pathPrefix) =>\n config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix\n )\n\n const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)\n\n // Generate routes manifest\n const { routesManifest } = generateRoutesManifest({\n appType,\n pageKeys,\n config,\n redirects,\n headers,\n onMatchHeaders,\n rewrites,\n restrictedRedirectPaths,\n isAppPPREnabled,\n })\n\n return routesManifest.dynamicRoutes\n .map((r) => r.page)\n .concat(routesManifest.staticRoutes.map((r) => r.page))\n}\n\nfunction startServer(dir: string, port: number): Promise<void> {\n const server = http.createServer((req, res) => {\n return serveHandler(req, res, {\n public: dir,\n })\n })\n\n return new Promise((resolve, reject) => {\n function onError(err: Error) {\n server.close(() => {\n reject(err)\n })\n }\n\n server.on('error', onError)\n\n server.listen(port, 'localhost', () => {\n const address = server.address()\n if (address == null) {\n reject(new Error('Unable to get server address'))\n return\n }\n\n // No longer needed after startup\n server.removeListener('error', onError)\n\n let addressString\n if (typeof address === 'string') {\n addressString = address\n } else if (\n address.family === 'IPv6' &&\n (address.address === '::' || address.address === '::1')\n ) {\n addressString = `localhost:${address.port}`\n } else if (address.family === 'IPv6') {\n addressString = `[${address.address}]:${address.port}`\n } else {\n addressString = `${address.address}:${address.port}`\n }\n\n Log.info(`Bundle analyzer available at http://${addressString}`)\n resolve()\n })\n })\n}\n"],"names":["analyze","dir","reactProductionProfiling","noMangling","appDirOnly","output","port","process","env","TURBOPACK","config","loadConfig","PHASE_ANALYZE","silent","bundler","Bundler","Turbopack","NEXT_DEPLOYMENT_ID","deploymentId","distDir","path","join","telemetry","Telemetry","setGlobal","Log","info","analyzeContext","duration","analyzeDuration","shutdownPromise","turbopackAnalyze","durationString","durationToString","analyzeDir","routes","collectRoutesForAnalyze","cp","__dirname","recursive","mkdir","writeFile","JSON","stringify","logMessage","event","record","eventAnalyzeCompleted","success","durationInSeconds","Math","round","totalPageCount","length","startServer","e","traceGlobals","get","pagesDir","appDir","findPagesDir","appType","Error","discovery","discoverRoutes","pageExtensions","isDev","baseDir","isSrcDir","relative","startsWith","pageKeys","pages","Object","keys","mappedPages","app","mappedAppPages","map","key","normalizeAppPath","redirects","headers","onMatchHeaders","rewrites","loadCustomRoutes","restrictedRedirectPaths","pathPrefix","basePath","isAppPPREnabled","checkIsAppPPREnabled","experimental","ppr","routesManifest","generateRoutesManifest","dynamicRoutes","r","page","concat","staticRoutes","server","http","createServer","req","res","serveHandler","public","Promise","resolve","reject","onError","err","close","on","listen","address","removeListener","addressString","family"],"mappings":";;;;+BAoCA;;;eAA8BA;;;uBAjCJ;6DACL;kEACC;+DACC;2BACO;kCACwB;kCACrB;0BACI;gCACN;8BACF;yEACA;wCACU;qBACF;0BACJ;iEAChB;qEAGQ;yBACC;wBACY;wBACT;yBAEL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWT,e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gBACnBN,OAAO,qBAAyC,CAAzC,IAAI/C,MAAM,iCAAV,qBAAA;2BAAA;gCAAA;kCAAA;gBAAwC;gBAC/C;YACF;YAEA,iCAAiC;YACjCsC,OAAOgB,cAAc,CAAC,SAASN;YAE/B,IAAIO;YACJ,IAAI,OAAOF,YAAY,UAAU;gBAC/BE,gBAAgBF;YAClB,OAAO,IACLA,QAAQG,MAAM,KAAK,UAClBH,CAAAA,QAAQA,OAAO,KAAK,QAAQA,QAAQA,OAAO,KAAK,KAAI,GACrD;gBACAE,gBAAgB,CAAC,UAAU,EAAEF,QAAQ7G,IAAI,EAAE;YAC7C,OAAO,IAAI6G,QAAQG,MAAM,KAAK,QAAQ;gBACpCD,gBAAgB,CAAC,CAAC,EAAEF,QAAQA,OAAO,CAAC,EAAE,EAAEA,QAAQ7G,IAAI,EAAE;YACxD,OAAO;gBACL+G,gBAAgB,GAAGF,QAAQA,OAAO,CAAC,CAAC,EAAEA,QAAQ7G,IAAI,EAAE;YACtD;YAEAmB,KAAIC,IAAI,CAAC,CAAC,oCAAoC,EAAE2F,eAAe;YAC/DT;QACF;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/build/analyze/index.ts"],"sourcesContent":["import type { NextConfigComplete } from '../../server/config-shared'\nimport type { __ApiPreviewProps } from '../../server/api-utils'\n\nimport { setGlobal } from '../../trace'\nimport * as Log from '../output/log'\nimport * as path from 'node:path'\nimport loadConfig from '../../server/config'\nimport { PHASE_ANALYZE } from '../../shared/lib/constants'\nimport { turbopackAnalyze, type AnalyzeContext } from '../turbopack-analyze'\nimport { durationToString } from '../duration-to-string'\nimport { cp, writeFile, mkdir } from 'node:fs/promises'\nimport { discoverRoutes } from '../route-discovery'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport loadCustomRoutes from '../../lib/load-custom-routes'\nimport { generateRoutesManifest } from '../generate-routes-manifest'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport http from 'node:http'\n\n// @ts-expect-error types are in @types/serve-handler\nimport serveHandler from 'next/dist/compiled/serve-handler'\nimport { Telemetry } from '../../telemetry/storage'\nimport { eventAnalyzeCompleted } from '../../telemetry/events'\nimport { traceGlobals } from '../../trace/shared'\nimport type { RoutesManifest } from '..'\nimport { Bundler } from '../../lib/bundler'\n\nexport type AnalyzeOptions = {\n dir: string\n reactProductionProfiling?: boolean\n noMangling?: boolean\n appDirOnly?: boolean\n output?: boolean\n port?: number\n}\n\nexport default async function analyze({\n dir,\n reactProductionProfiling = false,\n noMangling = false,\n appDirOnly = false,\n output = false,\n port = 4000,\n}: AnalyzeOptions): Promise<void> {\n try {\n // analyze is Turbopack-only. Mirror what parseBundlerArgs does for build/dev\n // so every process.env.TURBOPACK consumer in this run agrees with the bundler choice.\n process.env.TURBOPACK ??= '1'\n const config: NextConfigComplete = await loadConfig(PHASE_ANALYZE, dir, {\n silent: false,\n reactProductionProfiling,\n bundler: Bundler.Turbopack,\n })\n\n process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''\n\n const distDir = path.join(dir, '.next')\n const telemetry = new Telemetry({ distDir })\n setGlobal('phase', PHASE_ANALYZE)\n setGlobal('distDir', distDir)\n setGlobal('telemetry', telemetry)\n\n Log.info('Analyzing a production build...')\n\n const analyzeContext: AnalyzeContext = {\n config,\n dir,\n distDir,\n noMangling,\n appDirOnly,\n }\n\n const { duration: analyzeDuration, shutdownPromise } =\n await turbopackAnalyze(analyzeContext)\n\n const durationString = durationToString(analyzeDuration)\n const analyzeDir = path.join(distDir, 'diagnostics/analyze')\n\n await shutdownPromise\n\n const routes = await collectRoutesForAnalyze(dir, config, appDirOnly)\n\n await cp(path.join(__dirname, '../../bundle-analyzer'), analyzeDir, {\n recursive: true,\n })\n await mkdir(path.join(analyzeDir, 'data'), { recursive: true })\n await writeFile(\n path.join(analyzeDir, 'data', 'routes.json'),\n JSON.stringify(routes, null, 2)\n )\n\n let logMessage = `Analyze completed in ${durationString}.`\n if (output) {\n logMessage += ` Results written to ${analyzeDir}.\\nTo explore the analyze results interactively, run \\`next experimental-analyze\\` without \\`--output\\`.`\n }\n Log.event(logMessage)\n\n telemetry.record(\n eventAnalyzeCompleted({\n success: true,\n durationInSeconds: Math.round(analyzeDuration),\n totalPageCount: routes.length,\n })\n )\n\n if (!output) {\n await startServer(analyzeDir, port)\n }\n } catch (e) {\n const telemetry = traceGlobals.get('telemetry') as Telemetry | undefined\n if (telemetry) {\n telemetry.record(\n eventAnalyzeCompleted({\n success: false,\n })\n )\n }\n\n throw e\n }\n}\n\n/**\n * Collects all routes from the project for the bundle analyzer.\n * Returns a list of route paths (both static and dynamic).\n */\nasync function collectRoutesForAnalyze(\n dir: string,\n config: NextConfigComplete,\n appDirOnly: boolean\n): Promise<string[]> {\n const { pagesDir, appDir } = findPagesDir(dir)\n\n let appType: RoutesManifest['appType']\n if (pagesDir && appDir) {\n appType = 'hybrid'\n } else if (pagesDir) {\n appType = 'pages'\n } else if (appDir) {\n appType = 'app'\n } else {\n throw new Error('No pages or app directory found.')\n }\n\n const discovery = await discoverRoutes({\n appDir,\n pagesDir,\n pageExtensions: config.pageExtensions,\n isDev: false,\n baseDir: dir,\n isSrcDir: path.relative(dir, pagesDir || appDir || '').startsWith('src'),\n appDirOnly,\n })\n\n const pageKeys = {\n pages: Object.keys(discovery.mappedPages || {}),\n app: discovery.mappedAppPages\n ? Object.keys(discovery.mappedAppPages).map((key) =>\n normalizeAppPath(key)\n )\n : [],\n }\n\n // Load custom routes\n const { redirects, headers, onMatchHeaders, rewrites } =\n await loadCustomRoutes(config)\n\n // Compute restricted redirect paths\n const restrictedRedirectPaths = ['/_next'].map((pathPrefix) =>\n config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix\n )\n\n const isAppPPREnabled = Boolean(config.cacheComponents)\n\n // Generate routes manifest\n const { routesManifest } = generateRoutesManifest({\n appType,\n pageKeys,\n config,\n redirects,\n headers,\n onMatchHeaders,\n rewrites,\n restrictedRedirectPaths,\n isAppPPREnabled,\n })\n\n return routesManifest.dynamicRoutes\n .map((r) => r.page)\n .concat(routesManifest.staticRoutes.map((r) => r.page))\n}\n\nfunction startServer(dir: string, port: number): Promise<void> {\n const server = http.createServer((req, res) => {\n return serveHandler(req, res, {\n public: dir,\n })\n })\n\n return new Promise((resolve, reject) => {\n function onError(err: Error) {\n server.close(() => {\n reject(err)\n })\n }\n\n server.on('error', onError)\n\n server.listen(port, 'localhost', () => {\n const address = server.address()\n if (address == null) {\n reject(new Error('Unable to get server address'))\n return\n }\n\n // No longer needed after startup\n server.removeListener('error', onError)\n\n let addressString\n if (typeof address === 'string') {\n addressString = address\n } else if (\n address.family === 'IPv6' &&\n (address.address === '::' || address.address === '::1')\n ) {\n addressString = `localhost:${address.port}`\n } else if (address.family === 'IPv6') {\n addressString = `[${address.address}]:${address.port}`\n } else {\n addressString = `${address.address}:${address.port}`\n }\n\n Log.info(`Bundle analyzer available at http://${addressString}`)\n resolve()\n })\n })\n}\n"],"names":["analyze","dir","reactProductionProfiling","noMangling","appDirOnly","output","port","process","env","TURBOPACK","config","loadConfig","PHASE_ANALYZE","silent","bundler","Bundler","Turbopack","NEXT_DEPLOYMENT_ID","deploymentId","distDir","path","join","telemetry","Telemetry","setGlobal","Log","info","analyzeContext","duration","analyzeDuration","shutdownPromise","turbopackAnalyze","durationString","durationToString","analyzeDir","routes","collectRoutesForAnalyze","cp","__dirname","recursive","mkdir","writeFile","JSON","stringify","logMessage","event","record","eventAnalyzeCompleted","success","durationInSeconds","Math","round","totalPageCount","length","startServer","e","traceGlobals","get","pagesDir","appDir","findPagesDir","appType","Error","discovery","discoverRoutes","pageExtensions","isDev","baseDir","isSrcDir","relative","startsWith","pageKeys","pages","Object","keys","mappedPages","app","mappedAppPages","map","key","normalizeAppPath","redirects","headers","onMatchHeaders","rewrites","loadCustomRoutes","restrictedRedirectPaths","pathPrefix","basePath","isAppPPREnabled","Boolean","cacheComponents","routesManifest","generateRoutesManifest","dynamicRoutes","r","page","concat","staticRoutes","server","http","createServer","req","res","serveHandler","public","Promise","resolve","reject","onError","err","close","on","listen","address","removeListener","addressString","family"],"mappings":";;;;+BAmCA;;;eAA8BA;;;uBAhCJ;6DACL;kEACC;+DACC;2BACO;kCACwB;kCACrB;0BACI;gCACN;8BACF;yEACA;wCACU;0BACN;iEAChB;qEAGQ;yBACC;wBACY;wBACT;yBAEL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWT,eAAeA,QAAQ,EACpCC,GAAG,EACHC,2BAA2B,KAAK,EAChCC,aAAa,KAAK,EAClBC,aAAa,KAAK,EAClBC,SAAS,KAAK,EACdC,OAAO,IAAI,EACI;IACf,IAAI;QACF,6EAA6E;QAC7E,sFAAsF;QACtFC,QAAQC,GAAG,CAACC,SAAS,KAAK;QAC1B,MAAMC,SAA6B,MAAMC,IAAAA,eAAU,EAACC,wBAAa,EAAEX,KAAK;YACtEY,QAAQ;YACRX;YACAY,SAASC,gBAAO,CAACC,SAAS;QAC5B;QAEAT,QAAQC,GAAG,CAACS,kBAAkB,GAAGP,OAAOQ,YAAY,IAAI;QAExD,MAAMC,UAAUC,UAAKC,IAAI,CAACpB,KAAK;QAC/B,MAAMqB,YAAY,IAAIC,kBAAS,CAAC;YAAEJ;QAAQ;QAC1CK,IAAAA,gBAAS,EAAC,SAASZ,wBAAa;QAChCY,IAAAA,gBAAS,EAAC,WAAWL;QACrBK,IAAAA,gBAAS,EAAC,aAAaF;QAEvBG,KAAIC,IAAI,CAAC;QAET,MAAMC,iBAAiC;YACrCjB;YACAT;YACAkB;YACAhB;YACAC;QACF;QAEA,MAAM,EAAEwB,UAAUC,eAAe,EAAEC,eAAe,EAAE,GAClD,MAAMC,IAAAA,kCAAgB,EAACJ;QAEzB,MAAMK,iBAAiBC,IAAAA,kCAAgB,EAACJ;QACxC,MAAMK,aAAad,UAAKC,IAAI,CAACF,SAAS;QAEtC,MAAMW;QAEN,MAAMK,SAAS,MAAMC,wBAAwBnC,KAAKS,QAAQN;QAE1D,MAA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AO,IAAIyG,QAAQ,CAACC,SAASC;QAC3B,SAASC,QAAQC,GAAU;YACzBX,OAAOY,KAAK,CAAC;gBACXH,OAAOE;YACT;QACF;QAEAX,OAAOa,EAAE,CAAC,SAASH;QAEnBV,OAAOc,MAAM,CAAC3G,MAAM,aAAa;YAC/B,MAAM4G,UAAUf,OAAOe,OAAO;YAC9B,IAAIA,WAAW,MAAM;gBACnBN,OAAO,qBAAyC,CAAzC,IAAI9C,MAAM,iCAAV,qBAAA;2BAAA;gCAAA;kCAAA;gBAAwC;gBAC/C;YACF;YAEA,iCAAiC;YACjCqC,OAAOgB,cAAc,CAAC,SAASN;YAE/B,IAAIO;YACJ,IAAI,OAAOF,YAAY,UAAU;gBAC/BE,gBAAgBF;YAClB,OAAO,IACLA,QAAQG,MAAM,KAAK,UAClBH,CAAAA,QAAQA,OAAO,KAAK,QAAQA,QAAQA,OAAO,KAAK,KAAI,GACrD;gBACAE,gBAAgB,CAAC,UAAU,EAAEF,QAAQ5G,IAAI,EAAE;YAC7C,OAAO,IAAI4G,QAAQG,MAAM,KAAK,QAAQ;gBACpCD,gBAAgB,CAAC,CAAC,EAAEF,QAAQA,OAAO,CAAC,EAAE,EAAEA,QAAQ5G,IAAI,EAAE;YACxD,OAAO;gBACL8G,gBAAgB,GAAGF,QAAQA,OAAO,CAAC,CAAC,EAAEA,QAAQ5G,IAAI,EAAE;YACtD;YAEAmB,KAAIC,IAAI,CAAC,CAAC,oCAAoC,EAAE0F,eAAe;YAC/DT;QACF;IACF;AACF","ignoreList":[0]}

@@ -13,3 +13,2 @@ "use strict";

const _needsexperimentalreact = require("../lib/needs-experimental-react");
const _ppr = require("../server/lib/experimental/ppr");
const _staticenv = require("../lib/static-env");

@@ -56,3 +55,2 @@ function _interop_require_default(obj) {

const nextConfigEnv = (0, _staticenv.getNextConfigEnv)(config);
const isPPREnabled = (0, _ppr.checkIsAppPPREnabled)(config.experimental.ppr);
const isCacheComponentsEnabled = !!config.cacheComponents;

@@ -86,3 +84,2 @@ const isUseCacheEnabled = !!config.experimental.useCache;

'process.env.__NEXT_TURBOPACK_SHARED_RUNTIME': config.experimental.turbopackSharedRuntime !== false,
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,

@@ -89,0 +86,0 @@ 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(config.experimental.cachedNavigations),

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../src/build/define-env.ts"],"sourcesContent":["import type {\n I18NConfig,\n I18NDomains,\n NextConfigComplete,\n} from '../server/config-shared'\nimport type { ProxyMatcher } from './analysis/get-page-static-info'\nimport type { Rewrite } from '../lib/load-custom-routes'\nimport path from 'node:path'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'\nimport {\n getNextConfigEnv,\n getNextPublicEnvironmentVariables,\n} from '../lib/static-env'\n\ntype BloomFilter = ReturnType<\n import('../shared/lib/bloom-filter').BloomFilter['export']\n>\n\nexport interface DefineEnvOptions {\n isTurbopack: boolean\n clientRouterFilters?: {\n staticFilter: BloomFilter\n dynamicFilter: BloomFilter\n }\n config: NextConfigComplete\n dev: boolean\n distDir: string\n projectPath: string\n fetchCacheKeyPrefix: string | undefined\n hasRewrites: boolean\n isClient: boolean\n isEdgeServer: boolean\n isNodeServer: boolean\n middlewareMatchers: ProxyMatcher[] | undefined\n omitNonDeterministic?: boolean\n rewrites: {\n beforeFiles: Rewrite[]\n afterFiles: Rewrite[]\n fallback: Rewrite[]\n }\n}\n\nconst DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION')\n\ninterface DefineEnv {\n [key: string]:\n | string\n | number\n | string[]\n | boolean\n | { [DEFINE_ENV_EXPRESSION]: string }\n | ProxyMatcher[]\n | BloomFilter\n | Partial<NextConfigComplete['images']>\n | NextConfigComplete['cacheLife']\n | I18NDomains\n | I18NConfig\n}\n\ninterface SerializedDefineEnv {\n [key: string]: string\n}\n\n/**\n * Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.\n */\nfunction serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {\n const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(\n Object.entries(defineEnv).map(([key, value]) => [\n key,\n typeof value === 'object' && DEFINE_ENV_EXPRESSION in value\n ? value[DEFINE_ENV_EXPRESSION]\n : JSON.stringify(value),\n ])\n )\n return defineEnvStringified\n}\n\nfunction getImageConfig(\n config: NextConfigComplete,\n dev: boolean\n): { 'process.env.__NEXT_IMAGE_OPTS': Partial<NextConfigComplete['images']> } {\n return {\n 'process.env.__NEXT_IMAGE_OPTS': {\n deviceSizes: config.images.deviceSizes,\n imageSizes: config.images.imageSizes,\n qualities: config.images.qualities,\n path: config.images.path,\n loader: config.images.loader,\n dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,\n unoptimized: config?.images?.unoptimized,\n ...(dev\n ? {\n // additional config in dev to allow validating on the client\n domains: config.images.domains,\n remotePatterns: config.images?.remotePatterns,\n localPatterns: config.images?.localPatterns,\n output: config.output,\n }\n : {}),\n },\n }\n}\n\nexport function getDefineEnv({\n isTurbopack,\n clientRouterFilters,\n config,\n dev,\n distDir,\n projectPath,\n fetchCacheKeyPrefix,\n hasRewrites,\n isClient,\n isEdgeServer,\n isNodeServer,\n middlewareMatchers,\n omitNonDeterministic,\n rewrites,\n}: DefineEnvOptions): SerializedDefineEnv {\n const nextPublicEnv = getNextPublicEnvironmentVariables()\n const nextConfigEnv = getNextConfigEnv(config)\n\n const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)\n const isCacheComponentsEnabled = !!config.cacheComponents\n const isUseCacheEnabled = !!config.experimental.useCache\n\n const defineEnv: DefineEnv = {\n // internal field to identify the plugin config\n __NEXT_DEFINE_ENV: true,\n\n ...nextPublicEnv,\n ...nextConfigEnv,\n ...(!isEdgeServer\n ? {}\n : {\n EdgeRuntime:\n /**\n * Cloud providers can set this environment variable to allow users\n * and library authors to have different implementations based on\n * the runtime they are running with, if it's not using `edge-runtime`\n */\n process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? 'edge-runtime',\n\n // process should be only { env: {...} } for edge runtime.\n // For ignore avoid warn on `process.emit` usage but directly omit it.\n 'process.emit': false,\n }),\n 'process.turbopack': isTurbopack,\n 'process.env.TURBOPACK': isTurbopack,\n 'process.env.__NEXT_BUNDLER': isTurbopack\n ? 'Turbopack'\n : process.env.NEXT_RSPACK\n ? 'Rspack'\n : 'Webpack',\n // TODO: enforce `NODE_ENV` on `process.env`, and add a test:\n 'process.env.NODE_ENV':\n dev || config.experimental.allowDevelopmentBuild\n ? 'development'\n : 'production',\n 'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',\n 'process.env.__NEXT_DISABLE_DEV_OVERLAY_UX':\n process.env.NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX === '1',\n 'process.env.NEXT_RUNTIME': isEdgeServer\n ? 'edge'\n : isNodeServer\n ? 'nodejs'\n : '',\n 'process.env.NEXT_MINIMAL': '',\n 'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(\n config.experimental.appNavFailHandling\n ),\n 'process.env.__NEXT_TURBOPACK_SHARED_RUNTIME':\n config.experimental.turbopackSharedRuntime !== false,\n 'process.env.__NEXT_PPR': isPPREnabled,\n 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(\n config.experimental.cachedNavigations\n ),\n 'process.env.__NEXT_INSTANT_NAV_TOGGLE': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_COLD_CACHE_BADGE': Boolean(\n config.experimental.coldCacheBadge\n ),\n 'process.env.__NEXT_REQUEST_INSIGHTS':\n dev && !!config.experimental.requestInsights,\n 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,\n 'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true,\n\n 'process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS':\n config.supportsImmutableAssets || false,\n\n ...(config.experimental?.useSkewCookie || !config.deploymentId\n ? {\n 'process.env.NEXT_DEPLOYMENT_ID': false,\n }\n : isClient\n ? isTurbopack\n ? {\n // This is set at runtime by packages/next/src/client/register-deployment-id-global.ts\n 'process.env.NEXT_DEPLOYMENT_ID': {\n [DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID',\n },\n }\n : {\n // For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID\n // approach because we cannot forward this global variable to web workers easily.\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }\n : config.experimental?.runtimeServerDeploymentId\n ? {\n // Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is\n }\n : {\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }),\n\n // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment\n // variable to the client.\n 'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':\n process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING || false,\n 'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',\n ...(isTurbopack\n ? {}\n : {\n 'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],\n }),\n 'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH':\n config.experimental.manualClientBasePath ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.dynamic))\n ? 0\n : config.experimental.staleTimes?.dynamic\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.static))\n ? 5 * 60 // 5 minutes\n : config.experimental.staleTimes?.static\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':\n config.experimental.clientRouterFilter ?? true,\n 'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':\n clientRouterFilters?.staticFilter ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_D_FILTER':\n clientRouterFilters?.dynamicFilter ?? false,\n 'process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS': Boolean(\n config.experimental.validateRSCRequestHeaders\n ),\n 'process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION': Boolean(\n config.experimental.serverComponentsHmrCancellation\n ),\n 'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(\n config.experimental.dynamicOnHover\n ),\n 'process.env.__NEXT_USE_OFFLINE': Boolean(config.experimental.useOffline),\n 'process.env.__NEXT_PREFETCH_INLINING': Boolean(\n config.experimental.prefetchInlining\n ),\n 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':\n config.experimental.optimisticClientCache ?? true,\n 'process.env.__NEXT_MIDDLEWARE_PREFETCH':\n config.experimental.proxyPrefetch ?? 'flexible',\n 'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,\n 'process.browser': isClient,\n 'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,\n // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory\n ...(dev && (isClient ?? isEdgeServer)\n ? {\n 'process.env.__NEXT_DIST_DIR': distDir,\n }\n : {}),\n // This is used in devtools to strip the project path in edge runtime,\n // as there's only a dummy `dir` value (`.`) as edge runtime doesn't have concept of file system.\n ...(dev && isEdgeServer\n ? {\n 'process.env.__NEXT_EDGE_PROJECT_DIR': isTurbopack\n ? path.relative(process.cwd(), projectPath)\n : projectPath,\n }\n : {}),\n 'process.env.__NEXT_BASE_PATH': config.basePath,\n 'process.env.__NEXT_CASE_SENSITIVE_ROUTES': Boolean(\n config.experimental.caseSensitiveRoutes\n ),\n 'process.env.__NEXT_REWRITES': rewrites as any,\n 'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,\n 'process.env.__NEXT_DEV_INDICATOR': config.devIndicators !== false,\n 'process.env.__NEXT_DEV_INDICATOR_POSITION':\n config.devIndicators === false\n ? 'bottom-left' // This will not be used as the indicator is disabled.\n : (config.devIndicators.position ?? 'bottom-left'),\n 'process.env.__NEXT_STRICT_MODE':\n config.reactStrictMode === null ? false : config.reactStrictMode,\n 'process.env.__NEXT_STRICT_MODE_APP':\n // When next.config.js does not have reactStrictMode it's enabled by default.\n config.reactStrictMode === null ? true : config.reactStrictMode,\n 'process.env.__NEXT_OPTIMIZE_CSS':\n (config.experimental.optimizeCss && !dev) ?? false,\n 'process.env.__NEXT_SCRIPT_WORKERS':\n (config.experimental.nextScriptWorkers && !dev) ?? false,\n 'process.env.__NEXT_SCROLL_RESTORATION':\n config.experimental.scrollRestoration ?? false,\n ...getImageConfig(config, dev),\n 'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,\n 'process.env.__NEXT_HAS_REWRITES': hasRewrites,\n 'process.env.__NEXT_CONFIG_OUTPUT': config.output || '',\n 'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,\n 'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,\n 'process.env.__NEXT_I18N_CONFIG': config.i18n || '',\n 'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':\n config.skipProxyUrlNormalize,\n 'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':\n config.experimental.externalProxyRewritesResolve ?? false,\n 'process.env.__NEXT_MANUAL_TRAILING_SLASH':\n config.skipTrailingSlashRedirect,\n 'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':\n (config.experimental.webVitalsAttribution &&\n config.experimental.webVitalsAttribution.length > 0) ??\n false,\n 'process.env.__NEXT_WEB_VITALS_ATTRIBUTION':\n config.experimental.webVitalsAttribution ?? false,\n 'process.env.__NEXT_LINK_NO_TOUCH_START':\n config.experimental.linkNoTouchStart ?? false,\n 'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,\n 'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':\n !!config.experimental.authInterrupts,\n 'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(\n process.env.NEXT_TELEMETRY_DISABLED\n ),\n ...(isNodeServer || isEdgeServer\n ? {\n // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)\n // This is typically found in unmaintained modules from the\n // pre-webpack era (common in server-side code)\n 'global.GENTLY': false,\n }\n : undefined),\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_EXPERIMENTAL_REACT':\n needsExperimentalReact(config),\n }\n : undefined),\n\n 'process.env.__NEXT_MULTI_ZONE_DRAFT_MODE':\n config.experimental.multiZoneDraftMode ?? false,\n 'process.env.__NEXT_TRUST_HOST_HEADER':\n config.experimental.trustHostHeader ?? false,\n 'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':\n config.experimental.allowedRevalidateHeaderKeys ?? [],\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,\n 'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(\n process.cwd(),\n projectPath\n ),\n }\n : {}),\n\n 'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(\n (config.logging && config.logging.browserToTerminal) || false\n ),\n 'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,\n\n // The devtools need to know whether or not to show an option to clear the\n // bundler cache. This option may be removed later once Turbopack's\n // filesystem cache feature is more stable.\n //\n // This environment value is currently best-effort:\n // - It's possible to disable the webpack filesystem cache, but it's\n // unlikely for a user to do that.\n // - Rspack's filesystem cache is unstable and requires a different\n // configuration than webpack to enable (which we don't do).\n //\n // In the worst case we'll show an option to clear the cache, but it'll be a\n // no-op that just restarts the development server.\n 'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE':\n !isTurbopack ||\n (config.experimental.turbopackFileSystemCacheForDev ?? false),\n 'process.env.__NEXT_REACT_DEBUG_CHANNEL':\n config.experimental.reactDebugChannel ?? false,\n 'process.env.__NEXT_TRANSITION_INDICATOR':\n config.experimental.transitionIndicator ?? false,\n 'process.env.__NEXT_GESTURE_TRANSITION':\n config.experimental.gestureTransition ?? false,\n 'process.env.__NEXT_OPTIMISTIC_ROUTING':\n config.experimental.optimisticRouting ?? false,\n 'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':\n config.experimental.instrumentationClientRouterTransitionEvents ?? false,\n 'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,\n 'process.env.__NEXT_EXPOSE_TESTING_API':\n isCacheComponentsEnabled &&\n (dev || config.experimental.exposeTestingApiInProductionBuild === true),\n 'process.env.__NEXT_CACHE_LIFE': config.cacheLife,\n 'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':\n config.experimental.clientParamParsingOrigins || [],\n }\n\n const userDefines = config.compiler?.define ?? {}\n for (const key in userDefines) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.define\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefines[key]\n }\n\n if (isNodeServer || isEdgeServer) {\n const userDefinesServer = config.compiler?.defineServer ?? {}\n for (const key in userDefinesServer) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.defineServer\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefinesServer[key]\n }\n }\n\n const serializedDefineEnv = serializeDefineEnv(defineEnv)\n\n // we delay inlining these values until after the build\n // with flying shuttle enabled so we can update them\n // without invalidating entries\n if (!dev && omitNonDeterministic) {\n // client uses window. instead of leaving process.env\n // in case process isn't polyfilled on client already\n // since by this point it won't be added by webpack\n const safeKey = (key: string) =>\n isClient ? `window.${key.split('.').pop()}` : key\n\n for (const key in nextPublicEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n for (const key in nextConfigEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n if (!config.experimental.runtimeServerDeploymentId) {\n for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {\n serializedDefineEnv[key] = safeKey(key)\n }\n }\n }\n\n return serializedDefineEnv\n}\n"],"names":["getDefineEnv","DEFINE_ENV_EXPRESSION","Symbol","serializeDefineEnv","defineEnv","defineEnvStringified","Object","fromEntries","entries","map","key","value","JSON","stringify","getImageConfig","config","dev","deviceSizes","images","imageSizes","qualities","path","loader","dangerouslyAllowSVG","unoptimized","domains","remotePatterns","localPatterns","output","isTurbopack","clientRouterFilters","distDir","projectPath","fetchCacheKeyPrefix","hasRewrites","isClient","isEdgeServer","isNodeServer","middlewareMatchers","omitNonDeterministic","rewrites","nextPublicEnv","getNextPublicEnvironmentVariables","nextConfigEnv","getNextConfigEnv","isPPREnabled","checkIsAppPPREnabled","experimental","ppr","isCacheComponentsEnabled","cacheComponents","isUseCacheEnabled","useCache","__NEXT_DEFINE_ENV","EdgeRuntime","process","env","NEXT_EDGE_RUNTIME_PROVIDER","NEXT_RSPACK","allowDevelopmentBuild","NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX","Boolean","appNavFailHandling","turbopackSharedRuntime","cachedNavigations","coldCacheBadge","requestInsights","supportsImmutableAssets","useSkewCookie","deploymentId","runtimeServerDeploymentId","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","manualClientBasePath","isNaN","Number","staleTimes","dynamic","static","clientRouterFilter","staticFilter","dynamicFilter","validateRSCRequestHeaders","serverComponentsHmrCancellation","dynamicOnHover","useOffline","prefetchInlining","optimisticClientCache","proxyPrefetch","crossOrigin","__NEXT_TEST_MODE","relative","cwd","basePath","caseSensitiveRoutes","trailingSlash","devIndicators","position","reactStrictMode","optimizeCss","nextScriptWorkers","scrollRestoration","i18n","skipProxyUrlNormalize","externalProxyRewritesResolve","skipTrailingSlashRedirect","webVitalsAttribution","length","linkNoTouchStart","assetPrefix","authInterrupts","NEXT_TELEMETRY_DISABLED","undefined","needsExperimentalReact","multiZoneDraftMode","trustHostHeader","allowedRevalidateHeaderKeys","logging","browserToTerminal","mcpServer","turbopackFileSystemCacheForDev","reactDebugChannel","transitionIndicator","gestureTransition","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","exposeTestingApiInProductionBuild","cacheLife","clientParamParsingOrigins","userDefines","compiler","define","hasOwnProperty","Error","userDefinesServer","defineServer","serializedDefineEnv","safeKey","split","pop"],"mappings":";;;;+BAyGgBA;;;eAAAA;;;iEAlGC;wCACsB;qBACF;2BAI9B;;;;;;AA8BP,MAAMC,wBAAwBC,OAAO;AAqBrC;;CAEC,GACD,SAASC,mBAAmBC,SAAoB;IAC9C,MAAMC,uBAA4CC,OAAOC,WAAW,CAClED,OAAOE,OAAO,CAACJ,WAAWK,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAC9CD;YACA,OAAOC,UAAU,YAAYV,yBAAyBU,QAClDA,KAAK,CAACV,sBAAsB,GAC5BW,KAAKC,SAAS,CAACF;SACpB;IAEH,OAAON;AACT;AAEA,SAASS,eACPC,MAA0B,EAC1BC,GAAY;QAUKD,gBAKSA,iBACDA;IAdzB,OAAO;QACL,iCAAiC;YAC/BE,aAAaF,OAAOG,MAAM,CAACD,WAAW;YACtCE,YAAYJ,OAAOG,MAAM,CAACC,UAAU;YACpCC,WAAWL,OAAOG,MAAM,CAACE,SAAS;YAClCC,MAAMN,OAAOG,MAAM,CAACG,IAAI;YACxBC,QAAQP,OAAOG,MAAM,CAACI,MAAM;YAC5BC,qBAAqBR,OAAOG,MAAM,CAACK,mBAAmB;YACtDC,WAAW,EAAET,2BAAAA,iBAAAA,OAAQG,MAAM,qBAAdH,eAAgBS,WAAW;YACxC,GAAIR,MACA;gBACE,6DAA6D;gBAC7DS,SAASV,OAAOG,MAAM,CAACO,OAAO;gBA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;QACnD,MAAMkG,UAAU,CAAC/H,MACfyB,WAAW,CAAC,OAAO,EAAEzB,IAAIgI,KAAK,CAAC,KAAKC,GAAG,IAAI,GAAGjI;QAEhD,IAAK,MAAMA,OAAO+B,cAAe;YAC/B+F,mBAAmB,CAAC9H,IAAI,GAAG+H,QAAQ/H;QACrC;QACA,IAAK,MAAMA,OAAOiC,cAAe;YAC/B6F,mBAAmB,CAAC9H,IAAI,GAAG+H,QAAQ/H;QACrC;QACA,IAAI,CAACK,OAAOgC,YAAY,CAACuB,yBAAyB,EAAE;YAClD,KAAK,MAAM5D,OAAO;gBAAC;aAAiC,CAAE;gBACpD8H,mBAAmB,CAAC9H,IAAI,GAAG+H,QAAQ/H;YACrC;QACF;IACF;IAEA,OAAO8H;AACT","ignoreList":[0]}
{"version":3,"sources":["../../src/build/define-env.ts"],"sourcesContent":["import type {\n I18NConfig,\n I18NDomains,\n NextConfigComplete,\n} from '../server/config-shared'\nimport type { ProxyMatcher } from './analysis/get-page-static-info'\nimport type { Rewrite } from '../lib/load-custom-routes'\nimport path from 'node:path'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport {\n getNextConfigEnv,\n getNextPublicEnvironmentVariables,\n} from '../lib/static-env'\n\ntype BloomFilter = ReturnType<\n import('../shared/lib/bloom-filter').BloomFilter['export']\n>\n\nexport interface DefineEnvOptions {\n isTurbopack: boolean\n clientRouterFilters?: {\n staticFilter: BloomFilter\n dynamicFilter: BloomFilter\n }\n config: NextConfigComplete\n dev: boolean\n distDir: string\n projectPath: string\n fetchCacheKeyPrefix: string | undefined\n hasRewrites: boolean\n isClient: boolean\n isEdgeServer: boolean\n isNodeServer: boolean\n middlewareMatchers: ProxyMatcher[] | undefined\n omitNonDeterministic?: boolean\n rewrites: {\n beforeFiles: Rewrite[]\n afterFiles: Rewrite[]\n fallback: Rewrite[]\n }\n}\n\nconst DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION')\n\ninterface DefineEnv {\n [key: string]:\n | string\n | number\n | string[]\n | boolean\n | { [DEFINE_ENV_EXPRESSION]: string }\n | ProxyMatcher[]\n | BloomFilter\n | Partial<NextConfigComplete['images']>\n | NextConfigComplete['cacheLife']\n | I18NDomains\n | I18NConfig\n}\n\ninterface SerializedDefineEnv {\n [key: string]: string\n}\n\n/**\n * Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.\n */\nfunction serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {\n const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(\n Object.entries(defineEnv).map(([key, value]) => [\n key,\n typeof value === 'object' && DEFINE_ENV_EXPRESSION in value\n ? value[DEFINE_ENV_EXPRESSION]\n : JSON.stringify(value),\n ])\n )\n return defineEnvStringified\n}\n\nfunction getImageConfig(\n config: NextConfigComplete,\n dev: boolean\n): { 'process.env.__NEXT_IMAGE_OPTS': Partial<NextConfigComplete['images']> } {\n return {\n 'process.env.__NEXT_IMAGE_OPTS': {\n deviceSizes: config.images.deviceSizes,\n imageSizes: config.images.imageSizes,\n qualities: config.images.qualities,\n path: config.images.path,\n loader: config.images.loader,\n dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,\n unoptimized: config?.images?.unoptimized,\n ...(dev\n ? {\n // additional config in dev to allow validating on the client\n domains: config.images.domains,\n remotePatterns: config.images?.remotePatterns,\n localPatterns: config.images?.localPatterns,\n output: config.output,\n }\n : {}),\n },\n }\n}\n\nexport function getDefineEnv({\n isTurbopack,\n clientRouterFilters,\n config,\n dev,\n distDir,\n projectPath,\n fetchCacheKeyPrefix,\n hasRewrites,\n isClient,\n isEdgeServer,\n isNodeServer,\n middlewareMatchers,\n omitNonDeterministic,\n rewrites,\n}: DefineEnvOptions): SerializedDefineEnv {\n const nextPublicEnv = getNextPublicEnvironmentVariables()\n const nextConfigEnv = getNextConfigEnv(config)\n\n const isCacheComponentsEnabled = !!config.cacheComponents\n const isUseCacheEnabled = !!config.experimental.useCache\n\n const defineEnv: DefineEnv = {\n // internal field to identify the plugin config\n __NEXT_DEFINE_ENV: true,\n\n ...nextPublicEnv,\n ...nextConfigEnv,\n ...(!isEdgeServer\n ? {}\n : {\n EdgeRuntime:\n /**\n * Cloud providers can set this environment variable to allow users\n * and library authors to have different implementations based on\n * the runtime they are running with, if it's not using `edge-runtime`\n */\n process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? 'edge-runtime',\n\n // process should be only { env: {...} } for edge runtime.\n // For ignore avoid warn on `process.emit` usage but directly omit it.\n 'process.emit': false,\n }),\n 'process.turbopack': isTurbopack,\n 'process.env.TURBOPACK': isTurbopack,\n 'process.env.__NEXT_BUNDLER': isTurbopack\n ? 'Turbopack'\n : process.env.NEXT_RSPACK\n ? 'Rspack'\n : 'Webpack',\n // TODO: enforce `NODE_ENV` on `process.env`, and add a test:\n 'process.env.NODE_ENV':\n dev || config.experimental.allowDevelopmentBuild\n ? 'development'\n : 'production',\n 'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',\n 'process.env.__NEXT_DISABLE_DEV_OVERLAY_UX':\n process.env.NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX === '1',\n 'process.env.NEXT_RUNTIME': isEdgeServer\n ? 'edge'\n : isNodeServer\n ? 'nodejs'\n : '',\n 'process.env.NEXT_MINIMAL': '',\n 'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(\n config.experimental.appNavFailHandling\n ),\n 'process.env.__NEXT_TURBOPACK_SHARED_RUNTIME':\n config.experimental.turbopackSharedRuntime !== false,\n 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(\n config.experimental.cachedNavigations\n ),\n 'process.env.__NEXT_INSTANT_NAV_TOGGLE': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_COLD_CACHE_BADGE': Boolean(\n config.experimental.coldCacheBadge\n ),\n 'process.env.__NEXT_REQUEST_INSIGHTS':\n dev && !!config.experimental.requestInsights,\n 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,\n 'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true,\n\n 'process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS':\n config.supportsImmutableAssets || false,\n\n ...(config.experimental?.useSkewCookie || !config.deploymentId\n ? {\n 'process.env.NEXT_DEPLOYMENT_ID': false,\n }\n : isClient\n ? isTurbopack\n ? {\n // This is set at runtime by packages/next/src/client/register-deployment-id-global.ts\n 'process.env.NEXT_DEPLOYMENT_ID': {\n [DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID',\n },\n }\n : {\n // For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID\n // approach because we cannot forward this global variable to web workers easily.\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }\n : config.experimental?.runtimeServerDeploymentId\n ? {\n // Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is\n }\n : {\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }),\n\n // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment\n // variable to the client.\n 'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':\n process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING || false,\n 'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',\n ...(isTurbopack\n ? {}\n : {\n 'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],\n }),\n 'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH':\n config.experimental.manualClientBasePath ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.dynamic))\n ? 0\n : config.experimental.staleTimes?.dynamic\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.static))\n ? 5 * 60 // 5 minutes\n : config.experimental.staleTimes?.static\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':\n config.experimental.clientRouterFilter ?? true,\n 'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':\n clientRouterFilters?.staticFilter ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_D_FILTER':\n clientRouterFilters?.dynamicFilter ?? false,\n 'process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS': Boolean(\n config.experimental.validateRSCRequestHeaders\n ),\n 'process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION': Boolean(\n config.experimental.serverComponentsHmrCancellation\n ),\n 'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(\n config.experimental.dynamicOnHover\n ),\n 'process.env.__NEXT_USE_OFFLINE': Boolean(config.experimental.useOffline),\n 'process.env.__NEXT_PREFETCH_INLINING': Boolean(\n config.experimental.prefetchInlining\n ),\n 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':\n config.experimental.optimisticClientCache ?? true,\n 'process.env.__NEXT_MIDDLEWARE_PREFETCH':\n config.experimental.proxyPrefetch ?? 'flexible',\n 'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,\n 'process.browser': isClient,\n 'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,\n // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory\n ...(dev && (isClient ?? isEdgeServer)\n ? {\n 'process.env.__NEXT_DIST_DIR': distDir,\n }\n : {}),\n // This is used in devtools to strip the project path in edge runtime,\n // as there's only a dummy `dir` value (`.`) as edge runtime doesn't have concept of file system.\n ...(dev && isEdgeServer\n ? {\n 'process.env.__NEXT_EDGE_PROJECT_DIR': isTurbopack\n ? path.relative(process.cwd(), projectPath)\n : projectPath,\n }\n : {}),\n 'process.env.__NEXT_BASE_PATH': config.basePath,\n 'process.env.__NEXT_CASE_SENSITIVE_ROUTES': Boolean(\n config.experimental.caseSensitiveRoutes\n ),\n 'process.env.__NEXT_REWRITES': rewrites as any,\n 'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,\n 'process.env.__NEXT_DEV_INDICATOR': config.devIndicators !== false,\n 'process.env.__NEXT_DEV_INDICATOR_POSITION':\n config.devIndicators === false\n ? 'bottom-left' // This will not be used as the indicator is disabled.\n : (config.devIndicators.position ?? 'bottom-left'),\n 'process.env.__NEXT_STRICT_MODE':\n config.reactStrictMode === null ? false : config.reactStrictMode,\n 'process.env.__NEXT_STRICT_MODE_APP':\n // When next.config.js does not have reactStrictMode it's enabled by default.\n config.reactStrictMode === null ? true : config.reactStrictMode,\n 'process.env.__NEXT_OPTIMIZE_CSS':\n (config.experimental.optimizeCss && !dev) ?? false,\n 'process.env.__NEXT_SCRIPT_WORKERS':\n (config.experimental.nextScriptWorkers && !dev) ?? false,\n 'process.env.__NEXT_SCROLL_RESTORATION':\n config.experimental.scrollRestoration ?? false,\n ...getImageConfig(config, dev),\n 'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,\n 'process.env.__NEXT_HAS_REWRITES': hasRewrites,\n 'process.env.__NEXT_CONFIG_OUTPUT': config.output || '',\n 'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,\n 'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,\n 'process.env.__NEXT_I18N_CONFIG': config.i18n || '',\n 'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':\n config.skipProxyUrlNormalize,\n 'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':\n config.experimental.externalProxyRewritesResolve ?? false,\n 'process.env.__NEXT_MANUAL_TRAILING_SLASH':\n config.skipTrailingSlashRedirect,\n 'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':\n (config.experimental.webVitalsAttribution &&\n config.experimental.webVitalsAttribution.length > 0) ??\n false,\n 'process.env.__NEXT_WEB_VITALS_ATTRIBUTION':\n config.experimental.webVitalsAttribution ?? false,\n 'process.env.__NEXT_LINK_NO_TOUCH_START':\n config.experimental.linkNoTouchStart ?? false,\n 'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,\n 'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':\n !!config.experimental.authInterrupts,\n 'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(\n process.env.NEXT_TELEMETRY_DISABLED\n ),\n ...(isNodeServer || isEdgeServer\n ? {\n // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)\n // This is typically found in unmaintained modules from the\n // pre-webpack era (common in server-side code)\n 'global.GENTLY': false,\n }\n : undefined),\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_EXPERIMENTAL_REACT':\n needsExperimentalReact(config),\n }\n : undefined),\n\n 'process.env.__NEXT_MULTI_ZONE_DRAFT_MODE':\n config.experimental.multiZoneDraftMode ?? false,\n 'process.env.__NEXT_TRUST_HOST_HEADER':\n config.experimental.trustHostHeader ?? false,\n 'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':\n config.experimental.allowedRevalidateHeaderKeys ?? [],\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,\n 'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(\n process.cwd(),\n projectPath\n ),\n }\n : {}),\n\n 'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(\n (config.logging && config.logging.browserToTerminal) || false\n ),\n 'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,\n\n // The devtools need to know whether or not to show an option to clear the\n // bundler cache. This option may be removed later once Turbopack's\n // filesystem cache feature is more stable.\n //\n // This environment value is currently best-effort:\n // - It's possible to disable the webpack filesystem cache, but it's\n // unlikely for a user to do that.\n // - Rspack's filesystem cache is unstable and requires a different\n // configuration than webpack to enable (which we don't do).\n //\n // In the worst case we'll show an option to clear the cache, but it'll be a\n // no-op that just restarts the development server.\n 'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE':\n !isTurbopack ||\n (config.experimental.turbopackFileSystemCacheForDev ?? false),\n 'process.env.__NEXT_REACT_DEBUG_CHANNEL':\n config.experimental.reactDebugChannel ?? false,\n 'process.env.__NEXT_TRANSITION_INDICATOR':\n config.experimental.transitionIndicator ?? false,\n 'process.env.__NEXT_GESTURE_TRANSITION':\n config.experimental.gestureTransition ?? false,\n 'process.env.__NEXT_OPTIMISTIC_ROUTING':\n config.experimental.optimisticRouting ?? false,\n 'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':\n config.experimental.instrumentationClientRouterTransitionEvents ?? false,\n 'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,\n 'process.env.__NEXT_EXPOSE_TESTING_API':\n isCacheComponentsEnabled &&\n (dev || config.experimental.exposeTestingApiInProductionBuild === true),\n 'process.env.__NEXT_CACHE_LIFE': config.cacheLife,\n 'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':\n config.experimental.clientParamParsingOrigins || [],\n }\n\n const userDefines = config.compiler?.define ?? {}\n for (const key in userDefines) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.define\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefines[key]\n }\n\n if (isNodeServer || isEdgeServer) {\n const userDefinesServer = config.compiler?.defineServer ?? {}\n for (const key in userDefinesServer) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.defineServer\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefinesServer[key]\n }\n }\n\n const serializedDefineEnv = serializeDefineEnv(defineEnv)\n\n // we delay inlining these values until after the build\n // with flying shuttle enabled so we can update them\n // without invalidating entries\n if (!dev && omitNonDeterministic) {\n // client uses window. instead of leaving process.env\n // in case process isn't polyfilled on client already\n // since by this point it won't be added by webpack\n const safeKey = (key: string) =>\n isClient ? `window.${key.split('.').pop()}` : key\n\n for (const key in nextPublicEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n for (const key in nextConfigEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n if (!config.experimental.runtimeServerDeploymentId) {\n for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {\n serializedDefineEnv[key] = safeKey(key)\n }\n }\n }\n\n return serializedDefineEnv\n}\n"],"names":["getDefineEnv","DEFINE_ENV_EXPRESSION","Symbol","serializeDefineEnv","defineEnv","defineEnvStringified","Object","fromEntries","entries","map","key","value","JSON","stringify","getImageConfig","config","dev","deviceSizes","images","imageSizes","qualities","path","loader","dangerouslyAllowSVG","unoptimized","domains","remotePatterns","localPatterns","output","isTurbopack","clientRouterFilters","distDir","projectPath","fetchCacheKeyPrefix","hasRewrites","isClient","isEdgeServer","isNodeServer","middlewareMatchers","omitNonDeterministic","rewrites","nextPublicEnv","getNextPublicEnvironmentVariables","nextConfigEnv","getNextConfigEnv","isCacheComponentsEnabled","cacheComponents","isUseCacheEnabled","experimental","useCache","__NEXT_DEFINE_ENV","EdgeRuntime","process","env","NEXT_EDGE_RUNTIME_PROVIDER","NEXT_RSPACK","allowDevelopmentBuild","NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX","Boolean","appNavFailHandling","turbopackSharedRuntime","cachedNavigations","coldCacheBadge","requestInsights","supportsImmutableAssets","useSkewCookie","deploymentId","runtimeServerDeploymentId","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","manualClientBasePath","isNaN","Number","staleTimes","dynamic","static","clientRouterFilter","staticFilter","dynamicFilter","validateRSCRequestHeaders","serverComponentsHmrCancellation","dynamicOnHover","useOffline","prefetchInlining","optimisticClientCache","proxyPrefetch","crossOrigin","__NEXT_TEST_MODE","relative","cwd","basePath","caseSensitiveRoutes","trailingSlash","devIndicators","position","reactStrictMode","optimizeCss","nextScriptWorkers","scrollRestoration","i18n","skipProxyUrlNormalize","externalProxyRewritesResolve","skipTrailingSlashRedirect","webVitalsAttribution","length","linkNoTouchStart","assetPrefix","authInterrupts","NEXT_TELEMETRY_DISABLED","undefined","needsExperimentalReact","multiZoneDraftMode","trustHostHeader","allowedRevalidateHeaderKeys","logging","browserToTerminal","mcpServer","turbopackFileSystemCacheForDev","reactDebugChannel","transitionIndicator","gestureTransition","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","exposeTestingApiInProductionBuild","cacheLife","clientParamParsingOrigins","userDefines","compiler","define","hasOwnProperty","Error","userDefinesServer","defineServer","serializedDefineEnv","safeKey","split","pop"],"mappings":";;;;+BAwGgBA;;;eAAAA;;;iEAjGC;wCACsB;2BAIhC;;;;;;AA8BP,MAAMC,wBAAwBC,OAAO;AAqBrC;;CAEC,GACD,SAASC,mBAAmBC,SAAoB;IAC9C,MAAMC,uBAA4CC,OAAOC,WAAW,CAClED,OAAOE,OAAO,CAACJ,WAAWK,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAC9CD;YACA,OAAOC,UAAU,YAAYV,yBAAyBU,QAClDA,KAAK,CAACV,sBAAsB,GAC5BW,KAAKC,SAAS,CAACF;SACpB;IAEH,OAAON;AACT;AAEA,SAASS,eACPC,MAA0B,EAC1BC,GAAY;QAUKD,gBAKSA,iBACDA;IAdzB,OAAO;QACL,iCAAiC;YAC/BE,aAAaF,OAAOG,MAAM,CAACD,WAAW;YACtCE,YAAYJ,OAAOG,MAAM,CAACC,UAAU;YACpCC,WAAWL,OAAOG,MAAM,CAACE,SAAS;YAClCC,MAAMN,OAAOG,MAAM,CAACG,IAAI;YACxBC,QAAQP,OAAOG,MAAM,CAACI,MAAM;YAC5BC,qBAAqBR,OAAOG,MAAM,CAACK,mBAAmB;YACtDC,WAAW,EAAET,2BAAAA,iBAAAA,OAAQG,MAAM,qBAAdH,eAAgBS,WAAW;YACxC,GAAIR,MACA;gBAC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AAO,EAAEzB,IAAI6H,KAAK,CAAC,KAAKC,GAAG,IAAI,GAAG9H;QAEhD,IAAK,MAAMA,OAAO+B,cAAe;YAC/B4F,mBAAmB,CAAC3H,IAAI,GAAG4H,QAAQ5H;QACrC;QACA,IAAK,MAAMA,OAAOiC,cAAe;YAC/B0F,mBAAmB,CAAC3H,IAAI,GAAG4H,QAAQ5H;QACrC;QACA,IAAI,CAACK,OAAOiC,YAAY,CAACmB,yBAAyB,EAAE;YAClD,KAAK,MAAMzD,OAAO;gBAAC;aAAiC,CAAE;gBACpD2H,mBAAmB,CAAC3H,IAAI,GAAG4H,QAAQ5H;YACrC;QACF;IACF;IAEA,OAAO2H;AACT","ignoreList":[0]}

@@ -66,3 +66,3 @@ "use strict";

function isCatchAllRoute(pathname) {
// Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatability.
// Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatibility.
return !isOptionalCatchAll(pathname) && isCatchAll(pathname);

@@ -69,0 +69,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../src/build/normalize-catchall-routes.ts"],"sourcesContent":["import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'\nimport { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathname-normalizer'\n\n/**\n * This function will transform the appPaths in order to support catch-all routes and parallel routes.\n * It will traverse the appPaths, looking for catch-all routes and try to find parallel routes that could match\n * the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.\n *\n * @param appPaths The appPaths to transform\n */\nexport function normalizeCatchAllRoutes(\n appPaths: Record<string, string[]>,\n normalizer = new AppPathnameNormalizer()\n) {\n const catchAllRoutes = [\n ...new Set(\n Object.values(appPaths)\n .flat()\n .filter(isCatchAllRoute)\n // Sorting is important because we want to match the most specific path.\n .sort((a, b) => b.split('/').length - a.split('/').length)\n ),\n ]\n\n // interception routes should only be matched by a single entrypoint\n // we don't want to push a catch-all route to an interception route\n // because it would mean the interception would be handled by the wrong page component\n const filteredAppPaths = Object.keys(appPaths).filter(\n (route) => !isInterceptionRouteAppPath(route)\n )\n\n for (const appPath of filteredAppPaths) {\n for (const catchAllRoute of catchAllRoutes) {\n const normalizedCatchAllRoute = normalizer.normalize(catchAllRoute)\n const normalizedCatchAllRouteBasePath = normalizedCatchAllRoute.slice(\n 0,\n normalizedCatchAllRoute.search(catchAllRouteRegex)\n )\n\n if (\n // check if the appPath could match the catch-all\n appPath.startsWith(normalizedCatchAllRouteBasePath) &&\n // check if there's not already a slot value that could match the catch-all\n !appPaths[appPath].some((path) => hasMatchedSlots(path, catchAllRoute))\n ) {\n // optional catch-all routes are not currently supported, but leaving this logic in place\n // for when they are eventually supported.\n if (isOptionalCatchAll(catchAllRoute)) {\n // optional catch-all routes should match both the root segment and any segment after it\n // for example, `/[[...slug]]` should match `/` and `/foo` and `/foo/bar`\n appPaths[appPath].push(catchAllRoute)\n } else if (isCatchAll(catchAllRoute)) {\n // regular catch-all (single bracket) should only match segments after it\n // for example, `/[...slug]` should match `/foo` and `/foo/bar` but not `/`\n if (normalizedCatchAllRouteBasePath !== appPath) {\n appPaths[appPath].push(catchAllRoute)\n }\n }\n }\n }\n }\n}\n\nfunction hasMatchedSlots(path1: string, path2: string): boolean {\n const slots1 = path1.split('/').filter(isMatchableSlot)\n const slots2 = path2.split('/').filter(isMatchableSlot)\n\n // if the catch-all route does not have the same number of slots as the app path, it can't match\n if (slots1.length !== slots2.length) return false\n\n // compare the slots in both paths. For there to be a match, each slot must be the same\n for (let i = 0; i < slots1.length; i++) {\n if (slots1[i] !== slots2[i]) return false\n }\n\n return true\n}\n\n/**\n * Returns true for slots that should be considered when checking for match compatibility.\n * Excludes children slots because these are similar to having a segment-level `page`\n * which would cause a slot length mismatch when comparing it to a catch-all route.\n */\nfunction isMatchableSlot(segment: string): boolean {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nconst catchAllRouteRegex = /\\[?\\[\\.\\.\\./\n\nfunction isCatchAllRoute(pathname: string): boolean {\n // Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatability.\n return !isOptionalCatchAll(pathname) && isCatchAll(pathname)\n}\n\nfunction isOptionalCatchAll(pathname: string): boolean {\n return pathname.includes('[[...')\n}\n\nfunction isCatchAll(pathname: string): boolean {\n return pathname.includes('[...')\n}\n"],"names":["normalizeCatchAllRoutes","appPaths","normalizer","AppPathnameNormalizer","catchAllRoutes","Set","Object","values","flat","filter","isCatchAllRoute","sort","a","b","split","length","filteredAppPaths","keys","route","isInterceptionRouteAppPath","appPath","catchAllRoute","normalizedCatchAllRoute","normalize","normalizedCatchAllRouteBasePath","slice","search","catchAllRouteRegex","startsWith","some","path","hasMatchedSlots","isOptionalCatchAll","push","isCatchAll","path1","path2","slots1","isMatchableSlot","slots2","i","segment","pathname","includes"],"mappings":";;;;+BAUgBA;;;eAAAA;;;oCAV2B;uCACL;AAS/B,SAASA,wBACdC,QAAkC,EAClCC,aAAa,IAAIC,4CAAqB,EAAE;IAExC,MAAMC,iBAAiB;WAClB,IAAIC,IACLC,OAAOC,MAAM,CAACN,UACXO,IAAI,GACJC,MAAM,CAACC,gBACR,wEAAwE;SACvEC,IAAI,CAAC,CAACC,GAAGC,IAAMA,EAAEC,KAAK,CAAC,KAAKC,MAAM,GAAGH,EAAEE,KAAK,CAAC,KAAKC,MAAM;KAE9D;IAED,oEAAoE;IACpE,mEAAmE;IACnE,sFAAsF;IACtF,MAAMC,mBAAmBV,OAAOW,IAAI,CAAChB,UAAUQ,MAAM,CACnD,CAACS,QAAU,CAACC,IAAAA,8CAA0B,EAACD;IAGzC,KAAK,MAAME,WAAWJ,iBAAkB;QACtC,KAAK,MAAMK,iBAAiBjB,eAAgB;YAC1C,MAAMkB,0BAA0BpB,WAAWqB,SAAS,CAACF;YACrD,MAAMG,kCAAkCF,wBAAwBG,KAAK,CACnE,GACAH,wBAAwBI,MAAM,CAACC;YAGjC,IACE,iDAAiD;YACjDP,QAAQQ,UAAU,CAACJ,oCACnB,2EAA2E;YAC3E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"sourcesContent":["import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'\nimport { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathname-normalizer'\n\n/**\n * This function will transform the appPaths in order to support catch-all routes and parallel routes.\n * It will traverse the appPaths, looking for catch-all routes and try to find parallel routes that could match\n * the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.\n *\n * @param appPaths The appPaths to transform\n */\nexport function normalizeCatchAllRoutes(\n appPaths: Record<string, string[]>,\n normalizer = new AppPathnameNormalizer()\n) {\n const catchAllRoutes = [\n ...new Set(\n Object.values(appPaths)\n .flat()\n .filter(isCatchAllRoute)\n // Sorting is important because we want to match the most specific path.\n .sort((a, b) => b.split('/').length - a.split('/').length)\n ),\n ]\n\n // interception routes should only be matched by a single entrypoint\n // we don't want to push a catch-all route to an interception route\n // because it would mean the interception would be handled by the wrong page component\n const filteredAppPaths = Object.keys(appPaths).filter(\n (route) => !isInterceptionRouteAppPath(route)\n )\n\n for (const appPath of filteredAppPaths) {\n for (const catchAllRoute of catchAllRoutes) {\n const normalizedCatchAllRoute = normalizer.normalize(catchAllRoute)\n const normalizedCatchAllRouteBasePath = normalizedCatchAllRoute.slice(\n 0,\n normalizedCatchAllRoute.search(catchAllRouteRegex)\n )\n\n if (\n // check if the appPath could match the catch-all\n appPath.startsWith(normalizedCatchAllRouteBasePath) &&\n // check if there's not already a slot value that could match the catch-all\n !appPaths[appPath].some((path) => hasMatchedSlots(path, catchAllRoute))\n ) {\n // optional catch-all routes are not currently supported, but leaving this logic in place\n // for when they are eventually supported.\n if (isOptionalCatchAll(catchAllRoute)) {\n // optional catch-all routes should match both the root segment and any segment after it\n // for example, `/[[...slug]]` should match `/` and `/foo` and `/foo/bar`\n appPaths[appPath].push(catchAllRoute)\n } else if (isCatchAll(catchAllRoute)) {\n // regular catch-all (single bracket) should only match segments after it\n // for example, `/[...slug]` should match `/foo` and `/foo/bar` but not `/`\n if (normalizedCatchAllRouteBasePath !== appPath) {\n appPaths[appPath].push(catchAllRoute)\n }\n }\n }\n }\n }\n}\n\nfunction hasMatchedSlots(path1: string, path2: string): boolean {\n const slots1 = path1.split('/').filter(isMatchableSlot)\n const slots2 = path2.split('/').filter(isMatchableSlot)\n\n // if the catch-all route does not have the same number of slots as the app path, it can't match\n if (slots1.length !== slots2.length) return false\n\n // compare the slots in both paths. For there to be a match, each slot must be the same\n for (let i = 0; i < slots1.length; i++) {\n if (slots1[i] !== slots2[i]) return false\n }\n\n return true\n}\n\n/**\n * Returns true for slots that should be considered when checking for match compatibility.\n * Excludes children slots because these are similar to having a segment-level `page`\n * which would cause a slot length mismatch when comparing it to a catch-all route.\n */\nfunction isMatchableSlot(segment: string): boolean {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nconst catchAllRouteRegex = /\\[?\\[\\.\\.\\./\n\nfunction isCatchAllRoute(pathname: string): boolean {\n // Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatibility.\n return !isOptionalCatchAll(pathname) && isCatchAll(pathname)\n}\n\nfunction isOptionalCatchAll(pathname: string): boolean {\n return pathname.includes('[[...')\n}\n\nfunction isCatchAll(pathname: string): boolean {\n return pathname.includes('[...')\n}\n"],"names":["normalizeCatchAllRoutes","appPaths","normalizer","AppPathnameNormalizer","catchAllRoutes","Set","Object","values","flat","filter","isCatchAllRoute","sort","a","b","split","length","filteredAppPaths","keys","route","isInterceptionRouteAppPath","appPath","catchAllRoute","normalizedCatchAllRoute","normalize","normalizedCatchAllRouteBasePath","slice","search","catchAllRouteRegex","startsWith","some","path","hasMatchedSlots","isOptionalCatchAll","push","isCatchAll","path1","path2","slots1","isMatchableSlot","slots2","i","segment","pathname","includes"],"mappings":";;;;+BAUgBA;;;eAAAA;;;oCAV2B;uCACL;AAS/B,SAASA,wBACdC,QAAkC,EAClCC,aAAa,IAAIC,4CAAqB,EAAE;IAExC,MAAMC,iBAAiB;WAClB,IAAIC,IACLC,OAAOC,MAAM,CAACN,UACXO,IAAI,GACJC,MAAM,CAAC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yB,IAAI,GAAGA,IAAIH,OAAOtB,MAAM,EAAEyB,IAAK;QACtC,IAAIH,MAAM,CAACG,EAAE,KAAKD,MAAM,CAACC,EAAE,EAAE,OAAO;IACtC;IAEA,OAAO;AACT;AAEA;;;;CAIC,GACD,SAASF,gBAAgBG,OAAe;IACtC,OAAOA,QAAQb,UAAU,CAAC,QAAQa,YAAY;AAChD;AAEA,MAAMd,qBAAqB;AAE3B,SAASjB,gBAAgBgC,QAAgB;IACvC,mIAAmI;IACnI,OAAO,CAACV,mBAAmBU,aAAaR,WAAWQ;AACrD;AAEA,SAASV,mBAAmBU,QAAgB;IAC1C,OAAOA,SAASC,QAAQ,CAAC;AAC3B;AAEA,SAAST,WAAWQ,QAAgB;IAClC,OAAOA,SAASC,QAAQ,CAAC;AAC3B","ignoreList":[0]}

@@ -142,3 +142,3 @@ "use strict";

}({});
const nextVersion = "16.3.1-canary.11";
const nextVersion = "16.3.1-canary.12";
const ArchName = (0, _os.arch)();

@@ -145,0 +145,0 @@ const PlatformName = (0, _os.platform)();

@@ -96,3 +96,3 @@ "use strict";

isPersistentCachingEnabled: persistentCaching,
nextVersion: "16.3.1-canary.11"
nextVersion: "16.3.1-canary.12"
}, {

@@ -99,0 +99,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode,

@@ -119,3 +119,3 @@ // Import cpu-profile first to start profiling early if enabled

deferredEntries: config.experimental.deferredEntries,
nextVersion: "16.3.1-canary.11"
nextVersion: "16.3.1-canary.12"
};

@@ -122,0 +122,0 @@ if (config.experimental.turbopackSeedCacheFromWorktree) {

import type { NextConfigComplete, NextConfigRuntime } from '../server/config-shared';
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr';
import type { ServerRuntime } from '../types';

@@ -81,3 +80,3 @@ import type { BuildManifest } from '../server/get-page-files';

};
export declare function isPageStatic({ dir, page, distDir, configFileName, httpAgentOptions, locales, defaultLocale, parentId, pageRuntime, edgeInfo, pageType, cacheComponents, authInterrupts, useCacheTimeout, staticPageGenerationTimeout, originalAppPath, isrFlushToDisk, cacheMaxMemorySize, nextConfigOutput, cacheHandler, cacheHandlers, cacheLifeProfiles, pprConfig, buildId, deploymentId, clientAssetToken, sriEnabled, }: {
export declare function isPageStatic({ dir, page, distDir, configFileName, httpAgentOptions, locales, defaultLocale, parentId, pageRuntime, edgeInfo, pageType, cacheComponents, authInterrupts, useCacheTimeout, staticPageGenerationTimeout, originalAppPath, isrFlushToDisk, cacheMaxMemorySize, nextConfigOutput, cacheHandler, cacheHandlers, cacheLifeProfiles, buildId, deploymentId, clientAssetToken, sriEnabled, }: {
dir: string;

@@ -105,3 +104,2 @@ page: string;

nextConfigOutput: 'standalone' | 'export' | undefined;
pprConfig: ExperimentalPPRConfig | undefined;
buildId: string;

@@ -108,0 +106,0 @@ deploymentId: string;

@@ -143,3 +143,2 @@ "use strict";

});
const _ppr = require("../server/lib/experimental/ppr");
const _loadcustomroutes = require("../lib/load-custom-routes");

@@ -596,3 +595,3 @@ const _constants = require("../lib/constants");

}
async function isPageStatic({ dir, page, distDir, configFileName, httpAgentOptions, locales, defaultLocale, parentId, pageRuntime, edgeInfo, pageType, cacheComponents, authInterrupts, useCacheTimeout, staticPageGenerationTimeout, originalAppPath, isrFlushToDisk, cacheMaxMemorySize, nextConfigOutput, cacheHandler, cacheHandlers, cacheLifeProfiles, pprConfig, buildId, deploymentId, clientAssetToken, sriEnabled }) {
async function isPageStatic({ dir, page, distDir, configFileName, httpAgentOptions, locales, defaultLocale, parentId, pageRuntime, edgeInfo, pageType, cacheComponents, authInterrupts, useCacheTimeout, staticPageGenerationTimeout, originalAppPath, isrFlushToDisk, cacheMaxMemorySize, nextConfigOutput, cacheHandler, cacheHandlers, cacheLifeProfiles, buildId, deploymentId, clientAssetToken, sriEnabled }) {
// Skip page data collection for synthetic _global-error routes

@@ -698,6 +697,5 @@ if (page === _constants1.UNDERSCORE_GLOBAL_ERROR_ROUTE) {

rootParamKeys = (0, _collectrootparamkeys.collectRootParamKeys)(routeModule);
// A page supports partial prerendering if it is an app page and either
// the whole app has PPR enabled or this page has PPR enabled when we're
// in incremental mode.
isRoutePPREnabled = routeModule.definition.kind === _routekind.RouteKind.APP_PAGE && (0, _ppr.checkIsRoutePPREnabled)(pprConfig);
// A page supports partial prerendering when it is an app page and
// Cache Components is enabled.
isRoutePPREnabled = routeModule.definition.kind === _routekind.RouteKind.APP_PAGE && cacheComponents;
// If force dynamic was set and we don't have PPR enabled, then set the

@@ -704,0 +702,0 @@ // revalidate to 0.

@@ -6,5 +6,5 @@ 1:"$Sreact.fragment"

7:"$Sreact.suspense"
0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"3YrKiZrT98GTaBzv_9H8A"}
4:{}
5:"$0:rsc:props:children:0:props:serverProvidedParams:params"
8:null

@@ -12,3 +12,3 @@ 1:"$Sreact.fragment"

:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"3YrKiZrT98GTaBzv_9H8A"}
6:{}

@@ -15,0 +15,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params"

@@ -5,2 +5,2 @@ 1:"$Sreact.fragment"

4:"$Sreact.suspense"
0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"3YrKiZrT98GTaBzv_9H8A"}

@@ -5,2 +5,2 @@ 1:"$Sreact.fragment"

:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"3YrKiZrT98GTaBzv_9H8A"}
:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"3YrKiZrT98GTaBzv_9H8A"}

@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kor3_y3m.uh~.js"/><script src="/_next/static/chunks/0gto6h.7wfb54.js" async=""></script><script src="/_next/static/chunks/0o1qc.kvvuq1u.js" async=""></script><script src="/_next/static/chunks/turbopack-0vhvx5o96qn.d.js" async=""></script><script src="/_next/static/chunks/09tfif45vshr2.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script>

})();
</script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"sR5ErRj0ZbecEXQPAlvNc\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html>
</script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"3YrKiZrT98GTaBzv_9H8A\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html>

@@ -10,3 +10,3 @@ 1:"$Sreact.fragment"

:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"3YrKiZrT98GTaBzv_9H8A"}
d:[]

@@ -13,0 +13,0 @@ 7:"$Wd"

@@ -10,3 +10,3 @@ 1:"$Sreact.fragment"

:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"3YrKiZrT98GTaBzv_9H8A"}
d:[]

@@ -13,0 +13,0 @@ 7:"$Wd"

@@ -5,2 +5,2 @@ 1:"$Sreact.fragment"

4:"$Sreact.suspense"
0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"3YrKiZrT98GTaBzv_9H8A"}

@@ -5,2 +5,2 @@ 1:"$Sreact.fragment"

:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"3YrKiZrT98GTaBzv_9H8A"}
1:"$Sreact.fragment"
2:I[12361,["/_next/static/chunks/09tfif45vshr2.js"],"OutletBoundary"]
3:"$Sreact.suspense"
0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"3YrKiZrT98GTaBzv_9H8A"}
4:null

@@ -5,2 +5,2 @@ 1:"$Sreact.fragment"

4:[]
0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"3YrKiZrT98GTaBzv_9H8A"}
:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"3YrKiZrT98GTaBzv_9H8A"}

@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kor3_y3m.uh~.js"/><script src="/_next/static/chunks/0gto6h.7wfb54.js" async=""></script><script src="/_next/static/chunks/0o1qc.kvvuq1u.js" async=""></script><script src="/_next/static/chunks/turbopack-0vhvx5o96qn.d.js" async=""></script><script src="/_next/static/chunks/09tfif45vshr2.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script>

})();
</script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"sR5ErRj0ZbecEXQPAlvNc\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html>
</script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"3YrKiZrT98GTaBzv_9H8A\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html>

@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kor3_y3m.uh~.js"/><script src="/_next/static/chunks/0gto6h.7wfb54.js" async=""></script><script src="/_next/static/chunks/0o1qc.kvvuq1u.js" async=""></script><script src="/_next/static/chunks/turbopack-0vhvx5o96qn.d.js" async=""></script><script src="/_next/static/chunks/09tfif45vshr2.js" async=""></script><script src="/_next/static/chunks/16s6g-zs4p3i7.js" async=""></script><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script>

})();
</script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[41813,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/09tfif45vshr2.js\",\"/_next/static/chunks/16s6g-zs4p3i7.js\"],\"default\"]\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\nd:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nf:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/16s6g-zs4p3i7.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"sR5ErRj0ZbecEXQPAlvNc\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html>
</script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[41813,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/09tfif45vshr2.js\",\"/_next/static/chunks/16s6g-zs4p3i7.js\"],\"default\"]\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\nd:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nf:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/16s6g-zs4p3i7.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"3YrKiZrT98GTaBzv_9H8A\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html>

@@ -12,3 +12,3 @@ 1:"$Sreact.fragment"

:HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"]
0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"}
0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"3YrKiZrT98GTaBzv_9H8A"}
6:{}

@@ -15,0 +15,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params"

@@ -42,3 +42,3 @@ #!/usr/bin/env node

const nextBuild = async (options, directory)=>{
process.title = `next-build (v${"16.3.1-canary.11"})`;
process.title = `next-build (v${"16.3.1-canary.12"})`;
process.on('SIGTERM', ()=>{

@@ -45,0 +45,0 @@ (0, _cpuprofile.saveCpuProfile)();

@@ -43,3 +43,3 @@ #!/usr/bin/env node

const bindings = await (0, _swc.loadBindings)((_config_experimental1 = config.experimental) == null ? void 0 : _config_experimental1.useWasmBinary);
await bindings.turbo.databaseCompact(cachePath, "16.3.1-canary.11");
await bindings.turbo.databaseCompact(cachePath, "16.3.1-canary.12");
console.log('Turbopack database compaction complete.');

@@ -46,0 +46,0 @@ };

@@ -18,3 +18,3 @@ /**

const _setattributesfromprops = require("./set-attributes-from-props");
const version = "16.3.1-canary.11";
const version = "16.3.1-canary.12";
window.next = {

@@ -21,0 +21,0 @@ version,

@@ -20,3 +20,2 @@ "use strict";

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -23,0 +22,0 @@ if (error) {

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/client/components/handle-isr-error.tsx"],"sourcesContent":["import { workUnitAsyncStorage } from './server-async-storage'\n\n// if we are revalidating we want to re-throw the error so the\n// function crashes so we can maintain our previous cache\n// instead of caching the error page\nexport function handleISRError({ error }: { error: any }) {\n if (!workUnitAsyncStorage) {\n return\n }\n\n const store = workUnitAsyncStorage.getStore()\n switch (store?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n if (error) {\n console.error(error)\n }\n throw error\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return\n default:\n store satisfies never\n }\n}\n"],"names":["handleISRError","error","workUnitAsyncStorage","store","getStore","type","console","undefined"],"mappings":";;;;+BAKgBA;;;eAAAA;;;oCALqB;AAK9B,SAASA,eAAe,EAAEC,KAAK,EAAkB;IACtD,IAAI,CAACC,wCAAoB,EAAE;QACzB;IACF;IAEA,MAAMC,QAAQD,wCAAoB,CAACE,QAAQ;IAC3C,OAAQD,OAAOE;QACb,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,IAAIJ,OAAO;gBACTK,QAAQL,KAAK,CAACA;YAChB;YACA,MAAMA;QACR,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKM;YACH;QACF;YACEJ;IACJ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/client/components/handle-isr-error.tsx"],"sourcesContent":["import { workUnitAsyncStorage } from './server-async-storage'\n\n// if we are revalidating we want to re-throw the error so the\n// function crashes so we can maintain our previous cache\n// instead of caching the error page\nexport function handleISRError({ error }: { error: any }) {\n if (!workUnitAsyncStorage) {\n return\n }\n\n const store = workUnitAsyncStorage.getStore()\n switch (store?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n if (error) {\n console.error(error)\n }\n throw error\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return\n default:\n store satisfies never\n }\n}\n"],"names":["handleISRError","error","workUnitAsyncStorage","store","getStore","type","console","undefined"],"mappings":";;;;+BAKgBA;;;eAAAA;;;oCALqB;AAK9B,SAASA,eAAe,EAAEC,KAAK,EAAkB;IACtD,IAAI,CAACC,wCAAoB,EAAE;QACzB;IACF;IAEA,MAAMC,QAAQD,wCAAoB,CAACE,QAAQ;IAC3C,OAAQD,OAAOE;QACb,KAAK;QACL,KAAK;QACL,KAAK;YACH,IAAIJ,OAAO;gBACTK,QAAQL,KAAK,CAACA;YAChB;YACA,MAAMA;QACR,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKM;YACH;QACF;YACEJ;IACJ;AACF","ignoreList":[0]}

@@ -47,3 +47,2 @@ "use strict";

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':

@@ -85,3 +84,2 @@ case 'cache':

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':

@@ -115,3 +113,2 @@ case 'cache':

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':

@@ -118,0 +115,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/client/components/instant-samples.ts"],"sourcesContent":["import type { Params } from '../../server/request/params'\nimport type { ReadonlyURLSearchParams } from './readonly-url-search-params'\nimport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'\nimport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\nimport {\n createExhaustiveParamsProxy,\n createExhaustiveURLSearchParamsProxy,\n trackMissingSampleErrorAndThrow,\n} from '../../server/app-render/instant-validation/instant-samples'\nimport { InstantValidationError } from '../../server/app-render/instant-validation/instant-validation-error'\n\nexport function instrumentParamsForClientValidation<TPArams extends Params>(\n underlyingParams: TPArams\n): TPArams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.params ?? {})\n )\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingParams\n}\n\nexport function expectCompleteParamsInClientValidation(\n expression: string\n): void {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n const missingParams = Array.from(fallbackParams.keys())\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${workStore.route}\" called ${expression} but param${missingParams.length > 1 ? 's' : ''} ${missingParams.map((p) => `\"${p}\"`).join(', ')} ${missingParams.length > 1 ? 'are' : 'is'} not defined in the \\`unstable_samples\\` of \\`instant\\`. ` +\n `${expression} requires all route params to be provided.`\n )\n )\n }\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\nexport function instrumentSearchParamsForClientValidation(\n underlyingSearchParams: ReadonlyURLSearchParams\n): ReadonlyURLSearchParams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.searchParams ?? {})\n )\n return createExhaustiveURLSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingSearchParams\n}\n"],"names":["expectCompleteParamsInClientValidation","instrumentParamsForClientValidation","instrumentSearchParamsForClientValidation","underlyingParams","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","type","validationSamples","declaredKeys","Set","Object","keys","params","createExhaustiveParamsProxy","route","expression","fallbackParams","fallbackRouteParams","size","missingParams","Array","from","trackMissingSampleErrorAndThrow","InstantValidationError","length","map","p","join","underlyingSearchParams","searchParams","createExhaustiveURLSearchParamsProxy"],"mappings":";;;;;;;;;;;;;;;;IAiDgBA,sCAAsC;eAAtCA;;IAtCAC,mCAAmC;eAAnCA;;IA6EAC,yCAAyC;eAAzCA;;;8CAtFqB;0CACJ;gCAK1B;wCACgC;AAEhC,SAASD,oCACdE,gBAAyB;IAEzB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAIF,aAAaG,eAAe;QAC9B,OAAQA,cAAcE,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAIF,cAAcG,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACP,cAAcG,iBAAiB,CAACK,MAAM,IAAI,CAAC;wBA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IAE/C,MAAM3B,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAIF,aAAaG,eAAe;QAC9B,OAAQA,cAAcE,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAIF,cAAcG,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACP,cAAcG,iBAAiB,CAACsB,YAAY,IAAI,CAAC;wBAE/D,OAAOC,IAAAA,oDAAoC,EACzCF,wBACApB,cACAP,UAAUa,KAAK;oBAEnB;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEV;QACJ;IACF;IACA,OAAOwB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../src/client/components/instant-samples.ts"],"sourcesContent":["import type { Params } from '../../server/request/params'\nimport type { ReadonlyURLSearchParams } from './readonly-url-search-params'\nimport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'\nimport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\nimport {\n createExhaustiveParamsProxy,\n createExhaustiveURLSearchParamsProxy,\n trackMissingSampleErrorAndThrow,\n} from '../../server/app-render/instant-validation/instant-samples'\nimport { InstantValidationError } from '../../server/app-render/instant-validation/instant-validation-error'\n\nexport function instrumentParamsForClientValidation<TPArams extends Params>(\n underlyingParams: TPArams\n): TPArams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.params ?? {})\n )\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingParams\n}\n\nexport function expectCompleteParamsInClientValidation(\n expression: string\n): void {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n const missingParams = Array.from(fallbackParams.keys())\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${workStore.route}\" called ${expression} but param${missingParams.length > 1 ? 's' : ''} ${missingParams.map((p) => `\"${p}\"`).join(', ')} ${missingParams.length > 1 ? 'are' : 'is'} not defined in the \\`unstable_samples\\` of \\`instant\\`. ` +\n `${expression} requires all route params to be provided.`\n )\n )\n }\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\nexport function instrumentSearchParamsForClientValidation(\n underlyingSearchParams: ReadonlyURLSearchParams\n): ReadonlyURLSearchParams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.searchParams ?? {})\n )\n return createExhaustiveURLSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingSearchParams\n}\n"],"names":["expectCompleteParamsInClientValidation","instrumentParamsForClientValidation","instrumentSearchParamsForClientValidation","underlyingParams","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","type","validationSamples","declaredKeys","Set","Object","keys","params","createExhaustiveParamsProxy","route","expression","fallbackParams","fallbackRouteParams","size","missingParams","Array","from","trackMissingSampleErrorAndThrow","InstantValidationError","length","map","p","join","underlyingSearchParams","searchParams","createExhaustiveURLSearchParamsProxy"],"mappings":";;;;;;;;;;;;;;;;IAgDgBA,sCAAsC;eAAtCA;;IArCAC,mCAAmC;eAAnCA;;IA2EAC,yCAAyC;eAAzCA;;;8CApFqB;0CACJ;gCAK1B;wCACgC;AAEhC,SAASD,oCACdE,gBAAyB;IAEzB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAIF,aAAaG,eAAe;QAC9B,OAAQA,cAAcE,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAIF,cAAcG,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACP,cAAcG,iBAAiB,CAACK,MAAM,IAAI,CAAC;wBAEzD,OAAOC,IAAAA,2CAA2B,EAChCb,kBACAQ,cACAP,UAAUa,KAAK;oBAEnB;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEV;QACJ;IACF;IACA,OAAOJ;AACT;AAEO,SAASH,uCACdkB,UAAkB;IAElB,MAAMd,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAIF,aAAaG,eAAe;QAC9B,OAAQA,cAAcE,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAIF,cAAcG,iBAAiB,E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L,KAAK;gBACH;YACF;gBACEV;QACJ;IACF;IACA,OAAOwB;AACT","ignoreList":[0]}

@@ -30,3 +30,2 @@ "use strict";

case 'prerender-client':
case 'prerender-ppr':
case 'validation-client':

@@ -33,0 +32,0 @@ const fallbackParams = workUnitStore.fallbackRouteParams;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/client/components/navigation-untracked.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { workUnitAsyncStorage } from './server-async-storage'\n\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams(): boolean {\n // The AsyncLocalStorage module is kept out of the client bundle via the\n // `./server-async-storage` browser alias; the guard ensures the stub is never\n // dereferenced in the browser.\n if (typeof window === 'undefined') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) return false\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'validation-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n return fallbackParams ? fallbackParams.size > 0 : false\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n\n return false\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n"],"names":["useUntrackedPathname","hasFallbackRouteParams","window","workUnitStore","workUnitAsyncStorage","getStore","type","fallbackParams","fallbackRouteParams","size","useContext","PathnameContext"],"mappings":";;;;+BAuDgBA;;;eAAAA;;;uBAvDW;iDACK;oCACK;AAErC;;;;;;CAMC,GACD,SAASC;IACP,wEAAwE;IACxE,8EAA8E;IAC9E,+BAA+B;IAC/B,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAMC,gBAAgBC,wCAAoB,CAACC,QAAQ;QACnD,IAAI,CAACF,eAAe,OAAO;QAE3B,OAAQA,cAAcG,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAMC,iBAAiBJ,cAAcK,mBAAmB;gBACxD,OAAOD,iBAAiBA,eAAeE,IAAI,GAAG,IAAI;YACpD,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEN;QACJ;QAEA,OAAO;IACT;IAEA,OAAO;AACT;AAaO,SAASH;IACd,qEAAqE;IACrE,8EAA8E;IAC9E,8EAA8E;IAC9E,uBAAuB;IACvB,IAAIC,0BAA0B;QAC5B,OAAO;IACT;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,sDAAsD;IACtD,OAAOS,IAAAA,iBAAU,EAACC,gDAAe;AACnC","ignoreList":[0]}
{"version":3,"sources":["../../../src/client/components/navigation-untracked.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { workUnitAsyncStorage } from './server-async-storage'\n\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams(): boolean {\n // The AsyncLocalStorage module is kept out of the client bundle via the\n // `./server-async-storage` browser alias; the guard ensures the stub is never\n // dereferenced in the browser.\n if (typeof window === 'undefined') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) return false\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n return fallbackParams ? fallbackParams.size > 0 : false\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n\n return false\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n"],"names":["useUntrackedPathname","hasFallbackRouteParams","window","workUnitStore","workUnitAsyncStorage","getStore","type","fallbackParams","fallbackRouteParams","size","useContext","PathnameContext"],"mappings":";;;;+BAsDgBA;;;eAAAA;;;uBAtDW;iDACK;oCACK;AAErC;;;;;;CAMC,GACD,SAASC;IACP,wEAAwE;IACxE,8EAA8E;IAC9E,+BAA+B;IAC/B,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAMC,gBAAgBC,wCAAoB,CAACC,QAAQ;QACnD,IAAI,CAACF,eAAe,OAAO;QAE3B,OAAQA,cAAcG,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAMC,iBAAiBJ,cAAcK,mBAAmB;gBACxD,OAAOD,iBAAiBA,eAAeE,IAAI,GAAG,IAAI;YACpD,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEN;QACJ;QAEA,OAAO;IACT;IAEA,OAAO;AACT;AAaO,SAASH;IACd,qEAAqE;IACrE,8EAA8E;IAC9E,8EAA8E;IAC9E,uBAAuB;IACvB,IAAIC,0BAA0B;QAC5B,OAAO;IACT;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,sDAAsD;IACtD,OAAOS,IAAAA,iBAAU,EAACC,gDAAe;AACnC","ignoreList":[0]}

@@ -50,3 +50,4 @@ "use strict";

const acc = {
metadataVaryPath: null
metadataVaryPath: null,
treeDivergedFromBase: false
};

@@ -53,0 +54,0 @@ const initialRouteTree = (0, _decodeserverresponse.decodeTransportTreeIntoRouteTree)(initialTransportData.t, // There's no base tree to overlay onto; the initial payload is a full

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n segmentCacheMap,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n segmentCacheMap // hydration writes are bound to the shared map\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n scrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","transportNodeToFlightRouterState","canonicalUrl","createHrefFromUrl","acc","metadataVaryPath","initialRouteTree","decodeTransportTreeIntoRouteTree","initialTask","createInitialCacheNodeForHydration","computeDynamicStaleAt","UnknownDynamicStaleTime","discoverKnownRoute","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","decodeStageUntilBoundary","staleAt","resolveStaleAt","writePrerenderResponseIntoCache","FetchStrategy","PPR","segmentCacheMap","catch","cancel","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","extractPathFromFlightRouterState","previousNextUrl","debugInfo"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;mCA9BkB;oCACe;8BAGA;gCACE;uBAO5C;sCAC0C;uBACnB;yBAIvB;qCACkC;kCACN;AAU5B,SAASA,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,oBAAoB,EACvBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGtB;IAEJ,sFAAsF;IACtF,kGAAkG;IAClG,mCAAmC;IACnC,MAAMuB,sBAAsBnB,yBAAyBoB,IAAI,CAAC;IAE1D,MAAMC,cAAcnB,qBAAqBoB,CAAC,CAACT,CAAC;IAE5C,uEAAuE;IACvE,qEAAqE;IACrE,UAAU;IACV,MAAMU,cAAcC,IAAAA,8CAAgC,EAACtB,qBAAqBD,CAAC;IAE3E,MAAMwB,eACJ,6EAA6E;IAC7E,kJAAkJ;IAClJ3B,WAEI4B,IAAAA,oCAAiB,EAAC5B,YAClBqB;IAEN,sEAAsE;IACtE,2EAA2E;IAC3E,wEAAwE;IACxE,+BAA+B;IAC/B,2EAA2E;IAC3E,6EAA6E;IAC7E,8CAA8C;IAC9C,EAAE;IACF,yEAAyE;IACzE,wEAAwE;IACxE,0EAA0E;IAC1E,0EAA0E;IAC1E,qEAAqE;IACrE,0CAA0C;IAC1C,MAAMQ,MAAM;QAAEC,kBAAkB;IAAK;IACrC,MAAMC,mBAAmBC,IAAAA,s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BC,OAAOpC,YAAYqC,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,WAAW;YACTA,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAnD;QACAoD,gBAAgBzE;QAChB,sEAAsE;QACtE0E,SACE,AAACC,CAAAA,IAAAA,oDAAgC,EAACxD,gBAAgBzB,UAAUwC,QAAO,KACnE;QACF0C,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOjB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n segmentCacheMap,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null, treeDivergedFromBase: false }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n segmentCacheMap // hydration writes are bound to the shared map\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n scrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","transportNodeToFlightRouterState","canonicalUrl","createHrefFromUrl","acc","metadataVaryPath","treeDivergedFromBase","initialRouteTree","decodeTransportTreeIntoRouteTree","initialTask","createInitialCacheNodeForHydration","computeDynamicStaleAt","UnknownDynamicStaleTime","discoverKnownRoute","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","decodeStageUntilBoundary","staleAt","resolveStaleAt","writePrerenderResponseIntoCache","FetchStrategy","PPR","segmentCacheMap","catch","cancel","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","extractPathFromFlightRouterState","previousNextUrl","debugInfo"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;mCA9BkB;oCACe;8BAGA;gCACE;u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BAAgB1E;QAChB,sEAAsE;QACtE2E,SACE,AAACC,CAAAA,IAAAA,oDAAgC,EAACzD,gBAAgBzB,UAAUyC,QAAO,KACnE;QACF0C,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOjB;AACT","ignoreList":[0]}

@@ -116,8 +116,5 @@ 'use client';

}
// Typically, during a navigation, we decode the response using Flight's
// During a navigation, we decode the response using Flight's
// `createFromFetch` API, which accepts a `fetch` promise.
// TODO: Remove this check once the old PPR flag is removed
const isLegacyPPR = process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS;
const shouldImmediatelyDecode = !isLegacyPPR;
const res = await createFetch(url, headers, 'auto', shouldImmediatelyDecode, options.signal);
const res = await createFetch(url, headers, 'auto', true, options.signal);
// If the fetch succeeds while we're in the offline state, notify the

@@ -161,13 +158,5 @@ // offline module so it can short-circuit the polling loop.

}
let flightResponsePromise = res.flightResponsePromise;
if (flightResponsePromise === null) {
// Typically, `createFetch` would have already started decoding the
// Flight response. If it hasn't, though, we need to decode it now.
// TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR
// without Cache Components). Remove this branch once legacy PPR
// is deleted.
flightResponsePromise = createFromNextReadableStream(res.body, headers, {
allowPartialStream: postponed
});
}
// This request passed `true` to `shouldImmediatelyDecode`, so the Flight
// response promise is always initialized.
const flightResponsePromise = res.flightResponsePromise;
const [flightResponse, cacheData] = await Promise.all([

@@ -174,0 +163,0 @@ flightResponsePromise,

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/router-reducer/fetch-server-response.ts"],"sourcesContent":["'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { fetch } from '../segment-cache/fetch'\nimport type {\n FlightRouterState,\n InitialRSCPayload,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers'\nimport type { PartialTransportData } from '../../../shared/lib/rsc-transport'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport { urlToUrlWithoutFlightMarker } from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n stripIsPartialByte,\n createNonTaskyPrefetchResponseStream,\n} from '../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n readonly signal?: AbortSignal\n}\n\nexport type StaticStageData<\n T extends\n | NavigationFlightResponse\n | InitialRSCPayload = NavigationFlightResponse,\n> = {\n readonly response: T\n readonly isResponsePartial: boolean\n}\n\ntype SpaFetchServerResponseResult = {\n transportData: PartialTransportData | null\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n supportsPerSegmentPrefetching: boolean\n postponed: boolean\n dynamicStaleTime: number\n staticStageData: StaticStageData | null\n runtimePrefetchStream: ReadableStream<Uint8Array> | null\n responseHeaders: Headers\n debugInfo: Array<any> | null\n /**\n * Dev only: resolves once the server has flushed the shell-stage content to\n * the stream (or earlier, on a cache miss). The navigation defers revealing\n * the response (resolving its deferred RSCs) until this settles, so React\n * doesn't render a boundary's children before their row has been decoded and\n * commit a premature Suspense fallback. `null` outside the streaming dev\n * render.\n */\n revealAfter: Promise<void> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2' | '3'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', () => {\n isPageUnloading = true\n })\n\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n isPageUnloading = false\n })\n}\n\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url\n\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url)\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt'\n } else {\n url.pathname += '.txt'\n }\n }\n }\n\n // Typically, during a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n // TODO: Remove this check once the old PPR flag is removed\n const isLegacyPPR =\n process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS\n const shouldImmediatelyDecode = !isLegacyPPR\n const res = await createFetch<NavigationFlightResponse>(\n url,\n headers,\n 'auto',\n shouldImmediatelyDecode,\n options.signal\n )\n\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../offline') as typeof import('../offline')\n notifyOnline()\n }\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\n const contentType = res.headers.get('content-type') || ''\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL)\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain')\n }\n }\n }\n\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash\n }\n\n return doMpaNavigation(responseUrl.toString())\n }\n\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n let flightResponsePromise = res.flightResponsePromise\n if (flightResponsePromise === null) {\n // Typically, `createFetch` would have already started decoding the\n // Flight response. If it hasn't, though, we need to decode it now.\n // TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR\n // without Cache Components). Remove this branch once legacy PPR\n // is deleted.\n flightResponsePromise =\n createFromNextReadableStream<NavigationFlightResponse>(\n res.body,\n headers,\n { allowPartialStream: postponed }\n )\n }\n\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData,\n ])\n\n if (\n (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url)\n }\n\n if (flightResponse.n !== undefined) {\n // The server responded with an MPA navigation URL instead of a\n // SPA payload.\n return doMpaNavigation(flightResponse.n)\n }\n\n const staticStageData =\n cacheData !== null\n ? await resolveStaticStageData(cacheData, flightResponse, headers)\n : null\n\n return {\n transportData: flightResponse.t ?? null,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q as NormalizedSearch,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n staticStageData,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n revealAfter: flightResponse._revealAfter ?? null,\n }\n } catch (err) {\n if (options.signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request.\n // Rethrow so the caller treats it as canceled, rather than logging a\n // failure or falling back to an MPA navigation.\n throw err\n }\n\n // If the fetch rejected due to a network error, wait for connectivity\n // to be restored and then retry. checkOfflineError returns true for\n // network errors (and starts the polling loop); returns false for\n // intentional aborts/timeouts, which fall through to the MPA fallback.\n //\n // Note: when the user navigates multiple times while offline, each\n // navigation queues a separate retry here. Once connectivity returns,\n // all pending retries resume simultaneously. This is mitigated in PR 3\n // by reusing back-forward cache entries during offline navigation, which\n // avoids issuing new fetches in the first place.\n if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../offline') as typeof import('../offline')\n if (checkOfflineError(err)) {\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerResponse(url, options)\n }\n }\n\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\n\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString()\n }\n}\n\n// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null\n cacheData: Promise<FetchResponseCacheData | null>\n}\n\ntype FetchResponseCacheData = {\n isResponsePartial: boolean\n // Separate clones of the response body for stage extraction. The static\n // stage and shell stage are extracted from independent reads, so each\n // needs its own ReadableStream. Both are derived from a chain of `tee()`\n // calls in `processFetch`.\n staticBodyClone?: ReadableStream<Uint8Array>\n shellBodyClone?: ReadableStream<Uint8Array>\n}\n\n/**\n * Strips the leading isPartial byte from an RSC navigation response and\n * clones the body for segment cache extraction.\n *\n * When cache components is enabled, the server prepends a single byte:\n * '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped\n * before Flight decoding because it's not valid RSC data. The body is\n * cloned before Flight can consume it so the clone is available for later use.\n *\n * When cache components is disabled, returns the original response with\n * cacheData: null.\n */\nexport async function processFetch(response: Response): Promise<{\n response: Response\n cacheData: FetchResponseCacheData | null\n}> {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError(\n 'Expected RSC navigation response to have a body'\n )\n }\n\n const { stream, isPartial } = await stripIsPartialByte(response.body)\n\n let responseStream: ReadableStream<Uint8Array>\n let cacheData: FetchResponseCacheData\n\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n // Three readers needed: the main Flight decoder, the static-stage\n // extractor, and the shell-stage extractor. Tee twice.\n const [stream1, rest] = stream.tee()\n const [staticBodyClone, shellBodyClone] = rest.tee()\n responseStream = stream1\n cacheData = {\n isResponsePartial: isPartial,\n staticBodyClone,\n shellBodyClone,\n }\n } else {\n responseStream = stream\n cacheData = { isResponsePartial: isPartial }\n }\n\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n })\n\n // The Response constructor doesn't preserve `url` or `redirected` from\n // the original. We need both: `url` for React DevTools and `redirected`\n // for the redirect replay logic below.\n Object.defineProperty(strippedResponse, 'url', { value: response.url })\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected,\n })\n\n return { response: strippedResponse, cacheData }\n }\n\n return { response, cacheData: null }\n}\n\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */\nexport async function resolveStaticStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<StaticStageData<T> | null> {\n const { isResponsePartial, staticBodyClone } = cacheData\n\n if (staticBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n staticBodyClone.cancel()\n\n return { response: flightResponse, isResponsePartial: false }\n }\n\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const staticStageByteLength = await flightResponse.l\n const response = await decodeStageUntilBoundary<T>(\n staticBodyClone,\n staticStageByteLength,\n headers\n )\n\n return { response, isResponsePartial: true }\n }\n\n // No caching — cancel the unused clone.\n staticBodyClone.cancel()\n }\n\n return null\n}\n\n/**\n * Resolves the shell stage of a prerender response, performing a separate\n * Flight decode of the byte prefix when the shell differs from the main\n * response. Returns null when no separate decode is needed:\n *\n * - `a === undefined`: server didn't emit shell stage info.\n * - `a` resolves to `null`: the shell IS the main response — the caller can\n * reuse the existing decoded `flightResponse` if it needs a shell payload.\n *\n * Returns the decoded shell payload when `a` resolves to a number, i.e.\n * the shell is a strict prefix of the response and requires a separate\n * decode at that byte boundary.\n */\nexport async function resolveShellStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n const { shellBodyClone } = cacheData\n\n if (!shellBodyClone) {\n return null\n }\n\n if (flightResponse.a === undefined) {\n shellBodyClone.cancel()\n return null\n }\n\n const shellByteLength = await flightResponse.a\n if (shellByteLength === null) {\n // Shell == main response — caller reuses the existing flightResponse.\n shellBodyClone.cancel()\n return null\n }\n\n return decodeStageUntilBoundary<T>(shellBodyClone, shellByteLength, headers)\n}\n\n/**\n * Truncates and buffers a Flight stream clone at the given byte boundary and\n * decodes the prefix as a Flight payload. Used by the static-stage and\n * shell-stage extraction helpers.\n */\nexport async function decodeStageUntilBoundary<T>(\n responseBodyClone: ReadableStream<Uint8Array>,\n byteLength: number,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const { buffer } = await createNonTaskyPrefetchResponseStream(\n responseBodyClone,\n byteLength\n )\n return decodeBufferedStage<T>(buffer, headers)\n}\n\n/**\n * Decodes already-buffered Flight response bytes as a stage payload. The\n * bytes are delivered to Flight as a single chunk so all rows are processed\n * synchronously in one call — required for the thenable-status reads that\n * scope a response's late-resolving metadata (vary params, isPartial, ...)\n * to this decode.\n */\nexport function decodeBufferedStage<T>(\n buffer: Uint8Array,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(buffer)\n controller.close()\n },\n })\n return createFromNextReadableStream<T>(stream, headers, {\n allowPartialStream: true,\n })\n}\n\n// When an HMR refresh can be superseded, we decode its Flight response through\n// a wrapper stream we can close on abort. Closing the stream (rather than\n// letting the aborted fetch error it) makes React's Flight client mark\n// unresolved rows as halted: they suspend during render instead of rejecting,\n// so a superseded request never surfaces an error on an already-committed tree.\n// Because the stream is closed, there's also no unclosed-stream GC-root leak\n// (see #89610). The wrapper is created synchronously here so that the decode\n// starts at the same point `createFromNextFetch` would, preserving the\n// server-latency debug timing.\nfunction createHaltingFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal\n): Promise<T> & { _debugInfo?: Array<any> } {\n let closed = false\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n const wrapper = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n closed = true\n try {\n controller.close()\n } catch {\n // The controller may already be closed; nothing to do.\n }\n if (reader !== null) {\n reader.cancel().catch(() => {})\n }\n }\n if (signal.aborted) {\n onAbort()\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n },\n async pull(controller) {\n if (closed) {\n return\n }\n if (reader === null) {\n let response: Response\n try {\n response = await fetchPromise\n } catch (err) {\n // We don't inspect `err`. If the request was superseded, `onAbort`\n // already ran synchronously (abort listeners fire during\n // `signal.abort()`, before this rejection microtask), so `closed` is\n // true and the controller is already closed — erroring it would\n // throw, and a superseded request's failure is moot regardless of its\n // cause. Only a genuine, non-superseded failure reaches here with\n // `closed` still false; that is the case we surface.\n if (!closed) {\n controller.error(err)\n }\n return\n }\n if (closed) {\n // Aborted while awaiting the response. The `fetch` abort tears down\n // an in-flight request, but if it had already completed we still hold\n // an unread body; release it so it isn't left dangling.\n response.body?.cancel().catch(() => {})\n return\n }\n const body = response.body\n if (body === null) {\n controller.close()\n return\n }\n reader = body.getReader()\n }\n try {\n const { done, value } = await reader.read()\n if (closed) {\n return\n }\n if (done) {\n controller.close()\n } else {\n controller.enqueue(value)\n }\n } catch (err) {\n // Same as the fetch catch above: once superseded (`closed`) the\n // controller is already closed and the outcome is moot, so we swallow\n // the rejection unconditionally; only a real, non-superseded read\n // failure (`closed` still false) is surfaced.\n if (!closed) {\n controller.error(err)\n }\n }\n },\n })\n\n // React attaches `_debugInfo` to the returned promise at runtime.\n return createFromNextReadableStream<T>(wrapper, headers, {\n allowPartialStream: true,\n }) as Promise<T> & { _debugInfo?: Array<any> }\n}\n\n// Selects the Flight decode strategy: a halting wrapper for cancellable HMR\n// refreshes, otherwise the standard fetch-based decode. Gated to the dev server\n// (where HMR runs) so the wrapper is eliminated from production and\n// `--debug-prerender` bundles regardless of the flag.\nfunction decodeFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal | undefined\n): Promise<T> & { _debugInfo?: Array<any> } {\n if (\n process.env.__NEXT_DEV_SERVER &&\n process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION &&\n signal\n ) {\n return createHaltingFlightResponse<T>(fetchPromise, headers, signal)\n }\n return createFromNextFetch<T>(fetchPromise, headers)\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n await setCacheBustingSearchParam(fetchUrl, headers)\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n let fetchPromise = processed.then(({ response }) => response)\n\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because a\n // top-level prefetch response never blocks a navigation; if it hasn't already\n // been written into the cache by the time the navigation happens, the router\n // will go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n let browserResponse = await fetchPromise\n\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n\n let redirected = browserResponse.redirected\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20\n for (let n = 0; n < MAX_REDIRECTS; n++) {\n if (!browserResponse.redirected) {\n // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n await setCacheBustingSearchParam(fetchUrl, headers)\n processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n fetchPromise = processed.then(({ response }) => response)\n flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\n }\n\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponsePromise: flightResponsePromise,\n\n cacheData: processed.then(({ cacheData }) => cacheData),\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders | undefined,\n options?: { allowPartialStream?: boolean }\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream,\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n"],"names":["createFetch","createFromNextReadableStream","decodeBufferedStage","decodeStageUntilBoundary","fetchServerResponse","processFetch","resolveShellStageData","resolveStaticStageData","createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","doMpaNavigation","url","urlToUrlWithoutFlightMarker","URL","location","origin","toString","isPageUnloading","window","addEventListener","options","flightRouterState","nextUrl","headers","RSC_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","prepareFlightRouterStateForRequest","isHmrRefresh","NODE_ENV","NEXT_HMR_REFRESH_HEADER","NEXT_URL","originalUrl","__NEXT_CONFIG_OUTPUT","pathname","endsWith","isLegacyPPR","__NEXT_PPR","__NEXT_CACHE_COMPONENTS","shouldImmediatelyDecode","res","signal","__NEXT_USE_OFFLINE","notifyOnline","responseUrl","canonicalUrl","redirected","contentType","get","interception","includes","postponed","NEXT_DID_POSTPONE_HEADER","isFlightResponse","startsWith","RSC_CONTENT_TYPE_HEADER","ok","body","hash","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","allowPartialStream","flightResponse","cacheData","Promise","all","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","getNavigationBuildId","n","undefined","staticStageData","transportData","t","renderedSearch","q","couldBeIntercepted","supportsPerSegmentPrefetching","S","dynamicStaleTime","d","UnknownDynamicStaleTime","runtimePrefetchStream","p","responseHeaders","debugInfo","_debugInfo","revealAfter","_revealAfter","err","aborted","checkOfflineError","getOffline","waitForConnection","offline","console","error","response","InvariantError","stream","isPartial","stripIsPartialByte","responseStream","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","stream1","rest","tee","staticBodyClone","shellBodyClone","isResponsePartial","strippedResponse","Response","status","statusText","Object","defineProperty","value","cancel","l","staticStageByteLength","a","shellByteLength","responseBodyClone","byteLength","buffer","createNonTaskyPrefetchResponseStream","ReadableStream","start","controller","enqueue","close","createHaltingFlightResponse","fetchPromise","closed","reader","wrapper","onAbort","catch","once","pull","getReader","done","read","decodeFlightResponse","__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION","createFromNextFetch","fetchPriority","__NEXT_TEST_MODE","deploymentId","getDeploymentId","self","__next_r","NEXT_HTML_REQUEST_ID_HEADER","NEXT_REQUEST_ID_HEADER","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","priority","fetchUrl","setCacheBustingSearchParam","processed","fetch","then","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","searchParams","NEXT_RSC_UNION_QUERY","delete","rscResponse","href","flightStream","requestHeaders","callServer","findSourceMapURL","debugChannel","unstable_allowPartialStream","promiseForResponse"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;IAmrBsBA,WAAW;eAAXA;;IA+JNC,4BAA4B;eAA5BA;;IAnSAC,mBAAmB;eAAnBA;;IAnBMC,wBAAwB;eAAxBA;;IA3YAC,mBAAmB;eAAnBA;;IA2PAC,YAAY;eAAZA;;IA+GAC,qBAAqB;eAArBA;;IAlDAC,sBAAsB;eAAtBA;;;wBAlcf;gCAEwB;uBACT;k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C/BpD,uBAAuBA;QAEvBG,WAAWmG,UAAUE,IAAI,CAAC,CAAC,EAAErG,SAAS,EAAE,GAAKA;IAC/C;IAEA,OAAO4G;AACT;AAEO,SAASlL,6BACdoL,YAAwC,EACxCC,cAA0C,EAC1C1J,OAA0C;IAE1C,OAAOpB,yBAAyB6K,cAAc;QAC5CE,YAAAA,yBAAU;QACVC,kBAAAA,qCAAgB;QAChBC,cAAc7K,sBAAsBA,mBAAmB0K;QACvDI,6BAA6B9J,SAASyC;IACxC;AACF;AAEA,SAASoF,oBACPkC,kBAAqC,EACrCL,cAA8B;IAE9B,OAAO5K,gBAAgBiL,oBAAoB;QACzCJ,YAAAA,yBAAU;QACVC,kBAAAA,qCAAgB;QAChBC,cAAc7K,sBAAsBA,mBAAmB0K;IACzD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/router-reducer/fetch-server-response.ts"],"sourcesContent":["'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { fetch } from '../segment-cache/fetch'\nimport type {\n FlightRouterState,\n InitialRSCPayload,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers'\nimport type { PartialTransportData } from '../../../shared/lib/rsc-transport'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport { urlToUrlWithoutFlightMarker } from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n stripIsPartialByte,\n createNonTaskyPrefetchResponseStream,\n} from '../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n readonly signal?: AbortSignal\n}\n\nexport type StaticStageData<\n T extends\n | NavigationFlightResponse\n | InitialRSCPayload = NavigationFlightResponse,\n> = {\n readonly response: T\n readonly isResponsePartial: boolean\n}\n\ntype SpaFetchServerResponseResult = {\n transportData: PartialTransportData | null\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n supportsPerSegmentPrefetching: boolean\n postponed: boolean\n dynamicStaleTime: number\n staticStageData: StaticStageData | null\n runtimePrefetchStream: ReadableStream<Uint8Array> | null\n responseHeaders: Headers\n debugInfo: Array<any> | null\n /**\n * Dev only: resolves once the server has flushed the shell-stage content to\n * the stream (or earlier, on a cache miss). The navigation defers revealing\n * the response (resolving its deferred RSCs) until this settles, so React\n * doesn't render a boundary's children before their row has been decoded and\n * commit a premature Suspense fallback. `null` outside the streaming dev\n * render.\n */\n revealAfter: Promise<void> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2' | '3'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', () => {\n isPageUnloading = true\n })\n\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n isPageUnloading = false\n })\n}\n\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url\n\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url)\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt'\n } else {\n url.pathname += '.txt'\n }\n }\n }\n\n // During a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n const res = await createFetch<NavigationFlightResponse>(\n url,\n headers,\n 'auto',\n true,\n options.signal\n )\n\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../offline') as typeof import('../offline')\n notifyOnline()\n }\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\n const contentType = res.headers.get('content-type') || ''\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL)\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain')\n }\n }\n }\n\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash\n }\n\n return doMpaNavigation(responseUrl.toString())\n }\n\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n // This request passed `true` to `shouldImmediatelyDecode`, so the Flight\n // response promise is always initialized.\n const flightResponsePromise = res.flightResponsePromise!\n\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData,\n ])\n\n if (\n (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url)\n }\n\n if (flightResponse.n !== undefined) {\n // The server responded with an MPA navigation URL instead of a\n // SPA payload.\n return doMpaNavigation(flightResponse.n)\n }\n\n const staticStageData =\n cacheData !== null\n ? await resolveStaticStageData(cacheData, flightResponse, headers)\n : null\n\n return {\n transportData: flightResponse.t ?? null,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q as NormalizedSearch,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n staticStageData,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n revealAfter: flightResponse._revealAfter ?? null,\n }\n } catch (err) {\n if (options.signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request.\n // Rethrow so the caller treats it as canceled, rather than logging a\n // failure or falling back to an MPA navigation.\n throw err\n }\n\n // If the fetch rejected due to a network error, wait for connectivity\n // to be restored and then retry. checkOfflineError returns true for\n // network errors (and starts the polling loop); returns false for\n // intentional aborts/timeouts, which fall through to the MPA fallback.\n //\n // Note: when the user navigates multiple times while offline, each\n // navigation queues a separate retry here. Once connectivity returns,\n // all pending retries resume simultaneously. This is mitigated in PR 3\n // by reusing back-forward cache entries during offline navigation, which\n // avoids issuing new fetches in the first place.\n if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../offline') as typeof import('../offline')\n if (checkOfflineError(err)) {\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerResponse(url, options)\n }\n }\n\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\n\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString()\n }\n}\n\n// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null\n cacheData: Promise<FetchResponseCacheData | null>\n}\n\ntype FetchResponseCacheData = {\n isResponsePartial: boolean\n // Separate clones of the response body for stage extraction. The static\n // stage and shell stage are extracted from independent reads, so each\n // needs its own ReadableStream. Both are derived from a chain of `tee()`\n // calls in `processFetch`.\n staticBodyClone?: ReadableStream<Uint8Array>\n shellBodyClone?: ReadableStream<Uint8Array>\n}\n\n/**\n * Strips the leading isPartial byte from an RSC navigation response and\n * clones the body for segment cache extraction.\n *\n * When cache components is enabled, the server prepends a single byte:\n * '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped\n * before Flight decoding because it's not valid RSC data. The body is\n * cloned before Flight can consume it so the clone is available for later use.\n *\n * When cache components is disabled, returns the original response with\n * cacheData: null.\n */\nexport async function processFetch(response: Response): Promise<{\n response: Response\n cacheData: FetchResponseCacheData | null\n}> {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError(\n 'Expected RSC navigation response to have a body'\n )\n }\n\n const { stream, isPartial } = await stripIsPartialByte(response.body)\n\n let responseStream: ReadableStream<Uint8Array>\n let cacheData: FetchResponseCacheData\n\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n // Three readers needed: the main Flight decoder, the static-stage\n // extractor, and the shell-stage extractor. Tee twice.\n const [stream1, rest] = stream.tee()\n const [staticBodyClone, shellBodyClone] = rest.tee()\n responseStream = stream1\n cacheData = {\n isResponsePartial: isPartial,\n staticBodyClone,\n shellBodyClone,\n }\n } else {\n responseStream = stream\n cacheData = { isResponsePartial: isPartial }\n }\n\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n })\n\n // The Response constructor doesn't preserve `url` or `redirected` from\n // the original. We need both: `url` for React DevTools and `redirected`\n // for the redirect replay logic below.\n Object.defineProperty(strippedResponse, 'url', { value: response.url })\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected,\n })\n\n return { response: strippedResponse, cacheData }\n }\n\n return { response, cacheData: null }\n}\n\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */\nexport async function resolveStaticStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<StaticStageData<T> | null> {\n const { isResponsePartial, staticBodyClone } = cacheData\n\n if (staticBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n staticBodyClone.cancel()\n\n return { response: flightResponse, isResponsePartial: false }\n }\n\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const staticStageByteLength = await flightResponse.l\n const response = await decodeStageUntilBoundary<T>(\n staticBodyClone,\n staticStageByteLength,\n headers\n )\n\n return { response, isResponsePartial: true }\n }\n\n // No caching — cancel the unused clone.\n staticBodyClone.cancel()\n }\n\n return null\n}\n\n/**\n * Resolves the shell stage of a prerender response, performing a separate\n * Flight decode of the byte prefix when the shell differs from the main\n * response. Returns null when no separate decode is needed:\n *\n * - `a === undefined`: server didn't emit shell stage info.\n * - `a` resolves to `null`: the shell IS the main response — the caller can\n * reuse the existing decoded `flightResponse` if it needs a shell payload.\n *\n * Returns the decoded shell payload when `a` resolves to a number, i.e.\n * the shell is a strict prefix of the response and requires a separate\n * decode at that byte boundary.\n */\nexport async function resolveShellStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n const { shellBodyClone } = cacheData\n\n if (!shellBodyClone) {\n return null\n }\n\n if (flightResponse.a === undefined) {\n shellBodyClone.cancel()\n return null\n }\n\n const shellByteLength = await flightResponse.a\n if (shellByteLength === null) {\n // Shell == main response — caller reuses the existing flightResponse.\n shellBodyClone.cancel()\n return null\n }\n\n return decodeStageUntilBoundary<T>(shellBodyClone, shellByteLength, headers)\n}\n\n/**\n * Truncates and buffers a Flight stream clone at the given byte boundary and\n * decodes the prefix as a Flight payload. Used by the static-stage and\n * shell-stage extraction helpers.\n */\nexport async function decodeStageUntilBoundary<T>(\n responseBodyClone: ReadableStream<Uint8Array>,\n byteLength: number,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const { buffer } = await createNonTaskyPrefetchResponseStream(\n responseBodyClone,\n byteLength\n )\n return decodeBufferedStage<T>(buffer, headers)\n}\n\n/**\n * Decodes already-buffered Flight response bytes as a stage payload. The\n * bytes are delivered to Flight as a single chunk so all rows are processed\n * synchronously in one call — required for the thenable-status reads that\n * scope a response's late-resolving metadata (vary params, isPartial, ...)\n * to this decode.\n */\nexport function decodeBufferedStage<T>(\n buffer: Uint8Array,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(buffer)\n controller.close()\n },\n })\n return createFromNextReadableStream<T>(stream, headers, {\n allowPartialStream: true,\n })\n}\n\n// When an HMR refresh can be superseded, we decode its Flight response through\n// a wrapper stream we can close on abort. Closing the stream (rather than\n// letting the aborted fetch error it) makes React's Flight client mark\n// unresolved rows as halted: they suspend during render instead of rejecting,\n// so a superseded request never surfaces an error on an already-committed tree.\n// Because the stream is closed, there's also no unclosed-stream GC-root leak\n// (see #89610). The wrapper is created synchronously here so that the decode\n// starts at the same point `createFromNextFetch` would, preserving the\n// server-latency debug timing.\nfunction createHaltingFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal\n): Promise<T> & { _debugInfo?: Array<any> } {\n let closed = false\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n const wrapper = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n closed = true\n try {\n controller.close()\n } catch {\n // The controller may already be closed; nothing to do.\n }\n if (reader !== null) {\n reader.cancel().catch(() => {})\n }\n }\n if (signal.aborted) {\n onAbort()\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n },\n async pull(controller) {\n if (closed) {\n return\n }\n if (reader === null) {\n let response: Response\n try {\n response = await fetchPromise\n } catch (err) {\n // We don't inspect `err`. If the request was superseded, `onAbort`\n // already ran synchronously (abort listeners fire during\n // `signal.abort()`, before this rejection microtask), so `closed` is\n // true and the controller is already closed — erroring it would\n // throw, and a superseded request's failure is moot regardless of its\n // cause. Only a genuine, non-superseded failure reaches here with\n // `closed` still false; that is the case we surface.\n if (!closed) {\n controller.error(err)\n }\n return\n }\n if (closed) {\n // Aborted while awaiting the response. The `fetch` abort tears down\n // an in-flight request, but if it had already completed we still hold\n // an unread body; release it so it isn't left dangling.\n response.body?.cancel().catch(() => {})\n return\n }\n const body = response.body\n if (body === null) {\n controller.close()\n return\n }\n reader = body.getReader()\n }\n try {\n const { done, value } = await reader.read()\n if (closed) {\n return\n }\n if (done) {\n controller.close()\n } else {\n controller.enqueue(value)\n }\n } catch (err) {\n // Same as the fetch catch above: once superseded (`closed`) the\n // controller is already closed and the outcome is moot, so we swallow\n // the rejection unconditionally; only a real, non-superseded read\n // failure (`closed` still false) is surfaced.\n if (!closed) {\n controller.error(err)\n }\n }\n },\n })\n\n // React attaches `_debugInfo` to the returned promise at runtime.\n return createFromNextReadableStream<T>(wrapper, headers, {\n allowPartialStream: true,\n }) as Promise<T> & { _debugInfo?: Array<any> }\n}\n\n// Selects the Flight decode strategy: a halting wrapper for cancellable HMR\n// refreshes, otherwise the standard fetch-based decode. Gated to the dev server\n// (where HMR runs) so the wrapper is eliminated from production and\n// `--debug-prerender` bundles regardless of the flag.\nfunction decodeFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal | undefined\n): Promise<T> & { _debugInfo?: Array<any> } {\n if (\n process.env.__NEXT_DEV_SERVER &&\n process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION &&\n signal\n ) {\n return createHaltingFlightResponse<T>(fetchPromise, headers, signal)\n }\n return createFromNextFetch<T>(fetchPromise, headers)\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n await setCacheBustingSearchParam(fetchUrl, headers)\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n let fetchPromise = processed.then(({ response }) => response)\n\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because a\n // top-level prefetch response never blocks a navigation; if it hasn't already\n // been written into the cache by the time the navigation happens, the router\n // will go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n let browserResponse = await fetchPromise\n\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n\n let redirected = browserResponse.redirected\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20\n for (let n = 0; n < MAX_REDIRECTS; n++) {\n if (!browserResponse.redirected) {\n // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n await setCacheBustingSearchParam(fetchUrl, headers)\n processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n fetchPromise = processed.then(({ response }) => response)\n flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\n }\n\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponsePromise: flightResponsePromise,\n\n cacheData: processed.then(({ cacheData }) => cacheData),\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders | undefined,\n options?: { allowPartialStream?: boolean }\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream,\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n"],"names":["createFetch","createFromNextReadableStream","decodeBufferedStage","decodeStageUntilBoundary","fetchServerResponse","processFetch","resolveShellStageData","resolveStaticStageData","createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","doMpaNavigation","url","urlToUrlWithoutFlightMarker","URL","location","origin","toString","isPageUnloading","window","addEventListener","options","flightRouterState","nextUrl","headers","RSC_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","prepareFlightRouterStateForRequest","isHmrRefresh","NODE_ENV","NEXT_HMR_REFRESH_HEADER","NEXT_URL","originalUrl","__NEXT_CONFIG_OUTPUT","pathname","endsWith","res","signal","__NEXT_USE_OFFLINE","notifyOnline","responseUrl","canonicalUrl","redirected","contentType","get","interception","includes","postponed","NEXT_DID_POSTPONE_HEADER","isFlightResponse","startsWith","RSC_CONTENT_TYPE_HEADER","ok","body","hash","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","flightResponse","cacheData","Promise","all","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","getNavigationBuildId","n","undefined","staticStageData","transportData","t","renderedSearch","q","couldBeIntercepted","supportsPerSegmentPrefetching","S","dynamicStaleTime","d","UnknownDynamicStaleTime","runtimePrefetchStream","p","responseHeaders","debugInfo","_debugInfo","revealAfter","_revealAfter","err","aborted","checkOfflineError","getOffline","waitForConnection","offline","console","error","response","__NEXT_CACHE_COMPONENTS","InvariantError","stream","isPartial","stripIsPartialByte","responseStream","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","stream1","rest","tee","staticBodyClone","shellBodyClone","isResponsePartial","strippedResponse","Response","status","statusText","Object","defineProperty","value","cancel","l","staticStageByteLength","a","shellByteLength","responseBodyClone","byteLength","buffer","createNonTaskyPrefetchResponseStream","ReadableStream","start","controller","enqueue","close","allowPartialStream","createHaltingFlightResponse","fetchPromise","closed","reader","wrapper","onAbort","catch","once","pull","getReader","done","read","decodeFlightResponse","__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION","createFromNextFetch","fetchPriority","shouldImmediatelyDecode","__NEXT_TEST_MODE","deploymentId","getDeploymentId","self","__next_r","NEXT_HTML_REQUEST_ID_HEADER","NEXT_REQUEST_ID_HEADER","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","priority","fetchUrl","setCacheBustingSearchParam","processed","fetch","then","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","searchParams","NEXT_RSC_UNION_QUERY","delete","rscResponse","href","flightStream","requestHeaders","callServer","findSourceMapURL","debugChannel","unstable_allowPartialStream","promiseForResponse"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;IAoqBsBA,WAAW;eAAXA;;IA+JNC,4BAA4B;eAA5BA;;IAnSAC,mBAAmB;eAAnBA;;IAnBMC,wBAAwB;eAAxBA;;IA5XAC,mBAAmB;eAAnBA;;IA4OAC,YAAY;eAAZA;;IA+GAC,qBAAqB;eAArBA;;IAlDAC,sBAAsB;eAAtBA;;;wBAnbf;gCAEwB;uBACT;kCAmBf;+BACoB;qCACM;mCACkB;4CAER;6BACC;8BAEZ;mCACK;2BACS;uBAIvC;yBACiC;AAExC,MAAMC,2BACJC,gCAA+B;AACjC,MAAMC,kBACJC,uBAAsB;AAExB,IAAIC;AAIJ,IAAIC,QAAQC,GAAG,CAACC,iBAAiB,IAAIF,QAAQC,GAAG,CAACE,0BAA0B,EAAE;IAC3EJ,qBAAqB,AACnBK,QAAQ,2BACRL,kBAAkB;AACtB;AA6DA,SAASM,gBAAgBC,GAAW;IAClC,OAAOC,IAAAA,wCAA2B,EAAC,IAAIC,IAAIF,KAAKG,SAASC,MAAM,GAAGC,QAAQ;AAC5E;AAEA,IAAIC,kBAAkB;AAEtB,IAAI,OAAOC,WAAW,aAAa;IACjC,sEAAsE;IACtE,6EAA6E;IAC7E,6DAA6D;IAC7DA,OAAOC,gBAAgB,CAAC,YAAY;QAClCF,kBAAkB;IACpB;IAEA,2EAA2E;IAC3E,gDAAgD;IAChDC,OAAOC,gBAAgB,CAAC,YAAY;QAClCF,kBAAkB;IACpB;AACF;AAMO,eAAerB,oBACpBe,GAAQ,EACRS,OAAmC;IAEnC,MAAM,EAAEC,iBAAiB,EAAEC,OAAO,EAAE,GAAGF;IAEvC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E;QACxE,6BAA6B;QAC7BU,IAAIgH,gBAAgBhH,EAAE;QACtB5B,SAAS4I,gBAAgB5I,OAAO;QAChC6B,MAAM+G,gBAAgB/G,IAAI;QAC1BwD,QAAQuD,gBAAgBvD,MAAM;QAE9B,uEAAuE;QACvE,0EAA0E;QAC1E,+BAA+B;QAC/BpD,uBAAuBA;QAEvBE,WAAWsG,UAAUE,IAAI,CAAC,CAAC,EAAExG,SAAS,EAAE,GAAKA;IAC/C;IAEA,OAAO+G;AACT;AAEO,SAAShL,6BACdkL,YAAwC,EACxCC,cAA0C,EAC1CxJ,OAA0C;IAE1C,OAAOpB,yBAAyB2K,cAAc;QAC5CE,YAAAA,yBAAU;QACVC,kBAAAA,qCAAgB;QAChBC,cAAc3K,sBAAsBA,mBAAmBwK;QACvDI,6BAA6B5J,SAAS2G;IACxC;AACF;AAEA,SAASe,oBACPmC,kBAAqC,EACrCL,cAA8B;IAE9B,OAAO1K,gBAAgB+K,oBAAoB;QACzCJ,YAAAA,yBAAU;QACVC,kBAAAA,qCAAgB;QAChBC,cAAc3K,sBAAsBA,mBAAmBwK;IACzD;AACF","ignoreList":[0]}

@@ -278,2 +278,3 @@ import type React from 'react';

metadataVaryPath: PageVaryPath | null;
treeDivergedFromBase: boolean;
};

@@ -280,0 +281,0 @@ export declare function convertRootFlightRouterStateToRouteTree(flightRouterState: FlightRouterState, renderedSearch: NormalizedSearch, acc: RouteTreeAccumulator): RouteTree<null>;

@@ -22,2 +22,3 @@ /**

dynamicStaleAt: number;
treeDivergedFromBase: boolean;
};

@@ -24,0 +25,0 @@ export declare function convertServerPatchToFullTree(now: number, currentTree: FlightRouterState, transportData: PartialTransportData | null, renderedSearch: string, dynamicStaleTimeSeconds: number): NavigationSeed;

@@ -36,2 +36,3 @@ /**

const _segment = require("../../../shared/lib/segment");
const _matchsegments = require("../match-segments");
const _varypath = require("./vary-path");

@@ -52,3 +53,4 @@ const _cache = require("./cache");

const acc = {
metadataVaryPath: null
metadataVaryPath: null,
treeDivergedFromBase: false
};

@@ -77,3 +79,4 @@ let routeTree;

headVaryParams,
dynamicStaleAt: (0, _bfcache.computeDynamicStaleAt)(now, dynamicStaleTimeSeconds)
dynamicStaleAt: (0, _bfcache.computeDynamicStaleAt)(now, dynamicStaleTimeSeconds),
treeDivergedFromBase: acc.treeDivergedFromBase
};

@@ -143,5 +146,10 @@ }

function decodeTransportTreeIntoRouteTree(transportNode, baseRouterState, renderedSearch, acc) {
return decodeTransportNode(transportNode, baseRouterState ?? undefined, _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, acc);
return decodeTransportNode(transportNode, baseRouterState ?? undefined, baseRouterState ?? undefined, _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, acc);
}
function decodeTransportNode(node, base, requestKey, parentPartialVaryPath, parentRenderedSearch, acc) {
function decodeTransportNode(node, base, // The base node to compare segment identities against (see
// NavigationSeed.treeDivergedFromBase). Tracked separately from `base`:
// inheritance drops the base inside authoritative subtrees, where the
// comparison must continue, and keeps it through inactive parallel routes,
// where the comparison must stop.
compareBase, requestKey, parentPartialVaryPath, parentRenderedSearch, acc) {
const nodeData = node.d;

@@ -152,2 +160,23 @@ const inheritsFromBase = nodeData !== undefined && nodeData.r === null;

const originalSegment = (0, _rsctransport.transportSegmentToSegment)(node.s);
if (compareBase !== undefined && !acc.treeDivergedFromBase) {
// Every transport node echoes the segment's identity, even "skipped"
// ones, so each position can be compared against the base.
const transportSegment = node.s;
if (typeof transportSegment !== 'string' && transportSegment.k == null) {
// The server omitted the param value for the client to parse from the
// URL (see the TODO in transportSegmentToSegment). Nothing to compare;
// the children are still checked.
} else {
const baseSegment = compareBase[0];
if (typeof originalSegment === 'string' && typeof baseSegment === 'string' && originalSegment.startsWith(_segment.PAGE_SEGMENT_KEY) && baseSegment.startsWith(_segment.PAGE_SEGMENT_KEY)) {
// Page segments match modulo embedded search params, which are
// validated separately (see getRenderedSearch).
} else if (originalSegment === _segment.DEFAULT_SEGMENT_KEY) {
// A default filled in by the server is not a claim about the
// position's identity.
} else if (!(0, _matchsegments.matchSegment)(baseSegment, originalSegment)) {
acc.treeDivergedFromBase = true;
}
}
}
const baseHints = inheritedBase !== undefined ? inheritedBase[4] ?? 0 : 0;

@@ -178,4 +207,21 @@ let prefetchHints = node.h ?? baseHints;

const childSegment = (0, _rsctransport.transportSegmentToSegment)(childNode.s);
let childCompareBase;
if (compareBase !== undefined && !acc.treeDivergedFromBase) {
const childCompareCandidate = compareBase[1][parallelRouteKey];
if (childCompareCandidate === undefined) {
// A slot the base tree doesn't have. Unless the server merely
// filled it with a default, the trees have different structures.
if (childSegment !== _segment.DEFAULT_SEGMENT_KEY) {
acc.treeDivergedFromBase = true;
}
} else if ((childCompareCandidate[2] ?? null) !== null) {
// The base branch carries a refresh state: an inactive parallel
// route reused from a different route (e.g. a "default" slot). The
// server's answer is expected to differ, so skip the branch.
} else {
childCompareBase = childCompareCandidate;
}
}
const childRequestKey = (0, _segmentvalueencoding.appendSegmentRequestKeyPart)(requestKey, parallelRouteKey, (0, _segmentvalueencoding.createSegmentRequestKeyPart)(childSegment));
const childTree = decodeTransportNode(childNode, childBase, childRequestKey, partialVaryPath, renderedSearch, acc);
const childTree = decodeTransportNode(childNode, childBase, childCompareBase, childRequestKey, partialVaryPath, renderedSearch, acc);
if (slots === null) {

@@ -182,0 +228,0 @@ slots = new Map();

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/segment-cache/decode-server-response.ts"],"sourcesContent":["/**\n * Decoding of RSC server responses (the transport format defined in\n * shared/lib/rsc-transport) into the client's own representations. This is\n * the only place on the client that consumes transport types; everything\n * downstream operates on RouteTree / NavigationSeed / CacheNode.\n */\n\nimport type {\n FlightRouterState,\n HeadData,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type {\n PartialTransportData,\n PartialTransportNode,\n} from '../../../shared/lib/rsc-transport'\nimport { transportSegmentToSegment } from '../../../shared/lib/rsc-transport'\nimport type { VaryParamsIterable } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n type SegmentRequestKey,\n ROOT_SEGMENT_REQUEST_KEY,\n appendSegmentRequestKeyPart,\n createSegmentRequestKeyPart,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport type { NormalizedSearch } from './cache-key'\nimport type {\n PageVaryPath,\n PartialSegmentVaryPath,\n SegmentVaryPath,\n} from './vary-path'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizeMetadataVaryPath,\n finalizePageVaryPath,\n getPartialLayoutVaryPath,\n getPartialPageVaryPath,\n getShellSegmentVaryPath,\n} from './vary-path'\nimport {\n type RouteTree,\n type RSCSegmentData,\n type RefreshState,\n type RouteTreeAccumulator,\n convertFlightRouterStateToRouteTree,\n convertRootFlightRouterStateToRouteTree,\n} from './cache'\nimport { computeDynamicStaleAt } from './bfcache'\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree<RSCSegmentData | null>\n metadataVaryPath: PageVaryPath | null\n head: HeadData | null\n isHeadPartial: boolean\n headVaryParams: VaryParamsIterable | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n transportData: PartialTransportData | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server responds with a\n // transport tree that covers only the parts of the route that have changed.\n // Decode it into a full RouteTree, overlaying it on the base tree so that\n // the slots the response carries no information about are reused from the\n // client's current state.\n //\n // The returned RouteTree carries the response's render output on each node\n // (RSCSegmentData). Pass a null transportData to convert the base tree\n // alone (e.g. for refreshes and history restores, before a response\n // is received).\n const acc: { metadataVaryPath: PageVaryPath | null } = {\n metadataVaryPath: null,\n }\n let routeTree: RouteTree<RSCSegmentData | null>\n let head: HeadData | null = null\n let isHeadPartial = true\n let headVaryParams: VaryParamsIterable | null = null\n if (transportData !== null) {\n routeTree = decodeTransportTreeIntoRouteTree(\n transportData.t,\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n const transportHead = transportData.h\n if (transportHead !== undefined) {\n head = transportHead.r\n isHeadPartial = transportHead.p\n headVaryParams = transportHead.v\n }\n } else {\n routeTree = convertRootFlightRouterStateToRouteTree(\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n }\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n renderedSearch,\n head,\n isHeadPartial,\n headVaryParams,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\n/**\n * Creates a RouteTree node for a segment, with its identity and cache-key\n * information (vary paths, page-ness, the normalized segment value)\n * initialized, and the remaining fields set to their defaults. The caller\n * finishes initializing those in place after recursing into the children.\n * Shared by the FlightRouterState converter and the transport decoder so the\n * two cannot drift, and so every node they produce has the same property\n * order (one hidden class).\n */\nexport function createRouteTreeNode<TData>(\n originalSegment: FlightRouterStateSegment,\n isRootParam: boolean,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<TData | null> {\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n if (Array.isArray(originalSegment)) {\n isPage = false\n const paramCacheKey = originalSegment[1]\n const paramName = originalSegment[0]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n paramCacheKey,\n paramName,\n isRootParam\n )\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n segment = originalSegment\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n return {\n requestKey,\n segment,\n shellVaryPath: getShellSegmentVaryPath(varyPath),\n refreshState: null,\n data: null,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. If isPage were\n // wrong it would break the behavior and we'd catch it quickly.\n varyPath: varyPath as any,\n isPage: isPage as boolean as any,\n slots: null,\n prefetchHints: 0,\n }\n}\n\n/**\n * Decodes a response's transport tree into a RouteTree, using the client's\n * current router state as the base for the parts of the route the response\n * carries no information about.\n *\n * The response is an overlay over the base:\n *\n * - Nodes with rendered output — and nodes with no data at all, which are\n * server-sent structure whose output the client fetches lazily — are\n * authoritative: their identity, hints, and subtree come entirely from\n * the response.\n * - Skipped nodes (data with a null rsc) sit on the path from the root down\n * to the rendered subtrees. The client is expected to already have them,\n * so their refresh state and hints are inherited from the base tree, and\n * any slot the response doesn't mention is reused from the base as-is.\n *\n * TODO: The base is a FlightRouterState only because that's the\n * representation the client router currently renders from (the router\n * reducer's `state.tree`, which the CacheNode tree and layout-router are\n * keyed against). Once the rendering path is updated to use RouteTree as its\n * source of truth, the base tree here can be a RouteTree, and the base-only\n * conversion path (convertFlightRouterStateToRouteTree) goes away with it.\n */\nexport function decodeTransportTreeIntoRouteTree(\n transportNode: PartialTransportNode,\n baseRouterState: FlightRouterState | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n return decodeTransportNode(\n transportNode,\n baseRouterState ?? undefined,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nfunction decodeTransportNode(\n node: PartialTransportNode,\n base: FlightRouterState | undefined,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n const nodeData = node.d\n const inheritsFromBase = nodeData !== undefined && nodeData.r === null\n // The base node this position inherits from, when it does.\n const inheritedBase = inheritsFromBase ? base : undefined\n\n const originalSegment = transportSegmentToSegment(node.s)\n\n const baseHints = inheritedBase !== undefined ? (inheritedBase[4] ?? 0) : 0\n let prefetchHints = node.h ?? baseHints\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n // Inherited positions keep the base tree's refresh state. Its rendered\n // search is updated to this response's, since all pages within the same\n // response share the same search value. (The refresh state acts like a\n // \"context provider\" for inactive parallel routes.)\n const baseCompressedRefreshState =\n inheritedBase !== undefined ? (inheritedBase[2] ?? null) : null\n const refreshState: RefreshState | null =\n baseCompressedRefreshState !== null\n ? {\n canonicalUrl: baseCompressedRefreshState[0] as string,\n renderedSearch: parentRenderedSearch,\n }\n : null\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n const tree = createRouteTreeNode<RSCSegmentData>(\n originalSegment,\n isRootParam,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n acc\n )\n tree.refreshState = refreshState\n const partialVaryPath = tree.isPage\n ? getPartialPageVaryPath(tree.varyPath)\n : getPartialLayoutVaryPath(tree.varyPath)\n\n let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null\n const transportChildren = node.c\n const baseChildren =\n inheritedBase !== undefined ? inheritedBase[1] : undefined\n if (transportChildren !== undefined) {\n for (const [parallelRouteKey, childNode] of transportChildren) {\n const childBase =\n baseChildren !== undefined ? baseChildren[parallelRouteKey] : undefined\n const childSegment = transportSegmentToSegment(childNode.s)\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childSegment)\n )\n const childTree = decodeTransportNode(\n childNode,\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n if (baseChildren !== undefined) {\n // Slots the response carries no information about are reused from the\n // base tree, structure-only.\n for (const parallelRouteKey in baseChildren) {\n if (\n transportChildren !== undefined &&\n transportChildren.has(parallelRouteKey)\n ) {\n continue\n }\n const childBase = baseChildren[parallelRouteKey]\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childBase[0])\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n\n if (inheritsFromBase) {\n // Recompute the propagated \"subtree\" prefetch hints for this segment,\n // since its children may combine response and base subtrees. Mirrors the\n // propagation done on the server in createTransportTreeFromLoaderTree.\n let propagated = prefetchHints & ~SubtreePrefetchHints\n if (slots !== null) {\n for (const childTree of slots.values()) {\n propagated = propagateSubtreeBits(propagated, childTree.prefetchHints)\n }\n }\n prefetchHints = propagated\n }\n\n if (nodeData !== undefined) {\n tree.data = {\n rsc: nodeData.r,\n isPartial: nodeData.p,\n varyParams: nodeData.v,\n }\n }\n\n tree.slots = slots\n tree.prefetchHints = prefetchHints\n return tree\n}\n"],"names":["convertServerPatchToFullTree","createRouteTreeNode","decodeTransportTreeIntoRouteTree","now","currentTree","transportData","renderedSearch","dynamicStaleTimeSeconds","acc","metadataVaryPath","routeTree","head","isHeadPartial","headVaryParams","t","transportHead","h","undefined","r","p","v","convertRootFlightRouterStateToRouteTree","dynamicStaleAt","computeDynamicStaleAt","originalSegment","isRootParam","requestKey","parentPartialVaryPath","segment","partialVaryPath","isPage","varyPath","Array","isArray","paramCacheKey","paramName","appendLayoutVaryPath","finalizeLayoutVaryPath","endsWith","PAGE_SEGMENT_KEY","finalizePageVaryPath","finalizeMetadataVaryPath","shellVaryPath","getShellSegmentVaryPath","refreshState","data","slots","prefetchHints","transportNode","baseRouterState","decodeTransportNode","ROOT_SEGMENT_REQUEST_KEY","node","base","parentRenderedSearch","nodeData","d","inheritsFromBase","inheritedBase","transportSegmentToSegment","s","baseHints","PrefetchHint","IsRootLayoutOrAbove","baseCompressedRefreshState","canonicalUrl","tree","getPartialPageVaryPath","getPartialLayoutVaryPath","transportChildren","c","baseChildren","parallelRouteKey","childNode","childBase","childSegment","childRequestKey","appendSegmentRequestKeyPart","createSegmentRequestKeyPart","childTree","Map","set","has","convertFlightRouterStateToRouteTree","propagated","SubtreePrefetchHints","values","propagateSubtreeBits","rsc","isPartial","varyParams"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;;;;;;IA4DeA,4BAA4B;eAA5BA;;IAiEAC,mBAAmB;eAAnBA;;IA0GAC,gCAAgC;eAAhCA;;;gCA5NT;8BAKmC;sCAOnC;yBAC0B;0BAe1B;uBAQA;yBAC+B;AAY/B,SAASF,6BACdG,GAAW,EACXC,WAA8B,EAC9BC,aAA0C,EAC1CC,cAAsB,EACtBC,uBAA+B;IAE/B,qEAAqE;IACrE,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,0BAA0B;IAC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B;IACF;IACA,IAAIR,iBAAiBtD,WAAW;QAC9B,sEAAsE;QACtE,6BAA6B;QAC7B,IAAK,MAAMuD,oBAAoBD,aAAc;YAC3C,IACEF,sBAAsBpD,aACtBoD,kBAAkBa,GAAG,CAACV,mBACtB;gBACA;YACF;YACA,MAAME,YAAYH,YAAY,CAACC,iBAAiB;YAChD,MAAMI,kBAAkBC,IAAAA,iDAA2B,EACjDnD,YACA8C,kBACAM,IAAAA,iDAA2B,EAACJ,SAAS,CAAC,EAAE;YAE1C,MAAMK,YAAYI,IAAAA,0CAAmC,EACnDT,WACAE,iBACA/C,iBACAvB,gBACAE;YAEF,IAAIsC,UAAU,MAAM;gBAClBA,QAAQ,IAAIkC;YACd;YACAlC,MAAMmC,GAAG,CAACT,kBAAkBO;QAC9B;IACF;IAEA,IAAItB,kBAAkB;QACpB,sEAAsE;QACtE,yEAAyE;QACzE,uEAAuE;QACvE,IAAI2B,aAAarC,gBAAgB,CAACsC,oCAAoB;QACtD,IAAIvC,UAAU,MAAM;YAClB,KAAK,MAAMiC,aAAajC,MAAMwC,MAAM,GAAI;gBACtCF,aAAaG,IAAAA,oCAAoB,EAACH,YAAYL,UAAUhC,aAAa;YACvE;QACF;QACAA,gBAAgBqC;IAClB;IAEA,IAAI7B,aAAatC,WAAW;QAC1BiD,KAAKrB,IAAI,GAAG;YACV2C,KAAKjC,SAASrC,CAAC;YACfuE,WAAWlC,SAASpC,CAAC;YACrBuE,YAAYnC,SAASnC,CAAC;QACxB;IACF;IAEA8C,KAAKpB,KAAK,GAAGA;IACboB,KAAKnB,aAAa,GAAGA;IACrB,OAAOmB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/segment-cache/decode-server-response.ts"],"sourcesContent":["/**\n * Decoding of RSC server responses (the transport format defined in\n * shared/lib/rsc-transport) into the client's own representations. This is\n * the only place on the client that consumes transport types; everything\n * downstream operates on RouteTree / NavigationSeed / CacheNode.\n */\n\nimport type {\n FlightRouterState,\n HeadData,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type {\n PartialTransportData,\n PartialTransportNode,\n} from '../../../shared/lib/rsc-transport'\nimport { transportSegmentToSegment } from '../../../shared/lib/rsc-transport'\nimport type { VaryParamsIterable } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n type SegmentRequestKey,\n ROOT_SEGMENT_REQUEST_KEY,\n appendSegmentRequestKeyPart,\n createSegmentRequestKeyPart,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport {\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport type { NormalizedSearch } from './cache-key'\nimport type {\n PageVaryPath,\n PartialSegmentVaryPath,\n SegmentVaryPath,\n} from './vary-path'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizeMetadataVaryPath,\n finalizePageVaryPath,\n getPartialLayoutVaryPath,\n getPartialPageVaryPath,\n getShellSegmentVaryPath,\n} from './vary-path'\nimport {\n type RouteTree,\n type RSCSegmentData,\n type RefreshState,\n type RouteTreeAccumulator,\n convertFlightRouterStateToRouteTree,\n convertRootFlightRouterStateToRouteTree,\n} from './cache'\nimport { computeDynamicStaleAt } from './bfcache'\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree<RSCSegmentData | null>\n metadataVaryPath: PageVaryPath | null\n head: HeadData | null\n isHeadPartial: boolean\n headVaryParams: VaryParamsIterable | null\n dynamicStaleAt: number\n // Whether the response rendered a segment whose identity differs from the\n // base tree's at the same position (inactive parallel route branches are\n // expected to differ and don't count). Only meaningful when the base is a\n // request tree derived from a cached route entry, as during a prefetch:\n // divergence then means the entry doesn't describe what the server renders\n // — the URL has a rewrite that behaves dynamically (see\n // fetchSegmentPrefetchesUsingDynamicRequest). During a navigation the base\n // is the current page's tree, so divergence carries no signal. False when\n // there was no base to compare against.\n treeDivergedFromBase: boolean\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n transportData: PartialTransportData | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server responds with a\n // transport tree that covers only the parts of the route that have changed.\n // Decode it into a full RouteTree, overlaying it on the base tree so that\n // the slots the response carries no information about are reused from the\n // client's current state.\n //\n // The returned RouteTree carries the response's render output on each node\n // (RSCSegmentData). Pass a null transportData to convert the base tree\n // alone (e.g. for refreshes and history restores, before a response\n // is received).\n const acc: RouteTreeAccumulator = {\n metadataVaryPath: null,\n treeDivergedFromBase: false,\n }\n let routeTree: RouteTree<RSCSegmentData | null>\n let head: HeadData | null = null\n let isHeadPartial = true\n let headVaryParams: VaryParamsIterable | null = null\n if (transportData !== null) {\n routeTree = decodeTransportTreeIntoRouteTree(\n transportData.t,\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n const transportHead = transportData.h\n if (transportHead !== undefined) {\n head = transportHead.r\n isHeadPartial = transportHead.p\n headVaryParams = transportHead.v\n }\n } else {\n routeTree = convertRootFlightRouterStateToRouteTree(\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n }\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n renderedSearch,\n head,\n isHeadPartial,\n headVaryParams,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n treeDivergedFromBase: acc.treeDivergedFromBase,\n }\n}\n\n/**\n * Creates a RouteTree node for a segment, with its identity and cache-key\n * information (vary paths, page-ness, the normalized segment value)\n * initialized, and the remaining fields set to their defaults. The caller\n * finishes initializing those in place after recursing into the children.\n * Shared by the FlightRouterState converter and the transport decoder so the\n * two cannot drift, and so every node they produce has the same property\n * order (one hidden class).\n */\nexport function createRouteTreeNode<TData>(\n originalSegment: FlightRouterStateSegment,\n isRootParam: boolean,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<TData | null> {\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n if (Array.isArray(originalSegment)) {\n isPage = false\n const paramCacheKey = originalSegment[1]\n const paramName = originalSegment[0]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n paramCacheKey,\n paramName,\n isRootParam\n )\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n segment = originalSegment\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n return {\n requestKey,\n segment,\n shellVaryPath: getShellSegmentVaryPath(varyPath),\n refreshState: null,\n data: null,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. If isPage were\n // wrong it would break the behavior and we'd catch it quickly.\n varyPath: varyPath as any,\n isPage: isPage as boolean as any,\n slots: null,\n prefetchHints: 0,\n }\n}\n\n/**\n * Decodes a response's transport tree into a RouteTree, using the client's\n * current router state as the base for the parts of the route the response\n * carries no information about.\n *\n * The response is an overlay over the base:\n *\n * - Nodes with rendered output — and nodes with no data at all, which are\n * server-sent structure whose output the client fetches lazily — are\n * authoritative: their identity, hints, and subtree come entirely from\n * the response.\n * - Skipped nodes (data with a null rsc) sit on the path from the root down\n * to the rendered subtrees. The client is expected to already have them,\n * so their refresh state and hints are inherited from the base tree, and\n * any slot the response doesn't mention is reused from the base as-is.\n *\n * TODO: The base is a FlightRouterState only because that's the\n * representation the client router currently renders from (the router\n * reducer's `state.tree`, which the CacheNode tree and layout-router are\n * keyed against). Once the rendering path is updated to use RouteTree as its\n * source of truth, the base tree here can be a RouteTree, and the base-only\n * conversion path (convertFlightRouterStateToRouteTree) goes away with it.\n */\nexport function decodeTransportTreeIntoRouteTree(\n transportNode: PartialTransportNode,\n baseRouterState: FlightRouterState | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n return decodeTransportNode(\n transportNode,\n baseRouterState ?? undefined,\n baseRouterState ?? undefined,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nfunction decodeTransportNode(\n node: PartialTransportNode,\n base: FlightRouterState | undefined,\n // The base node to compare segment identities against (see\n // NavigationSeed.treeDivergedFromBase). Tracked separately from `base`:\n // inheritance drops the base inside authoritative subtrees, where the\n // comparison must continue, and keeps it through inactive parallel routes,\n // where the comparison must stop.\n compareBase: FlightRouterState | undefined,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n const nodeData = node.d\n const inheritsFromBase = nodeData !== undefined && nodeData.r === null\n // The base node this position inherits from, when it does.\n const inheritedBase = inheritsFromBase ? base : undefined\n\n const originalSegment = transportSegmentToSegment(node.s)\n\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n // Every transport node echoes the segment's identity, even \"skipped\"\n // ones, so each position can be compared against the base.\n const transportSegment = node.s\n if (typeof transportSegment !== 'string' && transportSegment.k == null) {\n // The server omitted the param value for the client to parse from the\n // URL (see the TODO in transportSegmentToSegment). Nothing to compare;\n // the children are still checked.\n } else {\n const baseSegment = compareBase[0]\n if (\n typeof originalSegment === 'string' &&\n typeof baseSegment === 'string' &&\n originalSegment.startsWith(PAGE_SEGMENT_KEY) &&\n baseSegment.startsWith(PAGE_SEGMENT_KEY)\n ) {\n // Page segments match modulo embedded search params, which are\n // validated separately (see getRenderedSearch).\n } else if (originalSegment === DEFAULT_SEGMENT_KEY) {\n // A default filled in by the server is not a claim about the\n // position's identity.\n } else if (!matchSegment(baseSegment, originalSegment)) {\n acc.treeDivergedFromBase = true\n }\n }\n }\n\n const baseHints = inheritedBase !== undefined ? (inheritedBase[4] ?? 0) : 0\n let prefetchHints = node.h ?? baseHints\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n // Inherited positions keep the base tree's refresh state. Its rendered\n // search is updated to this response's, since all pages within the same\n // response share the same search value. (The refresh state acts like a\n // \"context provider\" for inactive parallel routes.)\n const baseCompressedRefreshState =\n inheritedBase !== undefined ? (inheritedBase[2] ?? null) : null\n const refreshState: RefreshState | null =\n baseCompressedRefreshState !== null\n ? {\n canonicalUrl: baseCompressedRefreshState[0] as string,\n renderedSearch: parentRenderedSearch,\n }\n : null\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n const tree = createRouteTreeNode<RSCSegmentData>(\n originalSegment,\n isRootParam,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n acc\n )\n tree.refreshState = refreshState\n const partialVaryPath = tree.isPage\n ? getPartialPageVaryPath(tree.varyPath)\n : getPartialLayoutVaryPath(tree.varyPath)\n\n let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null\n const transportChildren = node.c\n const baseChildren =\n inheritedBase !== undefined ? inheritedBase[1] : undefined\n if (transportChildren !== undefined) {\n for (const [parallelRouteKey, childNode] of transportChildren) {\n const childBase =\n baseChildren !== undefined ? baseChildren[parallelRouteKey] : undefined\n const childSegment = transportSegmentToSegment(childNode.s)\n\n let childCompareBase: FlightRouterState | undefined\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n const childCompareCandidate = compareBase[1][parallelRouteKey]\n if (childCompareCandidate === undefined) {\n // A slot the base tree doesn't have. Unless the server merely\n // filled it with a default, the trees have different structures.\n if (childSegment !== DEFAULT_SEGMENT_KEY) {\n acc.treeDivergedFromBase = true\n }\n } else if ((childCompareCandidate[2] ?? null) !== null) {\n // The base branch carries a refresh state: an inactive parallel\n // route reused from a different route (e.g. a \"default\" slot). The\n // server's answer is expected to differ, so skip the branch.\n } else {\n childCompareBase = childCompareCandidate\n }\n }\n\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childSegment)\n )\n const childTree = decodeTransportNode(\n childNode,\n childBase,\n childCompareBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n if (baseChildren !== undefined) {\n // Slots the response carries no information about are reused from the\n // base tree, structure-only.\n for (const parallelRouteKey in baseChildren) {\n if (\n transportChildren !== undefined &&\n transportChildren.has(parallelRouteKey)\n ) {\n continue\n }\n const childBase = baseChildren[parallelRouteKey]\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childBase[0])\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n\n if (inheritsFromBase) {\n // Recompute the propagated \"subtree\" prefetch hints for this segment,\n // since its children may combine response and base subtrees. Mirrors the\n // propagation done on the server in createTransportTreeFromLoaderTree.\n let propagated = prefetchHints & ~SubtreePrefetchHints\n if (slots !== null) {\n for (const childTree of slots.values()) {\n propagated = propagateSubtreeBits(propagated, childTree.prefetchHints)\n }\n }\n prefetchHints = propagated\n }\n\n if (nodeData !== undefined) {\n tree.data = {\n rsc: nodeData.r,\n isPartial: nodeData.p,\n varyParams: nodeData.v,\n }\n }\n\n tree.slots = slots\n tree.prefetchHints = prefetchHints\n return tree\n}\n"],"names":["convertServerPatchToFullTree","createRouteTreeNode","decodeTransportTreeIntoRouteTree","now","currentTree","transportData","renderedSearch","dynamicStaleTimeSeconds","acc","metadataVaryPath","treeDivergedFromBase","routeTree","head","isHeadPartial","headVaryParams","t","transportHead","h","undefined","r","p","v","convertRootFlightRouterStateToRouteTree","dynamicStaleAt","computeDynamicStaleAt","originalSegment","isRootParam","requestKey","parentPartialVaryPath","segment","partialVaryPath","isPage","varyPath","Array","isArray","paramCacheKey","paramName","appendLayoutVaryPath","finalizeLayoutVaryPath","endsWith","PAGE_SEGMENT_KEY","finalizePageVaryPath","finalizeMetadataVaryPath","shellVaryPath","getShellSegmentVaryPath","refreshState","data","slots","prefetchHints","transportNode","baseRouterState","decodeTransportNode","ROOT_SEGMENT_REQUEST_KEY","node","base","compareBase","parentRenderedSearch","nodeData","d","inheritsFromBase","inheritedBase","transportSegmentToSegment","s","transportSegment","k","baseSegment","startsWith","DEFAULT_SEGMENT_KEY","matchSegment","baseHints","PrefetchHint","IsRootLayoutOrAbove","baseCompressedRefreshState","canonicalUrl","tree","getPartialPageVaryPath","getPartialLayoutVaryPath","transportChildren","c","baseChildren","parallelRouteKey","childNode","childBase","childSegment","childCompareBase","childCompareCandidate","childRequestKey","appendSegmentRequestKeyPart","createSegmentRequestKeyPart","childTree","Map","set","has","convertFlightRouterStateToRouteTree","propagated","SubtreePrefetchHints","values","propagateSubtreeBits","rsc","isPartial","varyParams"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;;;;;;IA0EeA,4BAA4B;eAA5BA;;IAmEAC,mBAAmB;eAAnBA;;IA0GAC,gCAAgC;eAAhCA;;;gCA5OT;8BAKmC;sCAOnC;yBAIA;+BACsB;0BAetB;uBAQA;yBAC+B;AAsB/B,SAASF,6BACdG,GAAW,EACXC,WAA8B,EAC9BC,aAA0C,EAC1CC,cAAsB,EACtBC,uBAA+B;IAE/B,qEAAqE;IACrE,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,0BAA0B;IAC1B,EAAE;IACF,2EAA2E;IAC3E,uEAAuE;IACvE,oEAAoE;IACpE,gBAAgB;IAChB,MAAMC,MAA4B;QAChCC,kBAAkB;QAClBC,sBAAsB;IACxB;IACA,IAAIC;IACJ,IAAIC,OAAwB;IAC5B,IAAIC,gBAAgB;IACpB,IAAIC,iBAA4C;IAChD,IAAIT,kBAAkB,MAAM;QAC1BM,YAAYT,iCACVG,cAAcU,CAAC,EACfX,aACAE,gBACAE;QAEF,MAAMQ,gBAAgBX,cAAcY,CAAC;QACrC,IAAID,kBAAkBE,WAAW;YAC/BN,OAAOI,cAAcG,CAAC;YACtBN,gBAAgBG,cAAcI,CAAC;YAC/BN,iBAAiBE,cAAcK,CAAC;QAClC;IACF,OAAO;QACLV,YAAYW,IAAAA,8CAAuC,EACjDlB,aACAE,gBACAE;IAEJ;IAEA,OAAO;QACLG;QACAF,kBAAkBD,IAAIC,gBAAgB;QACtCH;QACAM;QACAC;QACAC;QACAS,gBAAgBC,IAAAA,8BAAqB,EAACrB,KAAKI;QAC3CG,sBAAsBF,IAAIE,oBAAoB;IAChD;AACF;AAWO,SAAST,oBACdwB,eAAyC,EACzCC,WAAoB,EACpBC,UAA6B,EAC7BC,qBAAoD,EACpDtB,cAAgC,E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AAa;YACvE;QACF;QACAA,gBAAgB8C;IAClB;IAEA,IAAIrC,aAAavC,WAAW;QAC1BwD,KAAK5B,IAAI,GAAG;YACVoD,KAAKzC,SAAStC,CAAC;YACfgF,WAAW1C,SAASrC,CAAC;YACrBgF,YAAY3C,SAASpC,CAAC;QACxB;IACF;IAEAqD,KAAK3B,KAAK,GAAGA;IACb2B,KAAK1B,aAAa,GAAGA;IACrB,OAAO0B;AACT","ignoreList":[0]}

@@ -215,3 +215,5 @@ "use strict";

headVaryParams: null,
dynamicStaleAt: (0, _bfcache.computeDynamicStaleAt)(now, _bfcache.UnknownDynamicStaleTime)
dynamicStaleAt: (0, _bfcache.computeDynamicStaleAt)(now, _bfcache.UnknownDynamicStaleTime),
// Not derived from a server response; no base to diverge from.
treeDivergedFromBase: false
};

@@ -218,0 +220,0 @@ return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, null, route, // Not an HMR refresh, so there's no request generation to cancel.

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport type { CacheMap } from './cache-map'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n map\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n scrollRef: state.scrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","segmentCacheMap","map","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","getLinkForCurrentNavigation","fetchStrategy","FetchStrategy","Full","routeTree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","metadataVaryPath","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","computeDynamicStaleAt","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","discoverKnownRoute","search","createHrefFromUrl","response","staticStageResponse","isResponsePartial","resolveStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writePrerenderResponseIntoCache","t","r","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","rootVaryParamsIterable","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree"],"mappings":";;;;;;;;;;;;;;;;;;IAspBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA7wBAC,QAAQ;eAARA;;IAwKAC,oBAAoB;eAApBA;;;gCAzNa;qCACO;gCAQ7B;mCAC2B;2BACY;uBAYvC;kCAC4B;0BACmB;2BAEjB;uBACW;uBACJ;oCAEb;o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EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC,EAChCC,cAAqC;IAErC,MAAMmC,OAAOC,IAAAA,kCAA2B;IACxC,MAAMC,gBAAgBF,SAAS,OAAOA,KAAKE,aAAa,GAAGC,oBAAa,CAACkB,GAAG;IAE5E,MAAM1C,WAAWC,IAAAA,wBAAc,EAACxB,IAAIsB,IAAI,EAAEjB;IAE1C,6EAA6E;IAC7E,uEAAuE;IACvE,2EAA2E;IAC3E,uEAAuE;IACvE,uCAAuC;IACvC,MAAM,EAAE2J,2BAA2B,EAAE,GACnClJ,QAAQ;IACV,MAAMmJ,yBAAyBD;IAC/B,MAAME,eAAeC,IAAAA,+BAAoB,EACvC5I,UACAnB,0BACA0C,eACAsH,uBAAgB,CAACzE,OAAO,EACxB,MACAsE;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBI,OAAO;IACtC;IAEA,uEAAuE;IACvE,2EAA2E;IAC3E,2EAA2E;IAC3E,2EAA2E;IAC3E,+BAA+B;IAC/B,MAAMlE,SAAS,MAAMlF,aACnBlB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC,gBACAyJ,aAAahJ,eAAe;IAG9B,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAACiF,OAAOsC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAE2B,uBAAuB,EAAE,GAC/BxJ,QAAQ;QACVwJ,wBAAwBlK,0BAA0B+F,OAAOnB,IAAI;IAC/D;IAEA,OAAOmB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport type { CacheMap } from './cache-map'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n // Not derived from a server response; no base to diverge from.\n treeDivergedFromBase: false,\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n map\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n scrollRef: state.scrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","segmentCacheMap","map","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","getLinkForCurrentNavigation","fetchStrategy","FetchStrategy","Full","routeTree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","metadataVaryPath","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","computeDynamicStaleAt","UnknownDynamicStaleTime","treeDivergedFromBase","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","discoverKnownRoute","search","createHrefFromUrl","response","staticStageResponse","isResponsePartial","resolveStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writePrerenderResponseIntoCache","t","r","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","rootVaryParamsIterable","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree"],"mappings":";;;;;;;;;;;;;;;;;;IAwpBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA/wBAC,QAAQ;eAARA;;IAwKAC,oBAAoB;eAApBA;;;gCAzNa;qCACO;gCAQ7B;mCAC2B;2BACY;uBAYvC;kCAC4B;0BACmB;2BAEjB;uBACW;uBACJ;oCAEb;oCACI;+BACG;yBACyB;iCAChB;sCAIxC;AAUA,SAASD,SACdE,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC;IAEhC,IAAIC,iBAAwC;IAE5C,oEAAoE;IACpE,0EAA0E;IAC1E,wEAAwE;IACxE,sEAAsE;IACtE,6DAA6D;IAC7D,aAAa;IACb,IAAIC,QAAQC,GAAG,CAACC,yBAAyB,EAAE;QACzC,MAAM,EAAEC,kBAAkB,EAAE,GAC1BC,QAAQ;QACV,IAAID,sBAAsB;YACxB,2EAA2E;YAC3E,yEAAyE;YACzE,0EAA0E;YAC1E,0BAA0B;YAC1BJ,iBAAiBM,IAAAA,qCAAqB;YACtC,OAAOC,2BACLjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;QAEJ;IACF;IAEA,OAAOQ,aACLlB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC,gBACA,qDAAqD;IACrDS,sBAAe;AAEnB;AAEA,SAASD,aACPlB,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC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+C;IAC/C,IAAI,CAACkF,OAAOsC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAE2B,uBAAuB,EAAE,GAC/BzJ,QAAQ;QACVyJ,wBAAwBnK,0BAA0BgG,OAAOpB,IAAI;IAC/D;IAEA,OAAOoB;AACT","ignoreList":[0]}

@@ -101,3 +101,4 @@ /**

dynamicChildParamType: null,
pattern: null
pattern: null,
hasConflictingDynamicChildren: false
};

@@ -138,5 +139,7 @@ }

/**
* Gets or creates the dynamic child node for a KnownRoutePart.
* A node can have at most one dynamic child (you can't have both [slug] and
* [id] at the same route level), so we either return existing or create new.
* Gets or creates the dynamic child node for a KnownRoutePart. A node can
* have at most one dynamic child. Sibling filesystem routes can't declare two
* different params at the same level, but parallel route branches can (e.g.
* @modal/[...catchAll] alongside [username]) — the caller detects that case
* and marks the level as conflicted instead of calling this.
*/ function discoverDynamicChild(part, paramName, paramType) {

@@ -200,2 +203,3 @@ if (part.dynamicChild !== null) {

const paramName = segment[0];
const paramCacheKey = segment[1];
const paramType = segment[2];

@@ -215,2 +219,51 @@ const staticSiblings = segment[3];

}
// The param's cache key holds the value parsed from the *rendered*
// pathname. If the URL part(s) this segment would consume don't equal
// that value, the response was rewrite-affected in a way that shifts
// which URL part maps to which segment (e.g. a proxy injected a leading
// locale segment). A static segment catches this above by failing to
// match its URL part; a dynamic segment consumes whatever part is in
// front of it, so compare against the rendered value instead. Bail out.
switch(paramType){
case 'd':
{
// Canonicalize the URL part to the same encoded form the server used
// for the cache key.
if (urlPart !== null && (0, _routeparams.canonicalizeURLPart)(urlPart) !== paramCacheKey) {
return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);
}
break;
}
case 'c':
case 'oc':
{
// Catch-alls consume every remaining URL part; their cache keys are
// the rendered parts joined with '/' (empty string for an empty
// optional catch-all). Comparing the joined remainder also catches a
// rewrite that appended segments the URL doesn't have.
const joinedRemainingParts = pathnameParts.slice(partIndex).map(_routeparams.canonicalizeURLPart).join('/');
if (joinedRemainingParts !== paramCacheKey) {
return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);
}
break;
}
case 'ci(..)(..)':
case 'ci(.)':
case 'ci(..)':
case 'ci(...)':
case 'di(..)(..)':
case 'di(.)':
case 'di(..)':
case 'di(...)':
break;
default:
paramType;
}
if (parentKnownRoutePart.hasConflictingDynamicChildren || parentKnownRoutePart.dynamicChild !== null && (parentKnownRoutePart.dynamicChildParamName !== paramName || parentKnownRoutePart.dynamicChildParamType !== paramType)) {
// A different parallel route branch already claimed the dynamic child
// at this level with a different param. Mark the level as conflicted
// so matching bails out, and don't store a pattern via this branch.
parentKnownRoutePart.hasConflictingDynamicChildren = true;
return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);
}
// URL matches route structure. Build the known route tree.

@@ -424,4 +477,6 @@ knownRoutePart = discoverDynamicChild(parentKnownRoutePart, paramName, paramType);

}
// Try dynamic child
if (part.dynamicChild !== null) {
// Try dynamic child. Skip it entirely if parallel route branches disagree
// about the dynamic segment at this level — any pattern stored beneath it
// was learned under a conflicting model.
if (part.dynamicChild !== null && !part.hasConflictingDynamicChildren) {
const dynamicPart = part.dynamicChild;

@@ -428,0 +483,0 @@ const paramName = part.dynamicChildParamName;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/segment-cache/optimistic-routes.ts"],"sourcesContent":["/**\n * Optimistic Routing (Known Routes)\n *\n * This module enables the client to predict route structure for URLs that\n * haven't been prefetched yet, based on previously learned route patterns.\n * When successful, this allows skipping the route tree prefetch request\n * entirely.\n *\n * The core idea is that many URLs map to the same route structure. For example,\n * /blog/post-1 and /blog/post-2 both resolve to /blog/[slug]. Once we've\n * prefetched one, we can predict the structure of the other.\n *\n * However, we can't always make this prediction. Static siblings (like\n * /blog/featured alongside /blog/[slug]) have different route structures.\n * When we learn a dynamic route, we also learn its static siblings so we\n * know when NOT to apply the prediction.\n *\n * Main entry points:\n *\n * 1. discoverKnownRoute: Called after receiving a route tree from the server.\n * Traverses the route tree, compares URL parts to segments, and populates\n * the known route tree if they match. Routes are always inserted into the\n * cache.\n *\n * 2. matchKnownRoute: Called when looking up a route with no cache entry.\n * Matches the candidate URL against learned patterns. Returns a synthetic\n * cache entry if successful, or null to fall back to server resolution.\n *\n * Rewrite detection happens during traversal: if a URL path part doesn't match\n * the corresponding route segment, we stop populating the known route tree\n * (since the mapping is incorrect) but still insert the route into the cache.\n *\n * The known route tree is append-only with no eviction. Route patterns are\n * derived from the filesystem, so they don't become stale within a session.\n * Cache invalidation on deploy clears everything anyway.\n *\n * Current limitations (deopt to server resolution):\n * - Rewrites: Detected during traversal (tree not populated, but route cached)\n * - Intercepted routes: The route tree varies by referrer (Next-Url header),\n * so we can't predict the correct structure from the URL alone. Patterns are\n * still stored during discovery (so the trie stays populated for non-\n * intercepted siblings), but matching bails out when the pattern is marked\n * as interceptable.\n */\n\nimport type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport type {\n RouteTree,\n RSCSegmentData,\n FulfilledRouteCacheEntry,\n} from './cache'\nimport {\n EntryStatus,\n writeRouteIntoCache,\n fulfillRouteCacheEntry,\n getCurrentRouteCacheVersion,\n type PendingRouteCacheEntry,\n createMetadataRouteTree,\n} from './cache'\nimport { isValueExpired } from './cache-map'\nimport { doesStaticSegmentAppearInURL } from '../../route-params'\nimport type { NormalizedPathname, NormalizedSearch } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n finalizeMetadataVaryPath,\n getShellSegmentVaryPath,\n type PartialSegmentVaryPath,\n type PageVaryPath,\n} from './vary-path'\n\n/**\n * The known route tree is analogous to a route table. A different routing\n * implementation might use regexes or URLPattern; ours uses a trie indexed\n * by URL path segments.\n *\n * Each node (KnownRoutePart) represents a position in the URL and can have:\n * - staticChildren: Map of literal segments to child nodes\n * - dynamicChild: A single dynamic segment node ([slug], [...params], etc.)\n * - pattern: A cache entry template for routes that terminate here\n *\n * This tree only contains segments that correspond to actual filesystem routes.\n * Route groups like (marketing) and parallel routes like @modal are not\n * included since they don't appear in URLs. Similarly, if a URL is rewritten\n * to a different filesystem path, the original URL segments don't appear here\n * — only the resolved filesystem route structure is stored.\n *\n * Example tree after learning /blog/[slug], /blog/featured, and /about:\n *\n * ├── about\n * └── blog\n * ├── featured\n * └── [slug]\n *\n * When matching /blog/hello:\n * 1. \"blog\" matches static child\n * 2. \"hello\" doesn't match \"featured\", falls through to [slug]\n * 3. Returns [slug]'s pattern with resolved param { slug: \"hello\" }\n */\ntype KnownRoutePartBase = {\n // Known static paths at this level. The null vs Map distinction is\n // semantically meaningful:\n // - null: Static siblings are UNKNOWN at this level (e.g., webpack dev mode\n // where routes are compiled on-demand). If there's a dynamicChild, we\n // can't safely match it because the URL might be an unknown static sibling.\n // - Map (even if empty): Static siblings are KNOWN. We can safely match a\n // dynamicChild if the URL doesn't match any entry in the Map.\n staticChildren: Map<string, KnownRoutePart> | null\n\n // The cache entry that serves as a pattern for this route.\n // When a URL matches, we clone this and substitute param values.\n // null means we know this path exists (from static siblings) but haven't\n // learned its structure yet.\n pattern: FulfilledRouteCacheEntry | null\n\n // TODO: For prefix rewrite support. When true, this part may not appear in\n // the candidate URL because it was injected by a rewrite.\n // mayBeSkippedInURL: boolean\n}\n\n// The dynamic child fields are structured as a union so that narrowing on\n// dynamicChild also narrows dynamicChildParamName and dynamicChildParamType.\ntype KnownRoutePartWithoutDynamicChild = KnownRoutePartBase & {\n dynamicChild: null\n dynamicChildParamName: null\n dynamicChildParamType: null\n}\n\ntype KnownRoutePartWithDynamicChild = KnownRoutePartBase & {\n dynamicChild: KnownRoutePart\n dynamicChildParamName: string\n dynamicChildParamType: DynamicParamTypesShort\n}\n\ntype KnownRoutePart =\n | KnownRoutePartWithoutDynamicChild\n | KnownRoutePartWithDynamicChild\n\n/**\n * Param values extracted during URL matching. Used to reify the template.\n * Values are always strings: catch-all [...param] and optional catch-all\n * [[...param]] values are joined with '/' at the time they're resolved, which\n * matches how the rest of the system models catch-all cache keys (an empty\n * optional catch-all is the empty string). Keeping a single value type keeps\n * reads of this map monomorphic.\n */\ntype ResolvedParams = Map<string, string>\n\n/**\n * Read the pattern from a KnownRoutePart, evicting it if expired.\n *\n * This prevents stale patterns (e.g. from InliningHintsStale route entries\n * with staleAt = -1) from being cloned into synthetic entries indefinitely.\n * Once evicted, the pattern slot can be repopulated by the next\n * discoverKnownRoute call with a fresh entry from a /_tree response.\n */\nfunction readPattern(\n now: number,\n part: KnownRoutePart\n): FulfilledRouteCacheEntry | null {\n const pattern = part.pattern\n if (pattern === null) {\n return null\n }\n if (isValueExpired(now, getCurrentRouteCacheVersion(), pattern)) {\n // The pattern is expired. Null it out so the slot can be repopulated.\n part.pattern = null\n return null\n }\n return pattern\n}\n\nfunction createEmptyPart(): KnownRoutePart {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n }\n}\n\n// The root of the known route tree.\nlet knownRouteTreeRoot: KnownRoutePart = createEmptyPart()\n\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the route entry is marked as having a\n * dynamic rewrite, which prevents it from being used as a template for future\n * predictions. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */\nexport function discoverKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n pendingEntry: PendingRouteCacheEntry | null,\n routeTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const tree = routeTree\n\n const pathnameParts = splitPathnameIntoParts(pathname)\n\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n if (hasDynamicRewrite) {\n fulfilledEntry.hasDynamicRewrite = true\n }\n // Populate the known route tree (handles rewrite detection internally).\n // The entry is already in the cache; this just stores it as a pattern\n // if the URL matches the route structure.\n discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n fulfilledEntry,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n return fulfilledEntry\n }\n\n // No pending entry - discoverKnownRoutePart will create one and insert it\n // into the cache, or return an existing pattern if one exists.\n return discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n null,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n}\n\n/**\n * Bail out of populating the known route tree when discovery detects that the\n * URL doesn't match the route structure (a rewrite). The route entry is still\n * inserted into the cache for direct lookup — we just don't store it as a\n * pattern, since the URL and the tree describe different shapes.\n */\nfunction handleMismatchDueToRewrite(\n existingEntry: FulfilledRouteCacheEntry | null,\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n}\n\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart.\n * A node can have at most one dynamic child (you can't have both [slug] and\n * [id] at the same route level), so we either return existing or create new.\n */\nfunction discoverDynamicChild(\n part: KnownRoutePart,\n paramName: string,\n paramType: DynamicParamTypesShort\n): KnownRoutePart {\n if (part.dynamicChild !== null) {\n return part.dynamicChild\n }\n const newChild = createEmptyPart()\n // Type assertion needed because we're converting from \"without\" to \"with\"\n // dynamic child variant.\n const mutablePart = part as unknown as KnownRoutePartWithDynamicChild\n mutablePart.dynamicChild = newChild\n mutablePart.dynamicChildParamName = paramName\n mutablePart.dynamicChildParamType = paramType\n return newChild\n}\n\n/**\n * Recursive workhorse for discoverKnownRoute.\n *\n * Walks the route tree and URL parts in parallel, building out the known\n * route tree as it goes. At each step:\n * 1. Determines if the current segment appears in the URL (dynamic/static)\n * 2. Validates URL matches route structure (detects rewrites)\n * 3. Creates/updates the corresponding KnownRoutePart node\n * 4. Records static siblings for future matching\n * 5. Recurses into child slots (parallel routes)\n *\n * If a URL/route mismatch is detected (rewrite), we stop building the known\n * route tree but still cache the route entry for direct lookup.\n */\nfunction discoverKnownRoutePart(\n parentKnownRoutePart: KnownRoutePart,\n routeTree: RouteTree<RSCSegmentData | null>,\n pathnameParts: readonly string[],\n partIndex: number,\n existingEntry: FulfilledRouteCacheEntry | null,\n // These are passed through unchanged for entry creation at the leaf\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const segment = routeTree.segment\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n let knownRoutePart: KnownRoutePart = parentKnownRoutePart\n let nextPartIndex = partIndex\n\n if (typeof segment === 'string') {\n if (doesStaticSegmentAppearInURL(segment)) {\n // A visible static segment must consume exactly one URL part that\n // equals the segment. If the URL is exhausted or the URL part doesn't\n // match, the URL doesn't fit the route shape — the response was\n // rewrite-affected. Bail out.\n if (urlPart === null || urlPart !== segment) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart)\n if (existingChild === undefined) {\n existingChild = createEmptyPart()\n parentKnownRoutePart.staticChildren.set(urlPart, existingChild)\n }\n knownRoutePart = existingChild\n\n // Advance to next URL part.\n nextPartIndex = partIndex + 1\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n const paramName: string = segment[0]\n const paramType: DynamicParamTypesShort = segment[2]\n const staticSiblings: readonly string[] | null = segment[3]\n\n if (paramType !== 'oc' && urlPart === null) {\n // Every dynamic segment except the optional catch-all (`[[...param]]`)\n // must consume at least one URL part at runtime. If discovery reached\n // this segment with no URL parts left to consume, the URL doesn't fit\n // the route shape — the response was rewrite-affected. Bail out.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (\n staticSiblings !== null &&\n urlPart !== null &&\n staticSiblings.includes(urlPart)\n ) {\n // The route tree says this is a dynamic sibling, but the canonical URL\n // is a known static sibling. This is a mismatch.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // URL matches route structure. Build the known route tree.\n knownRoutePart = discoverDynamicChild(\n parentKnownRoutePart,\n paramName,\n paramType\n )\n\n // Record static siblings as placeholder parts.\n // IMPORTANT: We use the null vs Map distinction to track whether\n // siblings are known at this level:\n // - staticChildren: null = siblings unknown (can't safely match dynamic)\n // - staticChildren: Map = siblings known (even if empty)\n // This matters in dev mode where webpack may not know all siblings yet.\n if (staticSiblings !== null) {\n // Siblings are known - ensure we have a Map (even if empty)\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n for (const sibling of staticSiblings) {\n if (!parentKnownRoutePart.staticChildren.has(sibling)) {\n parentKnownRoutePart.staticChildren.set(sibling, createEmptyPart())\n }\n }\n }\n\n // Advance to next URL part. Catch-all segments (`[...param]` and\n // `[[...param]]`) absorb every remaining URL part at runtime (see\n // `matchKnownRoutePart`, which slices the rest of `pathnameParts`).\n if (paramType === 'c' || paramType === 'oc') {\n nextPartIndex = pathnameParts.length\n } else {\n nextPartIndex = partIndex + 1\n }\n }\n\n // Recurse into child routes. A route tree can have multiple parallel routes\n // (e.g., @modal alongside children). Each parallel route is a separate\n // branch, but they all share the same URL - we just need to traverse all\n // branches to build out the known route tree.\n const slots = routeTree.slots\n let resultFromChildren: FulfilledRouteCacheEntry | null = null\n if (slots !== null) {\n for (const childRouteTree of slots.values()) {\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue\n }\n const result = discoverKnownRoutePart(\n knownRoutePart,\n childRouteTree,\n pathnameParts,\n nextPartIndex,\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result\n }\n if (resultFromChildren !== null) {\n return resultFromChildren\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node (`__PAGE__` leaf). If there are still URL parts\n // left to consume, the route tree is shorter than the URL, which means\n // the URL doesn't match the route structure (likely a rewrite).\n if (nextPartIndex < pathnameParts.length) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node. Create/get the route cache entry and store as a\n // pattern. First, check if there's already a pattern for this route.\n const existingPattern = readPattern(now, knownRoutePart)\n if (existingPattern !== null) {\n // If this route has a dynamic rewrite, mark the existing pattern.\n if (hasDynamicRewrite) {\n existingPattern.hasDynamicRewrite = true\n }\n return existingPattern\n }\n\n // Get or create the entry\n let entry: FulfilledRouteCacheEntry\n if (existingEntry !== null) {\n // Already have a fulfilled entry, use it directly. It's already in the\n // route cache map.\n entry = existingEntry\n } else {\n // Create the entry and insert it into the route cache map.\n entry = writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (hasDynamicRewrite) {\n entry.hasDynamicRewrite = true\n }\n\n // Store as pattern\n knownRoutePart.pattern = entry\n return entry\n}\n\n/**\n * Attempts to match a URL against learned route patterns.\n *\n * Returns a synthetic FulfilledRouteCacheEntry if the URL matches a known\n * pattern, or null if no match is found (fall back to server resolution).\n */\nexport function matchKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch\n): FulfilledRouteCacheEntry | null {\n const pathnameParts = splitPathnameIntoParts(pathname)\n const resolvedParams: ResolvedParams = new Map()\n const match = matchKnownRoutePart(\n now,\n knownRouteTreeRoot,\n pathnameParts,\n 0,\n resolvedParams\n )\n\n if (match === null) {\n return null\n }\n\n const matchedPart = match.part\n const pattern = match.pattern\n\n // If the pattern could be intercepted, we can't safely use it for prediction.\n // Interception routes resolve to different route trees depending on the\n // referrer (the Next-Url header), which means the same URL can map to\n // different page components depending on where the navigation originated.\n // Since the known route tree only stores a single pattern per URL shape, we\n // can't distinguish between the intercepted and non-intercepted cases, so we\n // bail out to server resolution.\n //\n // TODO: We could store interception behavior in the known route tree itself\n // (e.g., which segments use interception markers and what they resolve to).\n // With enough information embedded in the trie, we could match interception\n // routes entirely on the client without a server round-trip.\n if (pattern.couldBeIntercepted) {\n return null\n }\n\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const acc: ReifyAccumulator = { metadataVaryPath: null }\n const reifiedTree = reifyRouteTree(\n pattern.tree,\n resolvedParams,\n search,\n null, // Start with null partial vary path at the root\n acc\n )\n\n // The metadata tree is a flat page node without the intermediate layout\n // structure. Clone it with the updated metadata vary path collected during\n // the main tree traversal.\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n // This shouldn't be reachable for a valid route tree.\n return null\n }\n const reifiedMetadata = createMetadataRouteTree(metadataVaryPath)\n\n // Create a synthetic (predicted) entry and store it as the new pattern.\n //\n // Why replace the pattern? We intentionally update the pattern with this\n // synthetic entry so that if our prediction was wrong (server returns a\n // different pathname due to dynamic rewrite), the entry gets marked with\n // hasDynamicRewrite. Future predictions for this route will see the flag\n // and bail out to server resolution instead of making the same mistake.\n const syntheticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n tree: reifiedTree,\n metadata: reifiedMetadata,\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n hasDynamicRewrite: false,\n renderedSearch: search,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version,\n }\n\n matchedPart.pattern = syntheticEntry\n\n return syntheticEntry\n}\n\n/**\n * Result of a successful match: the matched tree node and its pattern.\n * We return both because the caller needs to update the pattern after\n * creating a synthetic entry (for dynamic rewrite detection).\n */\ntype KnownRouteMatch = {\n part: KnownRoutePart\n pattern: FulfilledRouteCacheEntry\n} | null\n\n/**\n * Recursively matches a URL against the known route tree.\n *\n * Matching priority (most specific first):\n * 1. Static children - exact path segment match\n * 2. Dynamic child - [param], [...param], [[...param]]\n * 3. Direct pattern - when no more URL parts remain\n *\n * Collects resolved param values in resolvedParams as it traverses.\n * Returns null if no match found (caller should fall back to server).\n */\nfunction matchKnownRoutePart(\n now: number,\n part: KnownRoutePart,\n pathnameParts: string[],\n partIndex: number,\n resolvedParams: ResolvedParams\n): KnownRouteMatch {\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n return null\n }\n\n // Static children take priority over dynamic. This ensures /blog/featured\n // matches its own route rather than /blog/[slug].\n if (urlPart !== null) {\n const staticChild = part.staticChildren.get(urlPart)\n if (staticChild !== undefined) {\n // Check if this is an \"unknown\" placeholder part. These are created when\n // we learn about static siblings (from the route tree's staticSiblings\n // field) but haven't prefetched them yet. We know the path exists but\n // don't know its structure, so we can't predict it.\n if (\n staticChild.pattern === null &&\n staticChild.dynamicChild === null &&\n staticChild.staticChildren === null\n ) {\n // Bail out - server must resolve this route.\n return null\n }\n const match = matchKnownRoutePart(\n now,\n staticChild,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n if (match !== null) {\n return match\n }\n // Static child is a real node (not a placeholder) but its subtree\n // didn't match the remaining URL parts. This means the route exists\n // in the static subtree but hasn't been fully discovered yet. Do not\n // fall through to try the dynamic child — the static match is\n // authoritative. Bail out to server resolution.\n return null\n }\n }\n\n // Try dynamic child\n if (part.dynamicChild !== null) {\n const dynamicPart = part.dynamicChild\n const paramName = part.dynamicChildParamName\n const paramType = part.dynamicChildParamType\n const dynamicPattern = readPattern(now, dynamicPart)\n\n switch (paramType) {\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (\n dynamicPattern !== null &&\n !dynamicPattern.hasDynamicRewrite &&\n urlPart !== null\n ) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n break\n case 'oc': {\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) {\n if (urlPart !== null) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n const directPattern = readPattern(now, part)\n if (directPattern === null || directPattern.hasDynamicRewrite) {\n resolvedParams.set(paramName, '')\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n }\n break\n }\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, urlPart)\n return matchKnownRoutePart(\n now,\n dynamicPart,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n }\n break\n // Intercepted routes use relative path markers like (.), (..), (...)\n // Their behavior depends on navigation context (soft vs hard nav),\n // so we can't predict them client-side. Defer to server.\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n return null\n default:\n paramType satisfies never\n }\n }\n\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n\n return null\n}\n\n/**\n * Accumulator for collecting data during reifyRouteTree traversal.\n * metadataVaryPath is collected from the first page node encountered\n * (parallel routes may have multiple pages, but metadata uses the first).\n */\ntype ReifyAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\n/**\n * \"Reify\" means to make concrete - we take an abstract pattern (the template\n * route tree) and produce a concrete instance with actual param values.\n *\n * This function clones a RouteTree, substituting dynamic segment values from\n * resolvedParams and computing new vary paths. The vary path encodes param\n * values so segment cache entries can be correctly keyed.\n *\n * Example: Pattern for /blog/[slug] with resolvedParams { slug: \"hello\" }\n * produces a tree where segment [slug] has cacheKey \"hello\".\n */\nfunction reifyRouteTree(\n pattern: RouteTree<null>,\n resolvedParams: ResolvedParams,\n search: NormalizedSearch,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n acc: ReifyAccumulator\n): RouteTree<null> {\n const originalSegment = pattern.segment\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam =\n (pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n let newSegment = originalSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const newValue = resolvedParams.get(paramName)\n if (newValue !== undefined) {\n // Catch-all values are already joined into a single string when they're\n // resolved in matchKnownRoutePart, so the value can be used directly.\n const newCacheKey = newValue\n newSegment = [paramName, newCacheKey, paramType, staticSiblings]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n newCacheKey,\n paramName,\n isRootParam\n )\n } else {\n // Param not found in resolvedParams - keep original and inherit partial\n // TODO: This should never happen. Bail out with null.\n partialVaryPath = parentPartialVaryPath\n }\n } else {\n // Static segment: inherit partial vary path from parent\n partialVaryPath = parentPartialVaryPath\n }\n\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots: Map<string, RouteTree<null>> | null = null\n const patternSlots = pattern.slots\n if (patternSlots !== null) {\n newSlots = new Map()\n for (const [key, childPattern] of patternSlots) {\n newSlots.set(\n key,\n reifyRouteTree(\n childPattern,\n resolvedParams,\n search,\n partialVaryPath,\n acc\n )\n )\n }\n }\n\n if (pattern.isPage) {\n // Page segment: finalize with search params\n const newVaryPath = finalizePageVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n // Collect metadata vary path (first page wins, same as original algorithm)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n // Route cache patterns never carry seed data (see\n // stripDataFromRouteTree), so neither do trees reified from them.\n data: null,\n varyPath: newVaryPath,\n isPage: true,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n } else {\n // Layout segment: finalize without search params\n const newVaryPath = finalizeLayoutVaryPath(\n pattern.requestKey,\n partialVaryPath\n )\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n data: null,\n varyPath: newVaryPath,\n isPage: false,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n }\n}\n\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */\nexport function resetKnownRoutes(): void {\n knownRouteTreeRoot = createEmptyPart()\n}\n"],"names":["discoverKnownRoute","matchKnownRoute","resetKnownRoutes","readPattern","now","part","pattern","isValueExpired","getCurrentRouteCacheVersion","createEmptyPart","staticChildren","dynamicChild","dynamicChildParamName","dynamicChildParamType","knownRouteTreeRoot","pathname","search","nextUrl","pendingEntry","routeTree","metadataVaryPath","couldBeIntercepted","canonicalUrl","supportsPerSegmentPrefetching","hasDynamicRewrite","tree","pathnameParts","splitPathnameIntoParts","fulfilledEntry","fulfillRouteCacheEntry","discoverKnownRoutePart","handleMismatchDueToRewrite","existingEntry","fullTree","writeRouteIntoCache","discoverDynamicChild","paramName","paramType","newChild","mutablePart","parentKnownRoutePart","partIndex","segment","urlPart","length","knownRoutePart","nextPartIndex","doesStaticSegmentAppearInURL","Map","existingChild","get","undefined","set","staticSiblings","includes","sibling","has","slots","resultFromChildren","childRouteTree","values","refreshState","result","existingPattern","entry","resolvedParams","match","matchKnownRoutePart","matchedPart","acc","reifiedTree","reifyRouteTree","reifiedMetadata","createMetadataRouteTree","syntheticEntry","status","EntryStatus","Fulfilled","blockedTasks","metadata","renderedSearch","ref","size","staleAt","version","staticChild","dynamicPart","dynamicPattern","slice","join","directPattern","parentPartialVaryPath","originalSegment","isRootParam","prefetchHints","PrefetchHint","IsRootLayoutOrAbove","newSegment","partialVaryPath","newValue","newCacheKey","appendLayoutVaryPath","newSlots","patternSlots","key","childPattern","isPage","newVaryPath","finalizePageVaryPath","requestKey","finalizeMetadataVaryPath","shellVaryPath","getShellSegmentVaryPath","data","varyPath","finalizeLay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oD,MAAM;YACNC,UAAUP;YACVD,QAAQ;YACRjD,OAAO6C;YACPR,eAAexF,QAAQwF,aAAa;QACtC;IACF,OAAO;QACL,iDAAiD;QACjD,MAAMa,cAAcQ,IAAAA,gCAAsB,EACxC7G,QAAQuG,UAAU,EAClBX;QAEF,OAAO;YACLW,YAAYvG,QAAQuG,UAAU;YAC9BnE,SAASuD;YACTc,eAAeC,IAAAA,iCAAuB,EAACL;YACvC9C,cAAcvD,QAAQuD,YAAY;YAClCoD,MAAM;YACNC,UAAUP;YACVD,QAAQ;YACRjD,OAAO6C;YACPR,eAAexF,QAAQwF,aAAa;QACtC;IACF;AACF;AAMO,SAAS5F;IACdY,qBAAqBL;AACvB","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/segment-cache/optimistic-routes.ts"],"sourcesContent":["/**\n * Optimistic Routing (Known Routes)\n *\n * This module enables the client to predict route structure for URLs that\n * haven't been prefetched yet, based on previously learned route patterns.\n * When successful, this allows skipping the route tree prefetch request\n * entirely.\n *\n * The core idea is that many URLs map to the same route structure. For example,\n * /blog/post-1 and /blog/post-2 both resolve to /blog/[slug]. Once we've\n * prefetched one, we can predict the structure of the other.\n *\n * However, we can't always make this prediction. Static siblings (like\n * /blog/featured alongside /blog/[slug]) have different route structures.\n * When we learn a dynamic route, we also learn its static siblings so we\n * know when NOT to apply the prediction.\n *\n * Main entry points:\n *\n * 1. discoverKnownRoute: Called after receiving a route tree from the server.\n * Traverses the route tree, compares URL parts to segments, and populates\n * the known route tree if they match. Routes are always inserted into the\n * cache.\n *\n * 2. matchKnownRoute: Called when looking up a route with no cache entry.\n * Matches the candidate URL against learned patterns. Returns a synthetic\n * cache entry if successful, or null to fall back to server resolution.\n *\n * Rewrite detection happens during traversal: if a URL path part doesn't match\n * the corresponding route segment, we stop populating the known route tree\n * (since the mapping is incorrect) but still insert the route into the cache.\n *\n * The known route tree is append-only with no eviction. Route patterns are\n * derived from the filesystem, so they don't become stale within a session.\n * Cache invalidation on deploy clears everything anyway.\n *\n * Current limitations (deopt to server resolution):\n * - Rewrites: Detected during traversal (tree not populated, but route cached)\n * - Intercepted routes: The route tree varies by referrer (Next-Url header),\n * so we can't predict the correct structure from the URL alone. Patterns are\n * still stored during discovery (so the trie stays populated for non-\n * intercepted siblings), but matching bails out when the pattern is marked\n * as interceptable.\n */\n\nimport type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport type {\n RouteTree,\n RSCSegmentData,\n FulfilledRouteCacheEntry,\n} from './cache'\nimport {\n EntryStatus,\n writeRouteIntoCache,\n fulfillRouteCacheEntry,\n getCurrentRouteCacheVersion,\n type PendingRouteCacheEntry,\n createMetadataRouteTree,\n} from './cache'\nimport { isValueExpired } from './cache-map'\nimport {\n canonicalizeURLPart,\n doesStaticSegmentAppearInURL,\n} from '../../route-params'\nimport type { NormalizedPathname, NormalizedSearch } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n finalizeMetadataVaryPath,\n getShellSegmentVaryPath,\n type PartialSegmentVaryPath,\n type PageVaryPath,\n} from './vary-path'\n\n/**\n * The known route tree is analogous to a route table. A different routing\n * implementation might use regexes or URLPattern; ours uses a trie indexed\n * by URL path segments.\n *\n * Each node (KnownRoutePart) represents a position in the URL and can have:\n * - staticChildren: Map of literal segments to child nodes\n * - dynamicChild: A single dynamic segment node ([slug], [...params], etc.)\n * - pattern: A cache entry template for routes that terminate here\n *\n * This tree only contains segments that correspond to actual filesystem routes.\n * Route groups like (marketing) and parallel routes like @modal are not\n * included since they don't appear in URLs. Similarly, if a URL is rewritten\n * to a different filesystem path, the original URL segments don't appear here\n * — only the resolved filesystem route structure is stored.\n *\n * Example tree after learning /blog/[slug], /blog/featured, and /about:\n *\n * ├── about\n * └── blog\n * ├── featured\n * └── [slug]\n *\n * When matching /blog/hello:\n * 1. \"blog\" matches static child\n * 2. \"hello\" doesn't match \"featured\", falls through to [slug]\n * 3. Returns [slug]'s pattern with resolved param { slug: \"hello\" }\n */\ntype KnownRoutePartBase = {\n // Known static paths at this level. The null vs Map distinction is\n // semantically meaningful:\n // - null: Static siblings are UNKNOWN at this level (e.g., webpack dev mode\n // where routes are compiled on-demand). If there's a dynamicChild, we\n // can't safely match it because the URL might be an unknown static sibling.\n // - Map (even if empty): Static siblings are KNOWN. We can safely match a\n // dynamicChild if the URL doesn't match any entry in the Map.\n staticChildren: Map<string, KnownRoutePart> | null\n\n // The cache entry that serves as a pattern for this route.\n // When a URL matches, we clone this and substitute param values.\n // null means we know this path exists (from static siblings) but haven't\n // learned its structure yet.\n pattern: FulfilledRouteCacheEntry | null\n\n // True when parallel route branches disagree about the dynamic segment at\n // this level — different param name or type, e.g. an @modal/[...catchAll]\n // slot alongside [username]. The trie can only model one dynamic child per\n // level, so prediction below this level would bind one branch's URL parts\n // to another branch's params. Once set, discovery stops storing patterns\n // beneath this level and matching bails out to server resolution.\n //\n // TODO: Consider including conflicting sibling dynamic params in the route\n // tree, like we do for static siblings, and attempting to match both.\n hasConflictingDynamicChildren: boolean\n\n // TODO: For prefix rewrite support. When true, this part may not appear in\n // the candidate URL because it was injected by a rewrite. Today, discovery\n // refuses to store a pattern for such routes (see the cache key comparison\n // in discoverKnownRoutePart); this field would let them be predicted.\n // mayBeSkippedInURL: boolean\n}\n\n// The dynamic child fields are structured as a union so that narrowing on\n// dynamicChild also narrows dynamicChildParamName and dynamicChildParamType.\ntype KnownRoutePartWithoutDynamicChild = KnownRoutePartBase & {\n dynamicChild: null\n dynamicChildParamName: null\n dynamicChildParamType: null\n}\n\ntype KnownRoutePartWithDynamicChild = KnownRoutePartBase & {\n dynamicChild: KnownRoutePart\n dynamicChildParamName: string\n dynamicChildParamType: DynamicParamTypesShort\n}\n\ntype KnownRoutePart =\n | KnownRoutePartWithoutDynamicChild\n | KnownRoutePartWithDynamicChild\n\n/**\n * Param values extracted during URL matching. Used to reify the template.\n * Values are always strings: catch-all [...param] and optional catch-all\n * [[...param]] values are joined with '/' at the time they're resolved, which\n * matches how the rest of the system models catch-all cache keys (an empty\n * optional catch-all is the empty string). Keeping a single value type keeps\n * reads of this map monomorphic.\n */\ntype ResolvedParams = Map<string, string>\n\n/**\n * Read the pattern from a KnownRoutePart, evicting it if expired.\n *\n * This prevents stale patterns (e.g. from InliningHintsStale route entries\n * with staleAt = -1) from being cloned into synthetic entries indefinitely.\n * Once evicted, the pattern slot can be repopulated by the next\n * discoverKnownRoute call with a fresh entry from a /_tree response.\n */\nfunction readPattern(\n now: number,\n part: KnownRoutePart\n): FulfilledRouteCacheEntry | null {\n const pattern = part.pattern\n if (pattern === null) {\n return null\n }\n if (isValueExpired(now, getCurrentRouteCacheVersion(), pattern)) {\n // The pattern is expired. Null it out so the slot can be repopulated.\n part.pattern = null\n return null\n }\n return pattern\n}\n\nfunction createEmptyPart(): KnownRoutePart {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n hasConflictingDynamicChildren: false,\n }\n}\n\n// The root of the known route tree.\nlet knownRouteTreeRoot: KnownRoutePart = createEmptyPart()\n\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the route entry is marked as having a\n * dynamic rewrite, which prevents it from being used as a template for future\n * predictions. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */\nexport function discoverKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n pendingEntry: PendingRouteCacheEntry | null,\n routeTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const tree = routeTree\n\n const pathnameParts = splitPathnameIntoParts(pathname)\n\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n if (hasDynamicRewrite) {\n fulfilledEntry.hasDynamicRewrite = true\n }\n // Populate the known route tree (handles rewrite detection internally).\n // The entry is already in the cache; this just stores it as a pattern\n // if the URL matches the route structure.\n discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n fulfilledEntry,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n return fulfilledEntry\n }\n\n // No pending entry - discoverKnownRoutePart will create one and insert it\n // into the cache, or return an existing pattern if one exists.\n return discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n null,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n}\n\n/**\n * Bail out of populating the known route tree when discovery detects that the\n * URL doesn't match the route structure (a rewrite). The route entry is still\n * inserted into the cache for direct lookup — we just don't store it as a\n * pattern, since the URL and the tree describe different shapes.\n */\nfunction handleMismatchDueToRewrite(\n existingEntry: FulfilledRouteCacheEntry | null,\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n}\n\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart. A node can\n * have at most one dynamic child. Sibling filesystem routes can't declare two\n * different params at the same level, but parallel route branches can (e.g.\n * @modal/[...catchAll] alongside [username]) — the caller detects that case\n * and marks the level as conflicted instead of calling this.\n */\nfunction discoverDynamicChild(\n part: KnownRoutePart,\n paramName: string,\n paramType: DynamicParamTypesShort\n): KnownRoutePart {\n if (part.dynamicChild !== null) {\n return part.dynamicChild\n }\n const newChild = createEmptyPart()\n // Type assertion needed because we're converting from \"without\" to \"with\"\n // dynamic child variant.\n const mutablePart = part as unknown as KnownRoutePartWithDynamicChild\n mutablePart.dynamicChild = newChild\n mutablePart.dynamicChildParamName = paramName\n mutablePart.dynamicChildParamType = paramType\n return newChild\n}\n\n/**\n * Recursive workhorse for discoverKnownRoute.\n *\n * Walks the route tree and URL parts in parallel, building out the known\n * route tree as it goes. At each step:\n * 1. Determines if the current segment appears in the URL (dynamic/static)\n * 2. Validates URL matches route structure (detects rewrites)\n * 3. Creates/updates the corresponding KnownRoutePart node\n * 4. Records static siblings for future matching\n * 5. Recurses into child slots (parallel routes)\n *\n * If a URL/route mismatch is detected (rewrite), we stop building the known\n * route tree but still cache the route entry for direct lookup.\n */\nfunction discoverKnownRoutePart(\n parentKnownRoutePart: KnownRoutePart,\n routeTree: RouteTree<RSCSegmentData | null>,\n pathnameParts: readonly string[],\n partIndex: number,\n existingEntry: FulfilledRouteCacheEntry | null,\n // These are passed through unchanged for entry creation at the leaf\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const segment = routeTree.segment\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n let knownRoutePart: KnownRoutePart = parentKnownRoutePart\n let nextPartIndex = partIndex\n\n if (typeof segment === 'string') {\n if (doesStaticSegmentAppearInURL(segment)) {\n // A visible static segment must consume exactly one URL part that\n // equals the segment. If the URL is exhausted or the URL part doesn't\n // match, the URL doesn't fit the route shape — the response was\n // rewrite-affected. Bail out.\n if (urlPart === null || urlPart !== segment) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart)\n if (existingChild === undefined) {\n existingChild = createEmptyPart()\n parentKnownRoutePart.staticChildren.set(urlPart, existingChild)\n }\n knownRoutePart = existingChild\n\n // Advance to next URL part.\n nextPartIndex = partIndex + 1\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n const paramName: string = segment[0]\n const paramCacheKey: string = segment[1]\n const paramType: DynamicParamTypesShort = segment[2]\n const staticSiblings: readonly string[] | null = segment[3]\n\n if (paramType !== 'oc' && urlPart === null) {\n // Every dynamic segment except the optional catch-all (`[[...param]]`)\n // must consume at least one URL part at runtime. If discovery reached\n // this segment with no URL parts left to consume, the URL doesn't fit\n // the route shape — the response was rewrite-affected. Bail out.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (\n staticSiblings !== null &&\n urlPart !== null &&\n staticSiblings.includes(urlPart)\n ) {\n // The route tree says this is a dynamic sibling, but the canonical URL\n // is a known static sibling. This is a mismatch.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // The param's cache key holds the value parsed from the *rendered*\n // pathname. If the URL part(s) this segment would consume don't equal\n // that value, the response was rewrite-affected in a way that shifts\n // which URL part maps to which segment (e.g. a proxy injected a leading\n // locale segment). A static segment catches this above by failing to\n // match its URL part; a dynamic segment consumes whatever part is in\n // front of it, so compare against the rendered value instead. Bail out.\n switch (paramType) {\n case 'd': {\n // Canonicalize the URL part to the same encoded form the server used\n // for the cache key.\n if (\n urlPart !== null &&\n canonicalizeURLPart(urlPart) !== paramCacheKey\n ) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n break\n }\n case 'c':\n case 'oc': {\n // Catch-alls consume every remaining URL part; their cache keys are\n // the rendered parts joined with '/' (empty string for an empty\n // optional catch-all). Comparing the joined remainder also catches a\n // rewrite that appended segments the URL doesn't have.\n const joinedRemainingParts = pathnameParts\n .slice(partIndex)\n .map(canonicalizeURLPart)\n .join('/')\n if (joinedRemainingParts !== paramCacheKey) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n break\n }\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n // Interception params embed relative markers in their values, and\n // patterns containing them are never used for prediction anyway (see\n // matchKnownRoutePart), so skip the comparison.\n break\n default:\n paramType satisfies never\n }\n\n if (\n parentKnownRoutePart.hasConflictingDynamicChildren ||\n (parentKnownRoutePart.dynamicChild !== null &&\n (parentKnownRoutePart.dynamicChildParamName !== paramName ||\n parentKnownRoutePart.dynamicChildParamType !== paramType))\n ) {\n // A different parallel route branch already claimed the dynamic child\n // at this level with a different param. Mark the level as conflicted\n // so matching bails out, and don't store a pattern via this branch.\n parentKnownRoutePart.hasConflictingDynamicChildren = true\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // URL matches route structure. Build the known route tree.\n knownRoutePart = discoverDynamicChild(\n parentKnownRoutePart,\n paramName,\n paramType\n )\n\n // Record static siblings as placeholder parts.\n // IMPORTANT: We use the null vs Map distinction to track whether\n // siblings are known at this level:\n // - staticChildren: null = siblings unknown (can't safely match dynamic)\n // - staticChildren: Map = siblings known (even if empty)\n // This matters in dev mode where webpack may not know all siblings yet.\n if (staticSiblings !== null) {\n // Siblings are known - ensure we have a Map (even if empty)\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n for (const sibling of staticSiblings) {\n if (!parentKnownRoutePart.staticChildren.has(sibling)) {\n parentKnownRoutePart.staticChildren.set(sibling, createEmptyPart())\n }\n }\n }\n\n // Advance to next URL part. Catch-all segments (`[...param]` and\n // `[[...param]]`) absorb every remaining URL part at runtime (see\n // `matchKnownRoutePart`, which slices the rest of `pathnameParts`).\n if (paramType === 'c' || paramType === 'oc') {\n nextPartIndex = pathnameParts.length\n } else {\n nextPartIndex = partIndex + 1\n }\n }\n\n // Recurse into child routes. A route tree can have multiple parallel routes\n // (e.g., @modal alongside children). Each parallel route is a separate\n // branch, but they all share the same URL - we just need to traverse all\n // branches to build out the known route tree.\n const slots = routeTree.slots\n let resultFromChildren: FulfilledRouteCacheEntry | null = null\n if (slots !== null) {\n for (const childRouteTree of slots.values()) {\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue\n }\n const result = discoverKnownRoutePart(\n knownRoutePart,\n childRouteTree,\n pathnameParts,\n nextPartIndex,\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result\n }\n if (resultFromChildren !== null) {\n return resultFromChildren\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node (`__PAGE__` leaf). If there are still URL parts\n // left to consume, the route tree is shorter than the URL, which means\n // the URL doesn't match the route structure (likely a rewrite).\n if (nextPartIndex < pathnameParts.length) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node. Create/get the route cache entry and store as a\n // pattern. First, check if there's already a pattern for this route.\n const existingPattern = readPattern(now, knownRoutePart)\n if (existingPattern !== null) {\n // If this route has a dynamic rewrite, mark the existing pattern.\n if (hasDynamicRewrite) {\n existingPattern.hasDynamicRewrite = true\n }\n return existingPattern\n }\n\n // Get or create the entry\n let entry: FulfilledRouteCacheEntry\n if (existingEntry !== null) {\n // Already have a fulfilled entry, use it directly. It's already in the\n // route cache map.\n entry = existingEntry\n } else {\n // Create the entry and insert it into the route cache map.\n entry = writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (hasDynamicRewrite) {\n entry.hasDynamicRewrite = true\n }\n\n // Store as pattern\n knownRoutePart.pattern = entry\n return entry\n}\n\n/**\n * Attempts to match a URL against learned route patterns.\n *\n * Returns a synthetic FulfilledRouteCacheEntry if the URL matches a known\n * pattern, or null if no match is found (fall back to server resolution).\n */\nexport function matchKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch\n): FulfilledRouteCacheEntry | null {\n const pathnameParts = splitPathnameIntoParts(pathname)\n const resolvedParams: ResolvedParams = new Map()\n const match = matchKnownRoutePart(\n now,\n knownRouteTreeRoot,\n pathnameParts,\n 0,\n resolvedParams\n )\n\n if (match === null) {\n return null\n }\n\n const matchedPart = match.part\n const pattern = match.pattern\n\n // If the pattern could be intercepted, we can't safely use it for prediction.\n // Interception routes resolve to different route trees depending on the\n // referrer (the Next-Url header), which means the same URL can map to\n // different page components depending on where the navigation originated.\n // Since the known route tree only stores a single pattern per URL shape, we\n // can't distinguish between the intercepted and non-intercepted cases, so we\n // bail out to server resolution.\n //\n // TODO: We could store interception behavior in the known route tree itself\n // (e.g., which segments use interception markers and what they resolve to).\n // With enough information embedded in the trie, we could match interception\n // routes entirely on the client without a server round-trip.\n if (pattern.couldBeIntercepted) {\n return null\n }\n\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const acc: ReifyAccumulator = { metadataVaryPath: null }\n const reifiedTree = reifyRouteTree(\n pattern.tree,\n resolvedParams,\n search,\n null, // Start with null partial vary path at the root\n acc\n )\n\n // The metadata tree is a flat page node without the intermediate layout\n // structure. Clone it with the updated metadata vary path collected during\n // the main tree traversal.\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n // This shouldn't be reachable for a valid route tree.\n return null\n }\n const reifiedMetadata = createMetadataRouteTree(metadataVaryPath)\n\n // Create a synthetic (predicted) entry and store it as the new pattern.\n //\n // Why replace the pattern? We intentionally update the pattern with this\n // synthetic entry so that if our prediction was wrong (server returns a\n // different pathname due to dynamic rewrite), the entry gets marked with\n // hasDynamicRewrite. Future predictions for this route will see the flag\n // and bail out to server resolution instead of making the same mistake.\n const syntheticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n tree: reifiedTree,\n metadata: reifiedMetadata,\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n hasDynamicRewrite: false,\n renderedSearch: search,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version,\n }\n\n matchedPart.pattern = syntheticEntry\n\n return syntheticEntry\n}\n\n/**\n * Result of a successful match: the matched tree node and its pattern.\n * We return both because the caller needs to update the pattern after\n * creating a synthetic entry (for dynamic rewrite detection).\n */\ntype KnownRouteMatch = {\n part: KnownRoutePart\n pattern: FulfilledRouteCacheEntry\n} | null\n\n/**\n * Recursively matches a URL against the known route tree.\n *\n * Matching priority (most specific first):\n * 1. Static children - exact path segment match\n * 2. Dynamic child - [param], [...param], [[...param]]\n * 3. Direct pattern - when no more URL parts remain\n *\n * Collects resolved param values in resolvedParams as it traverses.\n * Returns null if no match found (caller should fall back to server).\n */\nfunction matchKnownRoutePart(\n now: number,\n part: KnownRoutePart,\n pathnameParts: string[],\n partIndex: number,\n resolvedParams: ResolvedParams\n): KnownRouteMatch {\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n return null\n }\n\n // Static children take priority over dynamic. This ensures /blog/featured\n // matches its own route rather than /blog/[slug].\n if (urlPart !== null) {\n const staticChild = part.staticChildren.get(urlPart)\n if (staticChild !== undefined) {\n // Check if this is an \"unknown\" placeholder part. These are created when\n // we learn about static siblings (from the route tree's staticSiblings\n // field) but haven't prefetched them yet. We know the path exists but\n // don't know its structure, so we can't predict it.\n if (\n staticChild.pattern === null &&\n staticChild.dynamicChild === null &&\n staticChild.staticChildren === null\n ) {\n // Bail out - server must resolve this route.\n return null\n }\n const match = matchKnownRoutePart(\n now,\n staticChild,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n if (match !== null) {\n return match\n }\n // Static child is a real node (not a placeholder) but its subtree\n // didn't match the remaining URL parts. This means the route exists\n // in the static subtree but hasn't been fully discovered yet. Do not\n // fall through to try the dynamic child — the static match is\n // authoritative. Bail out to server resolution.\n return null\n }\n }\n\n // Try dynamic child. Skip it entirely if parallel route branches disagree\n // about the dynamic segment at this level — any pattern stored beneath it\n // was learned under a conflicting model.\n if (part.dynamicChild !== null && !part.hasConflictingDynamicChildren) {\n const dynamicPart = part.dynamicChild\n const paramName = part.dynamicChildParamName\n const paramType = part.dynamicChildParamType\n const dynamicPattern = readPattern(now, dynamicPart)\n\n switch (paramType) {\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (\n dynamicPattern !== null &&\n !dynamicPattern.hasDynamicRewrite &&\n urlPart !== null\n ) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n break\n case 'oc': {\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) {\n if (urlPart !== null) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n const directPattern = readPattern(now, part)\n if (directPattern === null || directPattern.hasDynamicRewrite) {\n resolvedParams.set(paramName, '')\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n }\n break\n }\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, urlPart)\n return matchKnownRoutePart(\n now,\n dynamicPart,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n }\n break\n // Intercepted routes use relative path markers like (.), (..), (...)\n // Their behavior depends on navigation context (soft vs hard nav),\n // so we can't predict them client-side. Defer to server.\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n return null\n default:\n paramType satisfies never\n }\n }\n\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n\n return null\n}\n\n/**\n * Accumulator for collecting data during reifyRouteTree traversal.\n * metadataVaryPath is collected from the first page node encountered\n * (parallel routes may have multiple pages, but metadata uses the first).\n */\ntype ReifyAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\n/**\n * \"Reify\" means to make concrete - we take an abstract pattern (the template\n * route tree) and produce a concrete instance with actual param values.\n *\n * This function clones a RouteTree, substituting dynamic segment values from\n * resolvedParams and computing new vary paths. The vary path encodes param\n * values so segment cache entries can be correctly keyed.\n *\n * Example: Pattern for /blog/[slug] with resolvedParams { slug: \"hello\" }\n * produces a tree where segment [slug] has cacheKey \"hello\".\n */\nfunction reifyRouteTree(\n pattern: RouteTree<null>,\n resolvedParams: ResolvedParams,\n search: NormalizedSearch,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n acc: ReifyAccumulator\n): RouteTree<null> {\n const originalSegment = pattern.segment\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam =\n (pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n let newSegment = originalSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const newValue = resolvedParams.get(paramName)\n if (newValue !== undefined) {\n // Catch-all values are already joined into a single string when they're\n // resolved in matchKnownRoutePart, so the value can be used directly.\n const newCacheKey = newValue\n newSegment = [paramName, newCacheKey, paramType, staticSiblings]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n newCacheKey,\n paramName,\n isRootParam\n )\n } else {\n // Param not found in resolvedParams - keep original and inherit partial\n // TODO: This should never happen. Bail out with null.\n partialVaryPath = parentPartialVaryPath\n }\n } else {\n // Static segment: inherit partial vary path from parent\n partialVaryPath = parentPartialVaryPath\n }\n\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots: Map<string, RouteTree<null>> | null = null\n const patternSlots = pattern.slots\n if (patternSlots !== null) {\n newSlots = new Map()\n for (const [key, childPattern] of patternSlots) {\n newSlots.set(\n key,\n reifyRouteTree(\n childPattern,\n resolvedParams,\n search,\n partialVaryPath,\n acc\n )\n )\n }\n }\n\n if (pattern.isPage) {\n // Page segment: finalize with search params\n const newVaryPath = finalizePageVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n // Collect metadata vary path (first page wins, same as original algorithm)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n // Route cache patterns never carry seed data (see\n // stripDataFromRouteTree), so neither do trees reified from them.\n data: null,\n varyPath: newVaryPath,\n isPage: true,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n } else {\n // Layout segment: finalize without search params\n const newVaryPath = finalizeLayoutVaryPath(\n pattern.requestKey,\n partialVaryPath\n )\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n data: null,\n varyPath: newVaryPath,\n isPage: false,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n }\n}\n\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */\nexport function resetKnownRoutes(): void {\n knownRouteTreeRoot = createEmptyPart()\n}\n"],"names":["discoverKnownRoute","matchKnownRoute","resetKnownRoutes","readPattern","now","part","pattern","isValueExpired","getCurrentRouteCacheVersion","createEmptyPart","staticChildren","dynamicChild","dynamicChildParamName","dynamicChildParamType","hasConflictingDynamicChildren","knownRouteTreeRoot","pathname","search","nextUrl","pendingEntry","routeTree","metadataVaryPath","couldBeIntercepted","canonicalUrl","supportsPerSegmentPrefetching","hasDynamicRewrite","tree","pathnameParts","splitPathnameIntoParts","fulfilledEntry","fulfillRouteCacheEntry","discoverKnownRoutePart","handleMismatchDueToRewrite","existingEntry","fullTree","writeRouteIntoCache","discoverDynamicChild","paramName","paramType","newChild","mutablePart","parentKnownRoutePart","partIndex","segment","urlPart","length","knownRoutePart","nextPartIndex","doesStaticSegmentAppearInURL","Map","existingChild","get","undefined","set","paramCacheKey","staticSiblings","includes","canonicalizeURLPart","joinedRemainingParts","slice","map","join","sibling","has","slots","resultFromChildren","childRouteTree","values","refreshState","result","existingPattern","entry","resolvedParams","match","matchKnownRoutePart","matchedPart","acc","reifiedTree","reifyRouteTree","reifiedMetadata","createMetadataRouteTree","syntheticEntry","status","EntryStatus","Fulfilled","blockedTasks","metadata","renderedSearch","ref","size","staleAt","version","staticChild","dynamicPart","dynamicPattern","directPattern","parentPartialVaryPath","originalSegment","isRootParam","prefetchHints","PrefetchHint","IsRootLayoutOrAbove","newSegment","partialVaryPath","newValue","newCacheKey","appendLayoutVaryPath","newSlots","patternSlots","key","childPattern","isPage","newVaryPath","finalizePageVaryPath","requestKey","finalizeMetadataVaryPath","shellVaryPath","getShellSegmentVaryPath","data","varyPath","finalizeLayoutVaryPath"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC;;;;;;;;;;;;;;;;IAoLeA,kBAAkB;eAAlBA;;IA0fAC,eAAe;eAAfA;;IA2YAC,gBAAgB;eAAhBA;;;gCAtjCa;uBAatB;0BACwB;6BAIxB;0BAEgC;0BAShC;AA4FP;;;;;;;CAOC,GACD,SAASC,YACPC,GAAW,EACXC,IAAoB;IAEpB,MAAMC,UAAUD,KAAKC,OAAO;IAC5B,IAAIA,YAAY,MAAM;QACpB,OAAO;IACT;IACA,IAAIC,IAAAA,wBAAc,EAACH,KAAKI,IAAAA,kCAA2B,KAAIF,UAAU;QAC/D,sEAAsE;QACtED,KAAKC,OAAO,GAAG;QACf,OAAO;IACT;IACA,OAAOA;AACT;AAEA,SAASG;IACP,OAAO;QACLC,gBAAgB;QAChBC,cAAc;QACdC,uBAAuB;QACvBC,uBAAuB;QACvBP,SAAS;QACTQ,+BAA+B;IACjC;AACF;AAEA,oCAAoC;AACpC,IAAIC,qBAAqCN;AAoBlC,SAAST,mBACdI,GAAW,EACXY,QAAgB,EAChBC,MAAwB,EACxBC,OAAsB,EACtBC,YAA2C,EAC3CC,SAA2C,EAC3CC,gBAA8B,EAC9BC,kBAA2B,EAC3BC,YAAoB,EACpBC,6BAAsC,EACtCC,iBAA0B;IAE1B,MAAMC,OAAON;IAEb,MAAMO,gBAAgBC,IAAAA,gCAAsB,EAACZ;IAE7C,IAAIG,iBAAiB,MAAM;QACzB,kCAAkC;Q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D,gBAAgB,GAAG8F,IAAAA,kCAAwB,EAC7C7G,QAAQ4G,UAAU,EAClBjG,QACAsF;QAEJ;QACA,OAAO;YACLW,YAAY5G,QAAQ4G,UAAU;YAC9BvE,SAAS2D;YACTc,eAAeC,IAAAA,iCAAuB,EAACL;YACvC5C,cAAc9D,QAAQ8D,YAAY;YAClC,kDAAkD;YAClD,kEAAkE;YAClEkD,MAAM;YACNC,UAAUP;YACVD,QAAQ;YACR/C,OAAO2C;YACPR,eAAe7F,QAAQ6F,aAAa;QACtC;IACF,OAAO;QACL,iDAAiD;QACjD,MAAMa,cAAcQ,IAAAA,gCAAsB,EACxClH,QAAQ4G,UAAU,EAClBX;QAEF,OAAO;YACLW,YAAY5G,QAAQ4G,UAAU;YAC9BvE,SAAS2D;YACTc,eAAeC,IAAAA,iCAAuB,EAACL;YACvC5C,cAAc9D,QAAQ8D,YAAY;YAClCkD,MAAM;YACNC,UAAUP;YACVD,QAAQ;YACR/C,OAAO2C;YACPR,eAAe7F,QAAQ6F,aAAa;QACtC;IACF;AACF;AAMO,SAASjG;IACda,qBAAqBN;AACvB","ignoreList":[0]}

@@ -12,3 +12,2 @@ "use strict";

const _dynamicrenderingutils = require("../../server/dynamic-rendering-utils");
const _ispostpone = require("../../server/lib/router-utils/is-postpone");
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");

@@ -19,3 +18,3 @@ const _isnextroutererror = require("./is-next-router-error");

function unstable_rethrow(error) {
if ((0, _isnextroutererror.isNextRouterError)(error) || (0, _bailouttocsr.isBailoutToCSRError)(error) || (0, _hooksservercontext.isDynamicServerError)(error) || (0, _dynamicrendering.isDynamicPostpone)(error) || (0, _ispostpone.isPostpone)(error) || (0, _dynamicrenderingutils.isHangingPromiseRejectionError)(error) || (0, _dynamicrendering.isPrerenderInterruptedError)(error)) {
if ((0, _isnextroutererror.isNextRouterError)(error) || (0, _bailouttocsr.isBailoutToCSRError)(error) || (0, _hooksservercontext.isDynamicServerError)(error) || (0, _dynamicrenderingutils.isHangingPromiseRejectionError)(error) || (0, _dynamicrendering.isPrerenderInterruptedError)(error)) {
throw error;

@@ -22,0 +21,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/client/components/unstable-rethrow.ts"],"sourcesContent":["import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isPostpone } from '../../server/lib/router-utils/is-postpone'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport {\n isDynamicPostpone,\n isPrerenderInterruptedError,\n} from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isDynamicPostpone(error) ||\n isPostpone(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n"],"names":["unstable_rethrow","error","isNextRouterError","isBailoutToCSRError","isDynamicServerError","isDynamicPostpone","isPostpone","isHangingPromiseRejectionError","isPrerenderInterruptedError","Error","cause"],"mappings":";;;;+BAsBgBA;;;eAAAA;;;uCAtB+B;4BACpB;8BACS;mCACF;kCAI3B;oCAC8B;AAc9B,SAASA,iBAAiBC,KAAc;IAC7C,IACEC,IAAAA,oCAAiB,EAACD,UAClBE,IAAAA,iCAAmB,EAACF,UACpBG,IAAAA,wCAAoB,EAACH,UACrBI,IAAAA,mCAAiB,EAACJ,UAClBK,IAAAA,sBAAU,EAACL,UACXM,IAAAA,qDAA8B,EAACN,UAC/BO,IAAAA,6CAA2B,EAACP,QAC5B;QACA,MAAMA;IACR;IAEA,IAAIA,iBAAiBQ,SAAS,WAAWR,OAAO;QAC9CD,iBAAiBC,MAAMS,KAAK;IAC9B;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/client/components/unstable-rethrow.ts"],"sourcesContent":["import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n"],"names":["unstable_rethrow","error","isNextRouterError","isBailoutToCSRError","isDynamicServerError","isHangingPromiseRejectionError","isPrerenderInterruptedError","Error","cause"],"mappings":";;;;+BAkBgBA;;;eAAAA;;;uCAlB+B;8BACX;mCACF;kCACU;oCACP;AAc9B,SAASA,iBAAiBC,KAAc;IAC7C,IACEC,IAAAA,oCAAiB,EAACD,UAClBE,IAAAA,iCAAmB,EAACF,UACpBG,IAAAA,wCAAoB,EAACH,UACrBI,IAAAA,qDAA8B,EAACJ,UAC/BK,IAAAA,6CAA2B,EAACL,QAC5B;QACA,MAAMA;IACR;IAEA,IAAIA,iBAAiBM,SAAS,WAAWN,OAAO;QAC9CD,iBAAiBC,MAAMO,KAAK;IAC9B;AACF","ignoreList":[0]}

@@ -63,3 +63,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build.

const _isnextroutererror = require("./components/is-next-router-error");
const version = "16.3.1-canary.11";
const version = "16.3.1-canary.12";
let router;

@@ -66,0 +66,0 @@ const emitter = (0, _mitt.default)();

@@ -8,2 +8,3 @@ import type { DynamicParamTypesShort } from '../shared/lib/app-router-types';

export declare function getRenderedPathname(response: RSCResponse<unknown> | Response): NormalizedPathname;
export declare function canonicalizeURLPart(part: string): string;
export declare function parseDynamicParamFromURLPart(paramType: DynamicParamTypesShort, pathnameParts: Array<string>, partIndex: number): RouteParamValue;

@@ -10,0 +11,0 @@ export declare function doesStaticSegmentAppearInURL(segment: string): boolean;

@@ -6,2 +6,3 @@ "use strict";

0 && (module.exports = {
canonicalizeURLPart: null,
doesStaticSegmentAppearInURL: null,

@@ -23,2 +24,5 @@ getCacheKeyForDynamicParam: null,

_export(exports, {
canonicalizeURLPart: function() {
return canonicalizeURLPart;
},
doesStaticSegmentAppearInURL: function() {

@@ -77,10 +81,2 @@ return doesStaticSegmentAppearInURL;

}
// Pathname parts come from `URL.pathname.split('/')`, so they are already
// in the encoded form the URL parser produces. The server-side equivalent
// (`get-dynamic-param.ts`) starts from a decoded param value and applies
// `encodeURIComponent` once. The two encodings are not the same — for
// example, the URL parser leaves `,` and `:` untouched while
// `encodeURIComponent` percent-encodes them. To produce the same canonical
// form on the client (and avoid double-encoding `%xx` sequences such as
// `%2F` → `%252F`), we decode the URL part first and re-encode it.
function canonicalizeURLPart(part) {

@@ -87,0 +83,0 @@ try {

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../src/client/route-params.ts"],"sourcesContent":["import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport { hasBasePath } from './has-base-path'\nimport { removeBasePath } from './remove-base-path'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return (\n rewrittenQuery === '' ? '' : '?' + rewrittenQuery\n ) as NormalizedSearch\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return urlToUrlWithoutFlightMarker(new URL(response.url))\n .search as NormalizedSearch\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n if (rewrittenPath !== null) {\n return rewrittenPath as NormalizedPathname\n }\n\n const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n return (\n hasBasePath(pathname) ? removeBasePath(pathname) : pathname\n ) as NormalizedPathname\n}\n\n// Pathname parts come from `URL.pathname.split('/')`, so they are already\n// in the encoded form the URL parser produces. The server-side equivalent\n// (`get-dynamic-param.ts`) starts from a decoded param value and applies\n// `encodeURIComponent` once. The two encodings are not the same — for\n// example, the URL parser leaves `,` and `:` untouched while\n// `encodeURIComponent` percent-encodes them. To produce the same canonical\n// form on the client (and avoid double-encoding `%xx` sequences such as\n// `%2F` → `%252F`), we decode the URL part first and re-encode it.\nfunction canonicalizeURLPart(part: string): string {\n try {\n return encodeURIComponent(decodeURIComponent(part))\n } catch {\n // `decodeURIComponent` throws on malformed sequences. Fall back to the\n // already-encoded form rather than failing the navigation.\n return part\n }\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return canonicalizeURLPart(s.slice(prefix))\n }\n\n return canonicalizeURLPart(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return canonicalizeURLPart(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n const prefix = paramType.length - 2\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n\n return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment.startsWith(PAGE_SEGMENT_KEY) ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue,\n renderedSearch: NormalizedSearch\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(\n paramValue,\n urlSearchParamsToParsedUrlQuery(new URLSearchParams(renderedSearch))\n ) as string\n return pageSegmentWithSearchParams\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n const length = pathname.endsWith('/index.txt') ? 10 : 4\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = pathname.slice(0, -length)\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc'\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/')\n }\n return paramCacheKey\n}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n if (result[key] === undefined) {\n result[key] = value\n } else if (Array.isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [result[key], value]\n }\n }\n return result\n}\n"],"names":["doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getParamValueFromCacheKey","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","urlSearchParamsToParsedUrlQuery","urlToUrlWithoutFlightMarker","response","rewrittenQuery","headers","get","NEXT_REWRITTEN_QUERY_HEADER","URL","url","search","rewrittenPath","NEXT_REWRITTEN_PATH_HEADER","pathname","hasBasePath","removeBasePath","canonicalizeURLPart","part","encodeURIComponent","decodeURIComponent","paramType","pathnameParts","partIndex","length","slice","map","s","prefix","i","segment","ROOT_SEGMENT_REQUEST_KEY","startsWith","PAGE_SEGMENT_KEY","endsWith","DEFAULT_SEGMENT_KEY","paramValue","renderedSearch","pageSegmentWithSearchParams","addSearchParamsIfPageSegment","URLSearchParams","join","urlWithoutFlightParameters","searchParams","delete","NEXT_RSC_UNION_QUERY","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","paramCacheKey","isCatchAll","split","result","key","value","entries","undefined","Array","isArray","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;IA0JgBA,4BAA4B;eAA5BA;;IA4BAC,0BAA0B;eAA1BA;;IAwCAC,yBAAyB;eAAzBA;;IArLAC,mBAAmB;eAAnBA;;IAlBAC,iBAAiB;eAAjBA;;IAqDAC,4BAA4B;eAA5BA;;IAqKAC,+BAA+B;eAA/BA;;IApCAC,2BAA2B;eAA3BA;;;yBAxMT;sCACkC;kCAKlC;6BACqB;gCACG;AAUxB,SAASH,kBACdI,QAAyC;IAEzC,0EAA0E;IAC1E,2EAA2E;IAC3E,4EAA4E;IAC5E,MAAMC,iBAAiBD,SAASE,OAAO,CAACC,GAAG,CAACC,6CAA2B;IACvE,IAAIH,mBAAmB,MAAM;QAC3B,OACEA,mBAAmB,KAAK,KAAK,MAAMA;IAEvC;IACA,2EAA2E;IAC3E,6BAA6B;IAC7B,OAAOF,4BAA4B,IAAIM,IAAIL,SAASM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,aAAaa,OAAO,GAAI;QACjD,IAAIH,MAAM,CAACC,IAAI,KAAKG,WAAW;YAC7BJ,MAAM,CAACC,IAAI,GAAGC;QAChB,OAAO,IAAIG,MAAMC,OAAO,CAACN,MAAM,CAACC,IAAI,GAAG;YACrCD,MAAM,CAACC,IAAI,CAACM,IAAI,CAACL;QACnB,OAAO;YACLF,MAAM,CAACC,IAAI,GAAG;gBAACD,MAAM,CAACC,IAAI;gBAAEC;aAAM;QACpC;IACF;IACA,OAAOF;AACT","ignoreList":[0]}
{"version":3,"sources":["../../src/client/route-params.ts"],"sourcesContent":["import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport { hasBasePath } from './has-base-path'\nimport { removeBasePath } from './remove-base-path'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return (\n rewrittenQuery === '' ? '' : '?' + rewrittenQuery\n ) as NormalizedSearch\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return urlToUrlWithoutFlightMarker(new URL(response.url))\n .search as NormalizedSearch\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n if (rewrittenPath !== null) {\n return rewrittenPath as NormalizedPathname\n }\n\n const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n return (\n hasBasePath(pathname) ? removeBasePath(pathname) : pathname\n ) as NormalizedPathname\n}\n\n// Pathname parts come from `URL.pathname.split('/')`, so they are already\n// in the encoded form the URL parser produces. The server-side equivalent\n// (`get-dynamic-param.ts`) starts from a decoded param value and applies\n// `encodeURIComponent` once. The two encodings are not the same — for\n// example, the URL parser leaves `,` and `:` untouched while\n// `encodeURIComponent` percent-encodes them. To produce the same canonical\n// form on the client (and avoid double-encoding `%xx` sequences such as\n// `%2F` → `%252F`), we decode the URL part first and re-encode it.\nexport function canonicalizeURLPart(part: string): string {\n try {\n return encodeURIComponent(decodeURIComponent(part))\n } catch {\n // `decodeURIComponent` throws on malformed sequences. Fall back to the\n // already-encoded form rather than failing the navigation.\n return part\n }\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return canonicalizeURLPart(s.slice(prefix))\n }\n\n return canonicalizeURLPart(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return canonicalizeURLPart(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n const prefix = paramType.length - 2\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n\n return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment.startsWith(PAGE_SEGMENT_KEY) ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue,\n renderedSearch: NormalizedSearch\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(\n paramValue,\n urlSearchParamsToParsedUrlQuery(new URLSearchParams(renderedSearch))\n ) as string\n return pageSegmentWithSearchParams\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n const length = pathname.endsWith('/index.txt') ? 10 : 4\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = pathname.slice(0, -length)\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc'\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/')\n }\n return paramCacheKey\n}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n if (result[key] === undefined) {\n result[key] = value\n } else if (Array.isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [result[key], value]\n }\n }\n return result\n}\n"],"names":["canonicalizeURLPart","doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getParamValueFromCacheKey","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","urlSearchParamsToParsedUrlQuery","urlToUrlWithoutFlightMarker","response","rewrittenQuery","headers","get","NEXT_REWRITTEN_QUERY_HEADER","URL","url","search","rewrittenPath","NEXT_REWRITTEN_PATH_HEADER","pathname","hasBasePath","removeBasePath","part","encodeURIComponent","decodeURIComponent","paramType","pathnameParts","partIndex","length","slice","map","s","prefix","i","segment","ROOT_SEGMENT_REQUEST_KEY","startsWith","PAGE_SEGMENT_KEY","endsWith","DEFAULT_SEGMENT_KEY","paramValue","renderedSearch","pageSegmentWithSearchParams","addSearchParamsIfPageSegment","URLSearchParams","join","urlWithoutFlightParameters","searchParams","delete","NEXT_RSC_UNION_QUERY","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","paramCacheKey","isCatchAll","split","result","key","value","entries","undefined","Array","isArray","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;;IAkEgBA,mBAAmB;eAAnBA;;IAwFAC,4BAA4B;eAA5BA;;IA4BAC,0BAA0B;eAA1BA;;IAwCAC,yBAAyB;eAAzBA;;IArLAC,mBAAmB;eAAnBA;;IAlBAC,iBAAiB;eAAjBA;;IAqDAC,4BAA4B;eAA5BA;;IAqKAC,+BAA+B;eAA/BA;;IApCAC,2BAA2B;eAA3BA;;;yBAxMT;sCACkC;kCAKlC;6BACqB;gCACG;AAUxB,SAASH,kBACdI,QAAyC;IAEzC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ACT;AAEO,SAAS/C,gCACdwC,YAA6B;IAE7B,6EAA6E;IAC7E,iEAAiE;IACjE,wBAAwB;IACxB,MAAMU,SAAyB,CAAC;IAChC,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIZ,aAAaa,OAAO,GAAI;QACjD,IAAIH,MAAM,CAACC,IAAI,KAAKG,WAAW;YAC7BJ,MAAM,CAACC,IAAI,GAAGC;QAChB,OAAO,IAAIG,MAAMC,OAAO,CAACN,MAAM,CAACC,IAAI,GAAG;YACrCD,MAAM,CAACC,IAAI,CAACM,IAAI,CAACL;QACnB,OAAO;YACLF,MAAM,CAACC,IAAI,GAAG;gBAACD,MAAM,CAACC,IAAI;gBAAEC;aAAM;QACpC;IACF;IACA,OAAOF;AACT","ignoreList":[0]}

@@ -9,2 +9,3 @@ ---

- app/api-reference/directives/use-client
- app/guides/server-and-client-boundary
---

@@ -16,2 +17,4 @@

> **Good to know:** For an explanation of where each component type runs and how the boundary works, see [The Server and Client Boundary](/docs/app/guides/server-and-client-boundary).
## When to use Server and Client Components?

@@ -111,3 +114,3 @@

>
> The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:
> The RSC Payload is a compact, serialized representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:
>

@@ -189,3 +192,3 @@ > - The rendered result of Server Components

For example, the `<Layout>` component contains mostly static elements like a logo and navigation links, but includes an interactive search bar. `<Search />` is interactive and needs to be a Client Component, however, the rest of the layout can remain a Server Component.
For example, the `<Layout>` component contains mostly static elements like a logo and navigation links, but includes an interactive search bar. `<Search />` needs to be a Client Component, while the rest of the layout can stay a Server Component.

@@ -192,0 +195,0 @@ ```tsx filename="app/layout.tsx" highlight={12} switcher

@@ -374,2 +374,4 @@ ---

See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating a library cache with the Next.js server and client caches.
## Examples

@@ -376,0 +378,0 @@

---
title: How to use authentication with Cache Components
title: How to implement authentication with Cache Components
nav_title: Authentication with Cache Components

@@ -4,0 +4,0 @@ description: 'Learn how to read the user session, show authenticated UI without slowing down the page, and cache data derived from the session when Cache Components is enabled.'

@@ -769,4 +769,6 @@ ---

- [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and client cache coordination
- [Streaming](/docs/app/guides/streaming) for loading boundaries and `<Suspense>` patterns
- [Instant Navigation](/docs/app/guides/instant-navigation) for validating that navigations stay instant
- [View Transitions](/docs/app/guides/view-transitions) for animating state changes
- [Single-page applications](/docs/app/guides/single-page-applications#mutating-data-with-server-actions) for a shared-reducer `useOptimistic` example that keeps client and server list updates in sync

@@ -8,2 +8,3 @@ ---

links:
- app/guides/client-side-data-fetching
- app/guides/interactive-apps

@@ -13,18 +14,13 @@ - app/guides/server-actions

- app/guides/streaming
- app/api-reference/components/link
- app/guides/static-exports
---
Next.js fully supports building Single-Page Applications (SPAs).
Build Single-Page Applications (SPAs) with client-side navigation and data fetching. Next.js supports client and server patterns in the same app, and existing SPAs can migrate without a full rewrite.
This includes fast route transitions with prefetching, client-side data fetching, using browser APIs, integrating with third-party client libraries, creating static routes, and more.
If you have an existing SPA, you can migrate to Next.js without large changes to your code. Next.js then allows you to progressively add server features as needed.
## What is a Single-Page Application?
The definition of a SPA varies. We’ll define a “strict SPA” as:
The definition of a SPA varies. We'll define a "strict SPA" as:
- **Client-side rendering (CSR)**: The app is served by one HTML file (e.g. `index.html`). Every route, page transition, and data fetch is handled by JavaScript in the browser.
- **No full-page reloads**: Rather than requesting a new document for each route, client-side JavaScript manipulates the current page’s DOM and fetches data as needed.
- **No full-page reloads**: Rather than requesting a new document for each route, client-side JavaScript manipulates the current page's DOM and fetches data as needed.

@@ -39,16 +35,18 @@ Strict SPAs often require large amounts of JavaScript to load before the page can be interactive. Further, client data waterfalls can be challenging to manage. Building SPAs with Next.js can address these issues.

Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, Next.js allows you to progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/guides/server-actions), and more) as needed.
Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, you can progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/guides/server-actions), and more) as needed.
## Examples
## Build common SPA patterns
The following examples cover common patterns for building an SPA with Next.js. The companion [demo](https://next-spa-patterns.labs.vercel.dev) ([source](https://github.com/vercel-labs/next-spa-patterns)) shows each pattern in action.
### Using React’s `use` within a Context Provider
### Using React's `use` within a Context Provider
You can use React’s [`use` API](https://react.dev/reference/react/use) to stream data from the server to a Client Component. Fetch the data in a Server Component (a parent or layout) and pass the Promise down. The Client Component unwraps it with `use()`, since it cannot `await` during render.
You can use React's [`use` API](https://react.dev/reference/react/use) to stream data from the server to a Client Component. Fetch the data in a Server Component (a parent or layout) and pass the Promise down. The Client Component unwraps it with `use()`, since it cannot `await` during render.
Starting the request on the server, before the rest of the app renders, lets the response stream immediately and avoids client-side request waterfalls.
You can pass a single Promise as a prop and unwrap it with `use()`, or pair it with a React context provider so any Client Component can read the value through a custom hook. A provider isn't always the best fit: often you can read the data in a Server Component, or pass the Promise directly, rather than putting everything in context. For general client-side data fetching, a library like [SWR](#spas-with-swr) can help.
You can pass a single Promise as a prop and unwrap it with `use()`, or pair it with a React context provider so any Client Component can read the value through a custom hook.
When a Client Component needs focus revalidation, polling, mutations, or request deduplication, use a library such as SWR or TanStack Query. See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating the library cache with the Next.js server and client caches.
Start the request in a Server Component (here, the root layout) without awaiting it, and pass the Promise to the provider:

@@ -160,3 +158,3 @@

return '...'
return <p>{user.name}</p>
}

@@ -175,10 +173,8 @@ ```

return '...'
return <p>{user.name}</p>
}
```
You can also move the `use()` call into the `useUser` hook so components just call `const user = useUser()`. That reads cleanly, but calling `use()` in the component keeps it clear where the component suspends.
Wrap the consumer in a [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary to show a fallback while the Promise resolves:
Wrap the consumer in a `<Suspense>` boundary to show a fallback while the Promise resolves:
```tsx filename="app/page.tsx" switcher

@@ -214,321 +210,2 @@ import { Suspense } from 'react'

### SPAs with SWR
[SWR](https://swr.vercel.app) is a popular React library for data fetching.
With SWR 2.3.0 (and React 19+), you can gradually adopt server features alongside your existing SWR-based client data fetching code. This is an abstraction of the above `use()` pattern. This means you can move data fetching between the client and server-side, or use both:
- **Client-only:** `useSWR(key, fetcher)`
- **Server-only:** `useSWR(key)` + RSC-provided data
- **Mixed:** `useSWR(key, fetcher)` + RSC-provided data
Reach for SWR when you need its client-side features, such as revalidation on focus or interval, [`mutate`](https://swr.vercel.app/docs/mutation), or request deduplication across components. If a Client Component only needs to read server data once, pass a Promise to it and unwrap it with [`use()`](#using-reacts-use-within-a-context-provider) instead. That avoids adding a data-fetching library for data that never revalidates on the client.
To provide server data to SWR on the first render, wrap your application in `<SWRConfig>` and provide a `fallback`:
```tsx filename="app/layout.tsx" switcher
import { SWRConfig } from 'swr'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
'/api/user': getUser(),
},
}}
>
{children}
</SWRConfig>
)
}
```
```js filename="app/layout.js" switcher
import { SWRConfig } from 'swr'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
'/api/user': getUser(),
},
}}
>
{children}
</SWRConfig>
)
}
```
Because this is a Server Component, `getUser()` can securely read cookies, headers, or talk to your database. No separate API route is needed. Client components below the `<SWRConfig>` can call `useSWR()` with the same key to retrieve the user data. The component code with `useSWR` **does not require any changes** from your existing client-fetching solution.
```tsx filename="app/profile.tsx" switcher
'use client'
import useSWR from 'swr'
export function Profile() {
const fetcher = (url: string) => fetch(url).then((res) => res.json())
const { data, error } = useSWR('/api/user', fetcher)
return '...'
}
```
```jsx filename="app/profile.js" switcher
'use client'
import useSWR from 'swr'
export function Profile() {
const fetcher = (url) => fetch(url).then((res) => res.json())
const { data, error } = useSWR('/api/user', fetcher)
return '...'
}
```
The `fallback` data can be prerendered and included in the initial HTML response, then immediately read in the child components using `useSWR`. SWR’s polling, revalidation, and caching still run **client-side only**, so it preserves all the interactivity you rely on for an SPA.
Because Next.js seeds the `fallback` on the server, `useSWR` has data on first render, so there's no need for conditional logic to handle an `undefined` `data`. The seeded data counts as loaded, so [`isLoading`](https://swr.vercel.app/docs/advanced/understanding#combining-with-isloading-and-isvalidating-for-better-ux) stays `false`. A client-side revalidation surfaces as `isValidating` instead, which you can use to show a background-refresh indicator.
| | SWR | RSC | RSC + SWR |
| -------------------- | ------------------- | ------------------- | ------------------- |
| SSR data | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Streaming while SSR | <Cross size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Deduplicate requests | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
| Client-side features | <Check size={18} /> | <Cross size={18} /> | <Check size={18} /> |
#### Scoping server data to the components that use it
`<SWRConfig>` can live in any Server Component, not only the root layout. Placing it on the route segment that owns the data keeps the `fallback` close to where it is read, keeps unrelated keys out of a global config, and lets each segment start its own server-side requests. Nested `<SWRConfig>` providers merge their fallbacks, so a page-level config extends the keys seeded by a parent layout rather than replacing them:
```tsx filename="app/projects/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProject } from './data' // some server-side function
import { ProjectView } from './project-view'
export default function Page({ params }: PageProps<'/projects/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[`/api/projects/${id}`]: getProject(id),
},
}}
>
<ProjectView id={id} />
</SWRConfig>
)
}
```
```jsx filename="app/projects/[id]/page.js" switcher
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProject } from './data' // some server-side function
import { ProjectView } from './project-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// Not awaited: only components that read this key suspend
[`/api/projects/${id}`]: getProject(id),
},
}}
>
<ProjectView id={id} />
</SWRConfig>
)
}
```
Inside `<Suspense>`, `params.then()` resolves the `id` and passes it to `ProjectData`, which seeds the `fallback` with the `getProject(id)` promise. Only that subtree suspends while the data loads.
The Client Component reads the data with `useSWR` using the same key:
```tsx filename="app/projects/[id]/project-view.tsx" switcher
'use client'
import useSWR from 'swr'
const fetcher = (url: string) => fetch(url).then((res) => res.json())
export function ProjectView({ id }: { id: string }) {
// This key must match the `fallback` key exactly.
const { data } = useSWR(`/api/projects/${id}`, fetcher)
return <h1>{data?.name}</h1>
}
```
```jsx filename="app/projects/[id]/project-view.js" switcher
'use client'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((res) => res.json())
export function ProjectView({ id }) {
// This key must match the `fallback` key exactly.
const { data } = useSWR(`/api/projects/${id}`, fetcher)
return <h1>{data?.name}</h1>
}
```
> **Good to know:** The `fallback` key and the `useSWR` key must match exactly, since SWR looks up the seeded value by key. Nothing warns on a mismatch: the seeded value is never read, `data` starts as `undefined`, and SWR fetches again on the client. When a key is built from dynamic values (route params, search params), derive it in one shared place so the server and client cannot drift apart. `fallback` seeds the first render, not SWR's persistent cache, so use [`preload`](https://swr.vercel.app/docs/prefetching) to fill the cache and reuse the request on revalidation.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/swr) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/swr).
### SPAs with TanStack Query
You can use [TanStack Query](https://tanstack.com/query) (formerly React Query) with Next.js on the client and the server, and seed its cache from a Server Component the same way as [SWR](#spas-with-swr): prefetch on the server, hand the cache to the client, and let it own revalidation from there.
TanStack Query needs a one-time setup, including a `getQueryClient` (new per request on the server, a singleton in the browser), a `<QueryClientProvider>`, and a client configured to dehydrate pending queries. TanStack Query owns this integration, so follow [its Advanced SSR guide](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) for the full setup and current APIs.
A Server Component starts the request with `prefetchQuery` **without awaiting it**, then serializes the cache into the streamed HTML with `<HydrationBoundary>`:
```tsx filename="app/projects/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { getProject } from './data' // runs on the server and the client
import { ProjectView } from './project-view'
export default function Page({ params }: PageProps<'/projects/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }: { id: string }) {
const queryClient = getQueryClient()
// Not awaited, so rendering is not blocked.
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectView id={id} />
</HydrationBoundary>
)
}
```
```jsx filename="app/projects/[id]/page.js" switcher
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
import { getQueryClient } from '@/app/get-query-client'
import { getProject } from './data' // runs on the server and the client
import { ProjectView } from './project-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProjectData id={id} />
))}
</Suspense>
)
}
function ProjectData({ id }) {
const queryClient = getQueryClient()
// Not awaited, so rendering is not blocked.
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectView id={id} />
</HydrationBoundary>
)
}
```
As with SWR, `params.then()` resolves the `id` inside `<Suspense>`, and `ProjectData` prefetches below the boundary.
The Client Component reads the data with the same query key. Use `useSuspenseQuery` when a `<Suspense>` boundary handles loading and you want `data` to always be defined. Use `useQuery` when you would rather render its `isPending` and `error` states inline:
```tsx filename="app/projects/[id]/project-view.tsx" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getProject } from './data'
export function ProjectView({ id }: { id: string }) {
// This query key must match the server prefetch.
const { data } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return <h1>{data.name}</h1>
}
```
```jsx filename="app/projects/[id]/project-view.js" switcher
'use client'
import { useSuspenseQuery } from '@tanstack/react-query'
import { getProject } from './data'
export function ProjectView({ id }) {
// This query key must match the server prefetch.
const { data } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => getProject(id),
})
return <h1>{data.name}</h1>
}
```
The query key connects the two sides, the same way the matching `fallback` and `useSWR` keys do above.
> **Good to know:** When you cache this data with [Cache Components](/docs/app/getting-started/caching), add [`"use cache"`](/docs/app/api-reference/directives/use-cache) to the data function (such as `getProject`), not around `dehydrate()`. Caching the dehydrated state also caches TanStack Query metadata such as timestamps, which can serve stale data on later requests.
See the [live demo](https://next-spa-patterns.labs.vercel.dev/react-query) and its [source code](https://github.com/vercel-labs/next-spa-patterns/tree/main/app/react-query).
### Rendering components only in the browser

@@ -554,5 +231,5 @@

Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.
Next.js lets you use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.
`pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).
The `pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).

@@ -611,3 +288,3 @@ ```tsx filename="app/ui/sort-products.tsx" switcher

The sections above seed client-side data-fetching libraries from the server, which handle reads. Interactivity means writing data, and that usually happens outside those libraries: a Client Component calls a [Server Action](/docs/app/guides/server-actions) to run the mutation on the server. If you already use SWR or TanStack Query, you can instead write through an API route and revalidate with SWR's [`mutate`](https://swr.vercel.app/docs/mutation) or TanStack Query's [`invalidateQueries`](https://tanstack.com/query/latest/docs/framework/react/guides/invalidations-from-mutations). The rest of this section uses Server Actions directly.
Interactivity often requires writing data. A Client Component can call a [Server Action](/docs/app/guides/server-actions) to run the mutation on the server. A client data-fetching library can coordinate an optimistic browser update around the same Server Action, as shown in the [client-side data fetching guide](/docs/app/guides/client-side-data-fetching#coordinate-mutations). The rest of this section coordinates the Server Action with React's built-in state APIs.

@@ -874,3 +551,3 @@ A Server Action takes time and can fail. React has useful tools to keep the UI responsive while it runs, so a mutation can feel as instant as a client-rendered SPA: [transitions](https://react.dev/reference/react/useTransition), [`useOptimistic`](https://react.dev/reference/react/useOptimistic), [`useActionState`](https://react.dev/reference/react/useActionState), and [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus).

- **Automatic code-splitting**: Instead of shipping a single `index.html`, Next.js will generate an HTML file per route, so your visitors get the content faster without waiting for the client JavaScript bundle.
- **Improved user experience:** Instead of a minimal skeleton for all routes, you get fully rendered pages for each route. When users navigate client side, transitions remain instant and SPA-like.
- **Improved user experience:** Instead of a minimal skeleton for all routes, you get fully rendered pages for each route. When users navigate client side, transitions are still instant and SPA-like.

@@ -877,0 +554,0 @@ To enable a static export, update your configuration:

---
title: Directives
description: Directives are used to modify the behavior of your Next.js application.
description: Learn how React and Next.js directives define client entry points, Server Functions, and cached output.
---
The following directives are available:
Directives are string literals that tell the compiler and bundler how to treat the code around them. On their own, directives look like plain strings, but Next.js and React read them as instructions that transform the code they cover. A directive can create a client entry point or a Server Function, or cache a function's or component's output.
| Directive | Defined by | Effect |
| --------------------------------------------------------------- | ---------- | --------------------------------------------------- |
| [`'use client'`](/docs/app/api-reference/directives/use-client) | React | Creates a client entry point from Server Components |
| [`'use server'`](/docs/app/api-reference/directives/use-server) | React | Exposes server-side functions as Server Functions |
| [`'use cache'`](/docs/app/api-reference/directives/use-cache) | Next.js | Caches and reuses output based on the code's inputs |
The `'use cache'` directive also has [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) and [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private) variants. Configure custom [cache handlers](/docs/app/api-reference/config/next-config-js/cacheHandlers) to control where cached entries are stored.
> **Good to know:** Next.js applies directives during compilation in both development and production.
>
> The error overlay, indicators, and stack traces point to your source file and line rather than the generated output.
## Where to place a directive
The `'use client'` directive must appear at the top of a file, before any imports. It applies to the entire module and defines a file-wide boundary because the module is bundled and shipped to the browser. You cannot use `'use client'` inline.
Place `'use server'` or `'use cache'` at the top of a file to apply the directive to every export. Place either directive at the top of a function to apply it only to that function.
```ts filename="app/data.ts" switcher
// File-level: applies to every export
'use cache'
export async function getUser(id: string) {
return { id }
}
```
```js filename="app/data.js" switcher
// File-level: applies to every export
'use cache'
export async function getUser(id) {
return { id }
}
```
```tsx filename="app/user.tsx" switcher
// Function-level: applies to this function only
export async function User() {
'use cache'
return <p>User</p>
}
```
```jsx filename="app/user.js" switcher
// Function-level: applies to this function only
export async function User() {
'use cache'
return <p>User</p>
}
```
Declare `'use server'` and `'use cache'` in server modules, not in a `'use client'` module.
To import a `'use server'` or `'use cache'` function into a Client Component, place the directive at the top of the server module. The Client Component receives a reference that invokes the function on the server.
Place the directive inside a function when it should apply only to that function or component. When it should apply to several exported functions, place it at the top of the file instead of repeating it.
Every exported function covered by a file-level `'use server'` or `'use cache'` directive must be `async`.
## What each directive requires
A directive imposes rules on the code it covers:
- **`'use client'`** marks its exports as the boundary between server and client. Client Component props that cross the boundary must be [serializable](https://react.dev/reference/rsc/use-client#serializable-types). Ordinary functions, such as event handlers, cannot cross, but Server Functions can cross as references.
- **`'use server'`** marks the functions it covers as [Server Functions](/docs/app/glossary#server-function). Server Functions must be `async`. When invoked from a Client Component, their arguments and return values are serialized across the network. The Client Component receives a reference that invokes the function on the server, not the function's code.
- **`'use cache'`** caches the output of the functions or components it covers based on their inputs. Cached functions and components must be `async`. Their arguments and return values must be serializable, except for non-serializable values that the cached code passes through without inspecting. Cached code cannot read request-time APIs like `cookies()`, `headers()`, or `searchParams` directly.
File-level directive rules also apply to framework exports. With `'use cache'` at the top of a page or layout file, exported functions such as `generateMetadata` and `generateStaticParams` must be `async`. A file-level `'use cache'` directive does not allow non-function exports.
## Placement decides what you cache
With `'use cache'`, placement determines the scope of a cache entry. A directive at the top of a page caches the page's output and the components it imports. The same directive inside a data function caches only that function's result. When one data request performs the expensive work, cache that function instead of the page.
With [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote), a remote cache handler stores entries. Larger entries can increase storage and network costs.

@@ -10,3 +10,3 @@ ---

>
> You do not need to add the `'use client'` directive to every file that contains Client Components. You only need to add it to the files whose components you want to render directly within Server Components. The `'use client'` directive defines the client-server [boundary](https://nextjs.org/docs/app/getting-started/server-and-client-components#using-client-components), and the components exported from such a file serve as entry points to the client.
> You do not need to add the `'use client'` directive to every file that contains Client Components. You only need to add it to the files whose components you want to render directly within Server Components. The `'use client'` directive defines the [server and client boundary](/docs/app/guides/server-and-client-boundary), and the components exported from such a file serve as entry points to the client.

@@ -13,0 +13,0 @@ ## Usage

@@ -281,2 +281,17 @@ ---

Pass the module type to describe what the matched files export:
```ts
interface Mod {
name: string
default: () => string
}
// Record<string, () => Promise<Mod>>
const lazy = import.meta.glob<Mod>('./dir/*.ts')
// Record<string, Mod>
const eager = import.meta.glob<Mod>('./dir/*.ts', { eager: true })
```
### Options reference

@@ -283,0 +298,0 @@

@@ -13,3 +13,2 @@ import { setGlobal } from '../../trace';

import { generateRoutesManifest } from '../generate-routes-manifest';
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr';
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths';

@@ -122,3 +121,3 @@ import http from 'node:http';

].map((pathPrefix)=>config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix);
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr);
const isAppPPREnabled = Boolean(config.cacheComponents);
// Generate routes manifest

@@ -125,0 +124,0 @@ const { routesManifest } = generateRoutesManifest({

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/build/analyze/index.ts"],"sourcesContent":["import type { NextConfigComplete } from '../../server/config-shared'\nimport type { __ApiPreviewProps } from '../../server/api-utils'\n\nimport { setGlobal } from '../../trace'\nimport * as Log from '../output/log'\nimport * as path from 'node:path'\nimport loadConfig from '../../server/config'\nimport { PHASE_ANALYZE } from '../../shared/lib/constants'\nimport { turbopackAnalyze, type AnalyzeContext } from '../turbopack-analyze'\nimport { durationToString } from '../duration-to-string'\nimport { cp, writeFile, mkdir } from 'node:fs/promises'\nimport { discoverRoutes } from '../route-discovery'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport loadCustomRoutes from '../../lib/load-custom-routes'\nimport { generateRoutesManifest } from '../generate-routes-manifest'\nimport { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport http from 'node:http'\n\n// @ts-expect-error types are in @types/serve-handler\nimport serveHandler from 'next/dist/compiled/serve-handler'\nimport { Telemetry } from '../../telemetry/storage'\nimport { eventAnalyzeCompleted } from '../../telemetry/events'\nimport { traceGlobals } from '../../trace/shared'\nimport type { RoutesManifest } from '..'\nimport { Bundler } from '../../lib/bundler'\n\nexport type AnalyzeOptions = {\n dir: string\n reactProductionProfiling?: boolean\n noMangling?: boolean\n appDirOnly?: boolean\n output?: boolean\n port?: number\n}\n\nexport default async function analyze({\n dir,\n reactProductionProfiling = false,\n noMangling = false,\n appDirOnly = false,\n output = false,\n port = 4000,\n}: AnalyzeOptions): Promise<void> {\n try {\n // analyze is Turbopack-only. Mirror what parseBundlerArgs does for build/dev\n // so every process.env.TURBOPACK consumer in this run agrees with the bundler choice.\n process.env.TURBOPACK ??= '1'\n const config: NextConfigComplete = await loadConfig(PHASE_ANALYZE, dir, {\n silent: false,\n reactProductionProfiling,\n bundler: Bundler.Turbopack,\n })\n\n process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''\n\n const distDir = path.join(dir, '.next')\n const telemetry = new Telemetry({ distDir })\n setGlobal('phase', PHASE_ANALYZE)\n setGlobal('distDir', distDir)\n setGlobal('telemetry', telemetry)\n\n Log.info('Analyzing a production build...')\n\n const analyzeContext: AnalyzeContext = {\n config,\n dir,\n distDir,\n noMangling,\n appDirOnly,\n }\n\n const { duration: analyzeDuration, shutdownPromise } =\n await turbopackAnalyze(analyzeContext)\n\n const durationString = durationToString(analyzeDuration)\n const analyzeDir = path.join(distDir, 'diagnostics/analyze')\n\n await shutdownPromise\n\n const routes = await collectRoutesForAnalyze(dir, config, appDirOnly)\n\n await cp(path.join(__dirname, '../../bundle-analyzer'), analyzeDir, {\n recursive: true,\n })\n await mkdir(path.join(analyzeDir, 'data'), { recursive: true })\n await writeFile(\n path.join(analyzeDir, 'data', 'routes.json'),\n JSON.stringify(routes, null, 2)\n )\n\n let logMessage = `Analyze completed in ${durationString}.`\n if (output) {\n logMessage += ` Results written to ${analyzeDir}.\\nTo explore the analyze results interactively, run \\`next experimental-analyze\\` without \\`--output\\`.`\n }\n Log.event(logMessage)\n\n telemetry.record(\n eventAnalyzeCompleted({\n success: true,\n durationInSeconds: Math.round(analyzeDuration),\n totalPageCount: routes.length,\n })\n )\n\n if (!output) {\n await startServer(analyzeDir, port)\n }\n } catch (e) {\n const telemetry = traceGlobals.get('telemetry') as Telemetry | undefined\n if (telemetry) {\n telemetry.record(\n eventAnalyzeCompleted({\n success: false,\n })\n )\n }\n\n throw e\n }\n}\n\n/**\n * Collects all routes from the project for the bundle analyzer.\n * Returns a list of route paths (both static and dynamic).\n */\nasync function collectRoutesForAnalyze(\n dir: string,\n config: NextConfigComplete,\n appDirOnly: boolean\n): Promise<string[]> {\n const { pagesDir, appDir } = findPagesDir(dir)\n\n let appType: RoutesManifest['appType']\n if (pagesDir && appDir) {\n appType = 'hybrid'\n } else if (pagesDir) {\n appType = 'pages'\n } else if (appDir) {\n appType = 'app'\n } else {\n throw new Error('No pages or app directory found.')\n }\n\n const discovery = await discoverRoutes({\n appDir,\n pagesDir,\n pageExtensions: config.pageExtensions,\n isDev: false,\n baseDir: dir,\n isSrcDir: path.relative(dir, pagesDir || appDir || '').startsWith('src'),\n appDirOnly,\n })\n\n const pageKeys = {\n pages: Object.keys(discovery.mappedPages || {}),\n app: discovery.mappedAppPages\n ? Object.keys(discovery.mappedAppPages).map((key) =>\n normalizeAppPath(key)\n )\n : [],\n }\n\n // Load custom routes\n const { redirects, headers, onMatchHeaders, rewrites } =\n await loadCustomRoutes(config)\n\n // Compute restricted redirect paths\n const restrictedRedirectPaths = ['/_next'].map((pathPrefix) =>\n config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix\n )\n\n const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)\n\n // Generate routes manifest\n const { routesManifest } = generateRoutesManifest({\n appType,\n pageKeys,\n config,\n redirects,\n headers,\n onMatchHeaders,\n rewrites,\n restrictedRedirectPaths,\n isAppPPREnabled,\n })\n\n return routesManifest.dynamicRoutes\n .map((r) => r.page)\n .concat(routesManifest.staticRoutes.map((r) => r.page))\n}\n\nfunction startServer(dir: string, port: number): Promise<void> {\n const server = http.createServer((req, res) => {\n return serveHandler(req, res, {\n public: dir,\n })\n })\n\n return new Promise((resolve, reject) => {\n function onError(err: Error) {\n server.close(() => {\n reject(err)\n })\n }\n\n server.on('error', onError)\n\n server.listen(port, 'localhost', () => {\n const address = server.address()\n if (address == null) {\n reject(new Error('Unable to get server address'))\n return\n }\n\n // No longer needed after startup\n server.removeListener('error', onError)\n\n let addressString\n if (typeof address === 'string') {\n addressString = address\n } else if (\n address.family === 'IPv6' &&\n (address.address === '::' || address.address === '::1')\n ) {\n addressString = `localhost:${address.port}`\n } else if (address.family === 'IPv6') {\n addressString = `[${address.address}]:${address.port}`\n } else {\n addressString = `${address.address}:${address.port}`\n }\n\n Log.info(`Bundle analyzer available at http://${addressString}`)\n resolve()\n })\n })\n}\n"],"names":["setGlobal","Log","path","loadConfig","PHASE_ANALYZE","turbopackAnalyze","durationToString","cp","writeFile","mkdir","discoverRoutes","findPagesDir","loadCustomRoutes","generateRoutesManifest","checkIsAppPPREnabled","normalizeAppPath","http","serveHandler","Telemetry","eventAnalyzeCompleted","traceGlobals","Bundler","analyze","dir","reactProductionProfiling","noMangling","appDirOnly","output","port","process","env","TURBOPACK","config","silent","bundler","Turbopack","NEXT_DEPLOYMENT_ID","deploymentId","distDir","join","telemetry","info","analyzeContext","duration","analyzeDuration","shutdownPromise","durationString","analyzeDir","routes","collectRoutesForAnalyze","__dirname","recursive","JSON","stringify","logMessage","event","record","success","durationInSeconds","Math","round","totalPageCount","length","startServer","e","get","pagesDir","appDir","appType","Error","discovery","pageExtensions","isDev","baseDir","isSrcDir","relative","startsWith","pageKeys","pages","Object","keys","mappedPages","app","mappedAppPages","map","key","redirects","headers","onMatchHeaders","rewrites","restrictedRedirectPaths","pathPrefix","basePath","isAppPPREnabled","experimental","ppr","routesManifest","dynamicRoutes","r","page","concat","staticRoutes","server","createServer","req","res","public","Promise","resolve","reject","onError","err","close","on","listen","address","removeListener","addressString","family"],"mappings":"AAGA,SAASA,SAAS,QAAQ,cAAa;AACvC,YAAYC,SAAS,gBAAe;AACpC,YAAYC,UAAU,YAAW;AACjC,OAAOC,gBAAgB,sBAAqB;AAC5C,SAASC,aAAa,QAAQ,6BAA4B;AAC1D,SAASC,gBAAgB,QAA6B,uBAAsB;AAC5E,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,EAAE,EAAEC,SAAS,EAAEC,KAAK,QAAQ,mBAAkB;AACvD,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,KAAK,CAAC;gBACXH,OAAOE;YACT;QACF;QAEAT,OAAOW,EAAE,CAAC,SAASH;QAEnBR,OAAOY,MAAM,CAACtF,MAAM,aAAa;YAC/B,MAAMuF,UAAUb,OAAOa,OAAO;YAC9B,IAAIA,WAAW,MAAM;gBACnBN,OAAO,qBAAyC,CAAzC,IAAIxC,MAAM,iCAAV,qBAAA;2BAAA;gCAAA;kCAAA;gBAAwC;gBAC/C;YACF;YAEA,iCAAiC;YACjCiC,OAAOc,cAAc,CAAC,SAASN;YAE/B,IAAIO;YACJ,IAAI,OAAOF,YAAY,UAAU;gBAC/BE,gBAAgBF;YAClB,OAAO,IACLA,QAAQG,MAAM,KAAK,UAClBH,CAAAA,QAAQA,OAAO,KAAK,QAAQA,QAAQA,OAAO,KAAK,KAAI,GACrD;gBACAE,gBAAgB,CAAC,UAAU,EAAEF,QAAQvF,IAAI,EAAE;YAC7C,OAAO,IAAIuF,QAAQG,MAAM,KAAK,QAAQ;gBACpCD,gBAAgB,CAAC,CAAC,EAAEF,QAAQA,OAAO,CAAC,EAAE,EAAEA,QAAQvF,IAAI,EAAE;YACxD,OAAO;gBACLyF,gBAAgB,GAAGF,QAAQA,OAAO,CAAC,CAAC,EAAEA,QAAQvF,IAAI,EAAE;YACtD;YAEA3B,IAAIwC,IAAI,CAAC,CAAC,oCAAoC,EAAE4E,eAAe;YAC/DT;QACF;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/build/analyze/index.ts"],"sourcesContent":["import type { NextConfigComplete } from '../../server/config-shared'\nimport type { __ApiPreviewProps } from '../../server/api-utils'\n\nimport { setGlobal } from '../../trace'\nimport * as Log from '../output/log'\nimport * as path from 'node:path'\nimport loadConfig from '../../server/config'\nimport { PHASE_ANALYZE } from '../../shared/lib/constants'\nimport { turbopackAnalyze, type AnalyzeContext } from '../turbopack-analyze'\nimport { durationToString } from '../duration-to-string'\nimport { cp, writeFile, mkdir } from 'node:fs/promises'\nimport { discoverRoutes } from '../route-discovery'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport loadCustomRoutes from '../../lib/load-custom-routes'\nimport { generateRoutesManifest } from '../generate-routes-manifest'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport http from 'node:http'\n\n// @ts-expect-error types are in @types/serve-handler\nimport serveHandler from 'next/dist/compiled/serve-handler'\nimport { Telemetry } from '../../telemetry/storage'\nimport { eventAnalyzeCompleted } from '../../telemetry/events'\nimport { traceGlobals } from '../../trace/shared'\nimport type { RoutesManifest } from '..'\nimport { Bundler } from '../../lib/bundler'\n\nexport type AnalyzeOptions = {\n dir: string\n reactProductionProfiling?: boolean\n noMangling?: boolean\n appDirOnly?: boolean\n output?: boolean\n port?: number\n}\n\nexport default async function analyze({\n dir,\n reactProductionProfiling = false,\n noMangling = false,\n appDirOnly = false,\n output = false,\n port = 4000,\n}: AnalyzeOptions): Promise<void> {\n try {\n // analyze is Turbopack-only. Mirror what parseBundlerArgs does for build/dev\n // so every process.env.TURBOPACK consumer in this run agrees with the bundler choice.\n process.env.TURBOPACK ??= '1'\n const config: NextConfigComplete = await loadConfig(PHASE_ANALYZE, dir, {\n silent: false,\n reactProductionProfiling,\n bundler: Bundler.Turbopack,\n })\n\n process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''\n\n const distDir = path.join(dir, '.next')\n const telemetry = new Telemetry({ distDir })\n setGlobal('phase', PHASE_ANALYZE)\n setGlobal('distDir', distDir)\n setGlobal('telemetry', telemetry)\n\n Log.info('Analyzing a production build...')\n\n const analyzeContext: AnalyzeContext = {\n config,\n dir,\n distDir,\n noMangling,\n appDirOnly,\n }\n\n const { duration: analyzeDuration, shutdownPromise } =\n await turbopackAnalyze(analyzeContext)\n\n const durationString = durationToString(analyzeDuration)\n const analyzeDir = path.join(distDir, 'diagnostics/analyze')\n\n await shutdownPromise\n\n const routes = await collectRoutesForAnalyze(dir, config, appDirOnly)\n\n await cp(path.join(__dirname, '../../bundle-analyzer'), analyzeDir, {\n recursive: true,\n })\n await mkdir(path.join(analyzeDir, 'data'), { recursive: true })\n await writeFile(\n path.join(analyzeDir, 'data', 'routes.json'),\n JSON.stringify(routes, null, 2)\n )\n\n let logMessage = `Analyze completed in ${durationString}.`\n if (output) {\n logMessage += ` Results written to ${analyzeDir}.\\nTo explore the analyze results interactively, run \\`next experimental-analyze\\` without \\`--output\\`.`\n }\n Log.event(logMessage)\n\n telemetry.record(\n eventAnalyzeCompleted({\n success: true,\n durationInSeconds: Math.round(analyzeDuration),\n totalPageCount: routes.length,\n })\n )\n\n if (!output) {\n await startServer(analyzeDir, port)\n }\n } catch (e) {\n const telemetry = traceGlobals.get('telemetry') as Telemetry | undefined\n if (telemetry) {\n telemetry.record(\n eventAnalyzeCompleted({\n success: false,\n })\n )\n }\n\n throw e\n }\n}\n\n/**\n * Collects all routes from the project for the bundle analyzer.\n * Returns a list of route paths (both static and dynamic).\n */\nasync function collectRoutesForAnalyze(\n dir: string,\n config: NextConfigComplete,\n appDirOnly: boolean\n): Promise<string[]> {\n const { pagesDir, appDir } = findPagesDir(dir)\n\n let appType: RoutesManifest['appType']\n if (pagesDir && appDir) {\n appType = 'hybrid'\n } else if (pagesDir) {\n appType = 'pages'\n } else if (appDir) {\n appType = 'app'\n } else {\n throw new Error('No pages or app directory found.')\n }\n\n const discovery = await discoverRoutes({\n appDir,\n pagesDir,\n pageExtensions: config.pageExtensions,\n isDev: false,\n baseDir: dir,\n isSrcDir: path.relative(dir, pagesDir || appDir || '').startsWith('src'),\n appDirOnly,\n })\n\n const pageKeys = {\n pages: Object.keys(discovery.mappedPages || {}),\n app: discovery.mappedAppPages\n ? Object.keys(discovery.mappedAppPages).map((key) =>\n normalizeAppPath(key)\n )\n : [],\n }\n\n // Load custom routes\n const { redirects, headers, onMatchHeaders, rewrites } =\n await loadCustomRoutes(config)\n\n // Compute restricted redirect paths\n const restrictedRedirectPaths = ['/_next'].map((pathPrefix) =>\n config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix\n )\n\n const isAppPPREnabled = Boolean(config.cacheComponents)\n\n // Generate routes manifest\n const { routesManifest } = generateRoutesManifest({\n appType,\n pageKeys,\n config,\n redirects,\n headers,\n onMatchHeaders,\n rewrites,\n restrictedRedirectPaths,\n isAppPPREnabled,\n })\n\n return routesManifest.dynamicRoutes\n .map((r) => r.page)\n .concat(routesManifest.staticRoutes.map((r) => r.page))\n}\n\nfunction startServer(dir: string, port: number): Promise<void> {\n const server = http.createServer((req, res) => {\n return serveHandler(req, res, {\n public: dir,\n })\n })\n\n return new Promise((resolve, reject) => {\n function onError(err: Error) {\n server.close(() => {\n reject(err)\n })\n }\n\n server.on('error', onError)\n\n server.listen(port, 'localhost', () => {\n const address = server.address()\n if (address == null) {\n reject(new Error('Unable to get server address'))\n return\n }\n\n // No longer needed after startup\n server.removeListener('error', onError)\n\n let addressString\n if (typeof address === 'string') {\n addressString = address\n } else if (\n address.family === 'IPv6' &&\n (address.address === '::' || address.address === '::1')\n ) {\n addressString = `localhost:${address.port}`\n } else if (address.family === 'IPv6') {\n addressString = `[${address.address}]:${address.port}`\n } else {\n addressString = `${address.address}:${address.port}`\n }\n\n Log.info(`Bundle analyzer available at http://${addressString}`)\n resolve()\n })\n })\n}\n"],"names":["setGlobal","Log","path","loadConfig","PHASE_ANALYZE","turbopackAnalyze","durationToString","cp","writeFile","mkdir","discoverRoutes","findPagesDir","loadCustomRoutes","generateRoutesManifest","normalizeAppPath","http","serveHandler","Telemetry","eventAnalyzeCompleted","traceGlobals","Bundler","analyze","dir","reactProductionProfiling","noMangling","appDirOnly","output","port","process","env","TURBOPACK","config","silent","bundler","Turbopack","NEXT_DEPLOYMENT_ID","deploymentId","distDir","join","telemetry","info","analyzeContext","duration","analyzeDuration","shutdownPromise","durationString","analyzeDir","routes","collectRoutesForAnalyze","__dirname","recursive","JSON","stringify","logMessage","event","record","success","durationInSeconds","Math","round","totalPageCount","length","startServer","e","get","pagesDir","appDir","appType","Error","discovery","pageExtensions","isDev","baseDir","isSrcDir","relative","startsWith","pageKeys","pages","Object","keys","mappedPages","app","mappedAppPages","map","key","redirects","headers","onMatchHeaders","rewrites","restrictedRedirectPaths","pathPrefix","basePath","isAppPPREnabled","Boolean","cacheComponents","routesManifest","dynamicRoutes","r","page","concat","staticRoutes","server","createServer","req","res","public","Promise","resolve","reject","onError","err","close","on","listen","address","removeListener","addressString","family"],"mappings":"AAGA,SAASA,SAAS,QAAQ,cAAa;AACvC,YAAYC,SAAS,gBAAe;AACpC,YAAYC,UAAU,YAAW;AACjC,OAAOC,gBAAgB,sBAAqB;AAC5C,SAASC,aAAa,QAAQ,6BAA4B;AAC1D,SAASC,gBAAgB,QAA6B,uBAAsB;AAC5E,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,EAAE,EAAEC,SAAS,EAAEC,KAAK,QAAQ,mBAAkB;AACvD,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,YAAY,QAAQ,2BAA0B;AACvD,OAAOC,sBAAsB,+BAA8B;AAC3D,SAASC,sBAAsB,QAAQ,8BAA6B;AACpE,SAASC,gBAAgB,QAAQ,0CAAyC;AAC1E,OAAOC,UAAU,YAAW;AAE5B,qDAAqD;AACrD,OAAOC,kBAAkB,mCAAkC;AAC3D,SAASC,SAAS,QAAQ,0BAAyB;AACnD,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,YAAY,QAAQ,qBAAoB;AAEjD,SAASC,OAAO,QAAQ,oBAAmB;AAW3C,eAAe,eAAeC,QAAQ,EACpCC,GAAG,EACHC,2BAA2B,KAAK,EAChCC,aAAa,KAAK,EAClBC,aAAa,KAAK,EAClBC,SAAS,KAAK,EACdC,OAAO,IAAI,EACI;IACf,IAAI;QACF,6EAA6E;QAC7E,sFAAsF;QACtFC,QAAQC,GAAG,CAACC,SAAS,KAAK;QAC1B,MAAMC,SAA6B,MAAM5B,WAAWC,eAAekB,KAAK;YACtEU,QAAQ;YACRT;YACAU,SAASb,QAAQc,SAAS;QAC5B;QAEAN,QAA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QvF,IAAI,EAAE;YACtD;YAEA1B,IAAIuC,IAAI,CAAC,CAAC,oCAAoC,EAAE4E,eAAe;YAC/DT;QACF;IACF;AACF","ignoreList":[0]}
import path from 'node:path';
import { needsExperimentalReact } from '../lib/needs-experimental-react';
import { checkIsAppPPREnabled } from '../server/lib/experimental/ppr';
import { getNextConfigEnv, getNextPublicEnvironmentVariables } from '../lib/static-env';

@@ -40,3 +39,2 @@ const DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION');

const nextConfigEnv = getNextConfigEnv(config);
const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr);
const isCacheComponentsEnabled = !!config.cacheComponents;

@@ -70,3 +68,2 @@ const isUseCacheEnabled = !!config.experimental.useCache;

'process.env.__NEXT_TURBOPACK_SHARED_RUNTIME': config.experimental.turbopackSharedRuntime !== false,
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,

@@ -73,0 +70,0 @@ 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(config.experimental.cachedNavigations),

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/build/define-env.ts"],"sourcesContent":["import type {\n I18NConfig,\n I18NDomains,\n NextConfigComplete,\n} from '../server/config-shared'\nimport type { ProxyMatcher } from './analysis/get-page-static-info'\nimport type { Rewrite } from '../lib/load-custom-routes'\nimport path from 'node:path'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'\nimport {\n getNextConfigEnv,\n getNextPublicEnvironmentVariables,\n} from '../lib/static-env'\n\ntype BloomFilter = ReturnType<\n import('../shared/lib/bloom-filter').BloomFilter['export']\n>\n\nexport interface DefineEnvOptions {\n isTurbopack: boolean\n clientRouterFilters?: {\n staticFilter: BloomFilter\n dynamicFilter: BloomFilter\n }\n config: NextConfigComplete\n dev: boolean\n distDir: string\n projectPath: string\n fetchCacheKeyPrefix: string | undefined\n hasRewrites: boolean\n isClient: boolean\n isEdgeServer: boolean\n isNodeServer: boolean\n middlewareMatchers: ProxyMatcher[] | undefined\n omitNonDeterministic?: boolean\n rewrites: {\n beforeFiles: Rewrite[]\n afterFiles: Rewrite[]\n fallback: Rewrite[]\n }\n}\n\nconst DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION')\n\ninterface DefineEnv {\n [key: string]:\n | string\n | number\n | string[]\n | boolean\n | { [DEFINE_ENV_EXPRESSION]: string }\n | ProxyMatcher[]\n | BloomFilter\n | Partial<NextConfigComplete['images']>\n | NextConfigComplete['cacheLife']\n | I18NDomains\n | I18NConfig\n}\n\ninterface SerializedDefineEnv {\n [key: string]: string\n}\n\n/**\n * Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.\n */\nfunction serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {\n const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(\n Object.entries(defineEnv).map(([key, value]) => [\n key,\n typeof value === 'object' && DEFINE_ENV_EXPRESSION in value\n ? value[DEFINE_ENV_EXPRESSION]\n : JSON.stringify(value),\n ])\n )\n return defineEnvStringified\n}\n\nfunction getImageConfig(\n config: NextConfigComplete,\n dev: boolean\n): { 'process.env.__NEXT_IMAGE_OPTS': Partial<NextConfigComplete['images']> } {\n return {\n 'process.env.__NEXT_IMAGE_OPTS': {\n deviceSizes: config.images.deviceSizes,\n imageSizes: config.images.imageSizes,\n qualities: config.images.qualities,\n path: config.images.path,\n loader: config.images.loader,\n dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,\n unoptimized: config?.images?.unoptimized,\n ...(dev\n ? {\n // additional config in dev to allow validating on the client\n domains: config.images.domains,\n remotePatterns: config.images?.remotePatterns,\n localPatterns: config.images?.localPatterns,\n output: config.output,\n }\n : {}),\n },\n }\n}\n\nexport function getDefineEnv({\n isTurbopack,\n clientRouterFilters,\n config,\n dev,\n distDir,\n projectPath,\n fetchCacheKeyPrefix,\n hasRewrites,\n isClient,\n isEdgeServer,\n isNodeServer,\n middlewareMatchers,\n omitNonDeterministic,\n rewrites,\n}: DefineEnvOptions): SerializedDefineEnv {\n const nextPublicEnv = getNextPublicEnvironmentVariables()\n const nextConfigEnv = getNextConfigEnv(config)\n\n const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)\n const isCacheComponentsEnabled = !!config.cacheComponents\n const isUseCacheEnabled = !!config.experimental.useCache\n\n const defineEnv: DefineEnv = {\n // internal field to identify the plugin config\n __NEXT_DEFINE_ENV: true,\n\n ...nextPublicEnv,\n ...nextConfigEnv,\n ...(!isEdgeServer\n ? {}\n : {\n EdgeRuntime:\n /**\n * Cloud providers can set this environment variable to allow users\n * and library authors to have different implementations based on\n * the runtime they are running with, if it's not using `edge-runtime`\n */\n process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? 'edge-runtime',\n\n // process should be only { env: {...} } for edge runtime.\n // For ignore avoid warn on `process.emit` usage but directly omit it.\n 'process.emit': false,\n }),\n 'process.turbopack': isTurbopack,\n 'process.env.TURBOPACK': isTurbopack,\n 'process.env.__NEXT_BUNDLER': isTurbopack\n ? 'Turbopack'\n : process.env.NEXT_RSPACK\n ? 'Rspack'\n : 'Webpack',\n // TODO: enforce `NODE_ENV` on `process.env`, and add a test:\n 'process.env.NODE_ENV':\n dev || config.experimental.allowDevelopmentBuild\n ? 'development'\n : 'production',\n 'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',\n 'process.env.__NEXT_DISABLE_DEV_OVERLAY_UX':\n process.env.NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX === '1',\n 'process.env.NEXT_RUNTIME': isEdgeServer\n ? 'edge'\n : isNodeServer\n ? 'nodejs'\n : '',\n 'process.env.NEXT_MINIMAL': '',\n 'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(\n config.experimental.appNavFailHandling\n ),\n 'process.env.__NEXT_TURBOPACK_SHARED_RUNTIME':\n config.experimental.turbopackSharedRuntime !== false,\n 'process.env.__NEXT_PPR': isPPREnabled,\n 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(\n config.experimental.cachedNavigations\n ),\n 'process.env.__NEXT_INSTANT_NAV_TOGGLE': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_COLD_CACHE_BADGE': Boolean(\n config.experimental.coldCacheBadge\n ),\n 'process.env.__NEXT_REQUEST_INSIGHTS':\n dev && !!config.experimental.requestInsights,\n 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,\n 'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true,\n\n 'process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS':\n config.supportsImmutableAssets || false,\n\n ...(config.experimental?.useSkewCookie || !config.deploymentId\n ? {\n 'process.env.NEXT_DEPLOYMENT_ID': false,\n }\n : isClient\n ? isTurbopack\n ? {\n // This is set at runtime by packages/next/src/client/register-deployment-id-global.ts\n 'process.env.NEXT_DEPLOYMENT_ID': {\n [DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID',\n },\n }\n : {\n // For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID\n // approach because we cannot forward this global variable to web workers easily.\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }\n : config.experimental?.runtimeServerDeploymentId\n ? {\n // Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is\n }\n : {\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }),\n\n // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment\n // variable to the client.\n 'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':\n process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING || false,\n 'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',\n ...(isTurbopack\n ? {}\n : {\n 'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],\n }),\n 'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH':\n config.experimental.manualClientBasePath ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.dynamic))\n ? 0\n : config.experimental.staleTimes?.dynamic\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.static))\n ? 5 * 60 // 5 minutes\n : config.experimental.staleTimes?.static\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':\n config.experimental.clientRouterFilter ?? true,\n 'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':\n clientRouterFilters?.staticFilter ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_D_FILTER':\n clientRouterFilters?.dynamicFilter ?? false,\n 'process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS': Boolean(\n config.experimental.validateRSCRequestHeaders\n ),\n 'process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION': Boolean(\n config.experimental.serverComponentsHmrCancellation\n ),\n 'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(\n config.experimental.dynamicOnHover\n ),\n 'process.env.__NEXT_USE_OFFLINE': Boolean(config.experimental.useOffline),\n 'process.env.__NEXT_PREFETCH_INLINING': Boolean(\n config.experimental.prefetchInlining\n ),\n 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':\n config.experimental.optimisticClientCache ?? true,\n 'process.env.__NEXT_MIDDLEWARE_PREFETCH':\n config.experimental.proxyPrefetch ?? 'flexible',\n 'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,\n 'process.browser': isClient,\n 'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,\n // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory\n ...(dev && (isClient ?? isEdgeServer)\n ? {\n 'process.env.__NEXT_DIST_DIR': distDir,\n }\n : {}),\n // This is used in devtools to strip the project path in edge runtime,\n // as there's only a dummy `dir` value (`.`) as edge runtime doesn't have concept of file system.\n ...(dev && isEdgeServer\n ? {\n 'process.env.__NEXT_EDGE_PROJECT_DIR': isTurbopack\n ? path.relative(process.cwd(), projectPath)\n : projectPath,\n }\n : {}),\n 'process.env.__NEXT_BASE_PATH': config.basePath,\n 'process.env.__NEXT_CASE_SENSITIVE_ROUTES': Boolean(\n config.experimental.caseSensitiveRoutes\n ),\n 'process.env.__NEXT_REWRITES': rewrites as any,\n 'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,\n 'process.env.__NEXT_DEV_INDICATOR': config.devIndicators !== false,\n 'process.env.__NEXT_DEV_INDICATOR_POSITION':\n config.devIndicators === false\n ? 'bottom-left' // This will not be used as the indicator is disabled.\n : (config.devIndicators.position ?? 'bottom-left'),\n 'process.env.__NEXT_STRICT_MODE':\n config.reactStrictMode === null ? false : config.reactStrictMode,\n 'process.env.__NEXT_STRICT_MODE_APP':\n // When next.config.js does not have reactStrictMode it's enabled by default.\n config.reactStrictMode === null ? true : config.reactStrictMode,\n 'process.env.__NEXT_OPTIMIZE_CSS':\n (config.experimental.optimizeCss && !dev) ?? false,\n 'process.env.__NEXT_SCRIPT_WORKERS':\n (config.experimental.nextScriptWorkers && !dev) ?? false,\n 'process.env.__NEXT_SCROLL_RESTORATION':\n config.experimental.scrollRestoration ?? false,\n ...getImageConfig(config, dev),\n 'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,\n 'process.env.__NEXT_HAS_REWRITES': hasRewrites,\n 'process.env.__NEXT_CONFIG_OUTPUT': config.output || '',\n 'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,\n 'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,\n 'process.env.__NEXT_I18N_CONFIG': config.i18n || '',\n 'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':\n config.skipProxyUrlNormalize,\n 'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':\n config.experimental.externalProxyRewritesResolve ?? false,\n 'process.env.__NEXT_MANUAL_TRAILING_SLASH':\n config.skipTrailingSlashRedirect,\n 'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':\n (config.experimental.webVitalsAttribution &&\n config.experimental.webVitalsAttribution.length > 0) ??\n false,\n 'process.env.__NEXT_WEB_VITALS_ATTRIBUTION':\n config.experimental.webVitalsAttribution ?? false,\n 'process.env.__NEXT_LINK_NO_TOUCH_START':\n config.experimental.linkNoTouchStart ?? false,\n 'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,\n 'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':\n !!config.experimental.authInterrupts,\n 'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(\n process.env.NEXT_TELEMETRY_DISABLED\n ),\n ...(isNodeServer || isEdgeServer\n ? {\n // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)\n // This is typically found in unmaintained modules from the\n // pre-webpack era (common in server-side code)\n 'global.GENTLY': false,\n }\n : undefined),\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_EXPERIMENTAL_REACT':\n needsExperimentalReact(config),\n }\n : undefined),\n\n 'process.env.__NEXT_MULTI_ZONE_DRAFT_MODE':\n config.experimental.multiZoneDraftMode ?? false,\n 'process.env.__NEXT_TRUST_HOST_HEADER':\n config.experimental.trustHostHeader ?? false,\n 'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':\n config.experimental.allowedRevalidateHeaderKeys ?? [],\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,\n 'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(\n process.cwd(),\n projectPath\n ),\n }\n : {}),\n\n 'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(\n (config.logging && config.logging.browserToTerminal) || false\n ),\n 'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,\n\n // The devtools need to know whether or not to show an option to clear the\n // bundler cache. This option may be removed later once Turbopack's\n // filesystem cache feature is more stable.\n //\n // This environment value is currently best-effort:\n // - It's possible to disable the webpack filesystem cache, but it's\n // unlikely for a user to do that.\n // - Rspack's filesystem cache is unstable and requires a different\n // configuration than webpack to enable (which we don't do).\n //\n // In the worst case we'll show an option to clear the cache, but it'll be a\n // no-op that just restarts the development server.\n 'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE':\n !isTurbopack ||\n (config.experimental.turbopackFileSystemCacheForDev ?? false),\n 'process.env.__NEXT_REACT_DEBUG_CHANNEL':\n config.experimental.reactDebugChannel ?? false,\n 'process.env.__NEXT_TRANSITION_INDICATOR':\n config.experimental.transitionIndicator ?? false,\n 'process.env.__NEXT_GESTURE_TRANSITION':\n config.experimental.gestureTransition ?? false,\n 'process.env.__NEXT_OPTIMISTIC_ROUTING':\n config.experimental.optimisticRouting ?? false,\n 'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':\n config.experimental.instrumentationClientRouterTransitionEvents ?? false,\n 'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,\n 'process.env.__NEXT_EXPOSE_TESTING_API':\n isCacheComponentsEnabled &&\n (dev || config.experimental.exposeTestingApiInProductionBuild === true),\n 'process.env.__NEXT_CACHE_LIFE': config.cacheLife,\n 'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':\n config.experimental.clientParamParsingOrigins || [],\n }\n\n const userDefines = config.compiler?.define ?? {}\n for (const key in userDefines) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.define\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefines[key]\n }\n\n if (isNodeServer || isEdgeServer) {\n const userDefinesServer = config.compiler?.defineServer ?? {}\n for (const key in userDefinesServer) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.defineServer\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefinesServer[key]\n }\n }\n\n const serializedDefineEnv = serializeDefineEnv(defineEnv)\n\n // we delay inlining these values until after the build\n // with flying shuttle enabled so we can update them\n // without invalidating entries\n if (!dev && omitNonDeterministic) {\n // client uses window. instead of leaving process.env\n // in case process isn't polyfilled on client already\n // since by this point it won't be added by webpack\n const safeKey = (key: string) =>\n isClient ? `window.${key.split('.').pop()}` : key\n\n for (const key in nextPublicEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n for (const key in nextConfigEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n if (!config.experimental.runtimeServerDeploymentId) {\n for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {\n serializedDefineEnv[key] = safeKey(key)\n }\n }\n }\n\n return serializedDefineEnv\n}\n"],"names":["path","needsExperimentalReact","checkIsAppPPREnabled","getNextConfigEnv","getNextPublicEnvironmentVariables","DEFINE_ENV_EXPRESSION","Symbol","serializeDefineEnv","defineEnv","defineEnvStringified","Object","fromEntries","entries","map","key","value","JSON","stringify","getImageConfig","config","dev","deviceSizes","images","imageSizes","qualities","loader","dangerouslyAllowSVG","unoptimized","domains","remotePatterns","localPatterns","output","getDefineEnv","isTurbopack","clientRouterFilters","distDir","projectPath","fetchCacheKeyPrefix","hasRewrites","isClient","isEdgeServer","isNodeServer","middlewareMatchers","omitNonDeterministic","rewrites","nextPublicEnv","nextConfigEnv","isPPREnabled","experimental","ppr","isCacheComponentsEnabled","cacheComponents","isUseCacheEnabled","useCache","__NEXT_DEFINE_ENV","EdgeRuntime","process","env","NEXT_EDGE_RUNTIME_PROVIDER","NEXT_RSPACK","allowDevelopmentBuild","NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX","Boolean","appNavFailHandling","turbopackSharedRuntime","cachedNavigations","coldCacheBadge","requestInsights","supportsImmutableAssets","useSkewCookie","deploymentId","runtimeServerDeploymentId","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","manualClientBasePath","isNaN","Number","staleTimes","dynamic","static","clientRouterFilter","staticFilter","dynamicFilter","validateRSCRequestHeaders","serverComponentsHmrCancellation","dynamicOnHover","useOffline","prefetchInlining","optimisticClientCache","proxyPrefetch","crossOrigin","__NEXT_TEST_MODE","relative","cwd","basePath","caseSensitiveRoutes","trailingSlash","devIndicators","position","reactStrictMode","optimizeCss","nextScriptWorkers","scrollRestoration","i18n","skipProxyUrlNormalize","externalProxyRewritesResolve","skipTrailingSlashRedirect","webVitalsAttribution","length","linkNoTouchStart","assetPrefix","authInterrupts","NEXT_TELEMETRY_DISABLED","undefined","multiZoneDraftMode","trustHostHeader","allowedRevalidateHeaderKeys","logging","browserToTerminal","mcpServer","turbopackFileSystemCacheForDev","reactDebugChannel","transitionIndicator","gestureTransition","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","exposeTestingApiInProductionBuild","cacheLife","clientParamParsingOrigins","userDefines","compiler","define","hasOwnProperty","Error","userDefinesServer","defineServer","serializedDefineEnv","safeKey","split","pop"],"mappings":"AAOA,OAAOA,UAAU,YAAW;AAC5B,SAASC,sBAAsB,QAAQ,kCAAiC;AACxE,SAASC,oBAAoB,QAAQ,iCAAgC;AACrE,SACEC,gBAAgB,EAChBC,iCAAiC,QAC5B,oBAAmB;AA8B1B,MAAMC,wBAAwBC,OAAO;AAqBrC;;CAEC,GACD,SAASC,mBAAmBC,SAAoB;IAC9C,MAAMC,uBAA4CC,OAAOC,WAAW,CAClED,OAAOE,OAAO,CAACJ,WAAWK,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAC9CD;YACA,OAAOC,UAAU,YAAYV,yBAAyBU,QAClDA,KAAK,CAACV,sBAAsB,GAC5BW,KAAKC,SA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G,kBAAiBoH,YAAY,KAAI,CAAC;QAC5D,IAAK,MAAMzH,OAAOwH,kBAAmB;YACnC,IAAI9H,UAAU4H,cAAc,CAACtH,MAAM;gBACjC,MAAM,qBAEL,CAFK,IAAIuH,MACR,CAAC,oEAAoE,EAAEvH,IAAI,yFAAyF,CAAC,GADjK,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF;YACAN,SAAS,CAACM,IAAI,GAAGwH,iBAAiB,CAACxH,IAAI;QACzC;IACF;IAEA,MAAM0H,sBAAsBjI,mBAAmBC;IAE/C,uDAAuD;IACvD,oDAAoD;IACpD,+BAA+B;IAC/B,IAAI,CAACY,OAAOuB,sBAAsB;QAChC,qDAAqD;QACrD,qDAAqD;QACrD,mDAAmD;QACnD,MAAM8F,UAAU,CAAC3H,MACfyB,WAAW,CAAC,OAAO,EAAEzB,IAAI4H,KAAK,CAAC,KAAKC,GAAG,IAAI,GAAG7H;QAEhD,IAAK,MAAMA,OAAO+B,cAAe;YAC/B2F,mBAAmB,CAAC1H,IAAI,GAAG2H,QAAQ3H;QACrC;QACA,IAAK,MAAMA,OAAOgC,cAAe;YAC/B0F,mBAAmB,CAAC1H,IAAI,GAAG2H,QAAQ3H;QACrC;QACA,IAAI,CAACK,OAAO6B,YAAY,CAACuB,yBAAyB,EAAE;YAClD,KAAK,MAAMzD,OAAO;gBAAC;aAAiC,CAAE;gBACpD0H,mBAAmB,CAAC1H,IAAI,GAAG2H,QAAQ3H;YACrC;QACF;IACF;IAEA,OAAO0H;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../src/build/define-env.ts"],"sourcesContent":["import type {\n I18NConfig,\n I18NDomains,\n NextConfigComplete,\n} from '../server/config-shared'\nimport type { ProxyMatcher } from './analysis/get-page-static-info'\nimport type { Rewrite } from '../lib/load-custom-routes'\nimport path from 'node:path'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport {\n getNextConfigEnv,\n getNextPublicEnvironmentVariables,\n} from '../lib/static-env'\n\ntype BloomFilter = ReturnType<\n import('../shared/lib/bloom-filter').BloomFilter['export']\n>\n\nexport interface DefineEnvOptions {\n isTurbopack: boolean\n clientRouterFilters?: {\n staticFilter: BloomFilter\n dynamicFilter: BloomFilter\n }\n config: NextConfigComplete\n dev: boolean\n distDir: string\n projectPath: string\n fetchCacheKeyPrefix: string | undefined\n hasRewrites: boolean\n isClient: boolean\n isEdgeServer: boolean\n isNodeServer: boolean\n middlewareMatchers: ProxyMatcher[] | undefined\n omitNonDeterministic?: boolean\n rewrites: {\n beforeFiles: Rewrite[]\n afterFiles: Rewrite[]\n fallback: Rewrite[]\n }\n}\n\nconst DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION')\n\ninterface DefineEnv {\n [key: string]:\n | string\n | number\n | string[]\n | boolean\n | { [DEFINE_ENV_EXPRESSION]: string }\n | ProxyMatcher[]\n | BloomFilter\n | Partial<NextConfigComplete['images']>\n | NextConfigComplete['cacheLife']\n | I18NDomains\n | I18NConfig\n}\n\ninterface SerializedDefineEnv {\n [key: string]: string\n}\n\n/**\n * Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.\n */\nfunction serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {\n const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(\n Object.entries(defineEnv).map(([key, value]) => [\n key,\n typeof value === 'object' && DEFINE_ENV_EXPRESSION in value\n ? value[DEFINE_ENV_EXPRESSION]\n : JSON.stringify(value),\n ])\n )\n return defineEnvStringified\n}\n\nfunction getImageConfig(\n config: NextConfigComplete,\n dev: boolean\n): { 'process.env.__NEXT_IMAGE_OPTS': Partial<NextConfigComplete['images']> } {\n return {\n 'process.env.__NEXT_IMAGE_OPTS': {\n deviceSizes: config.images.deviceSizes,\n imageSizes: config.images.imageSizes,\n qualities: config.images.qualities,\n path: config.images.path,\n loader: config.images.loader,\n dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,\n unoptimized: config?.images?.unoptimized,\n ...(dev\n ? {\n // additional config in dev to allow validating on the client\n domains: config.images.domains,\n remotePatterns: config.images?.remotePatterns,\n localPatterns: config.images?.localPatterns,\n output: config.output,\n }\n : {}),\n },\n }\n}\n\nexport function getDefineEnv({\n isTurbopack,\n clientRouterFilters,\n config,\n dev,\n distDir,\n projectPath,\n fetchCacheKeyPrefix,\n hasRewrites,\n isClient,\n isEdgeServer,\n isNodeServer,\n middlewareMatchers,\n omitNonDeterministic,\n rewrites,\n}: DefineEnvOptions): SerializedDefineEnv {\n const nextPublicEnv = getNextPublicEnvironmentVariables()\n const nextConfigEnv = getNextConfigEnv(config)\n\n const isCacheComponentsEnabled = !!config.cacheComponents\n const isUseCacheEnabled = !!config.experimental.useCache\n\n const defineEnv: DefineEnv = {\n // internal field to identify the plugin config\n __NEXT_DEFINE_ENV: true,\n\n ...nextPublicEnv,\n ...nextConfigEnv,\n ...(!isEdgeServer\n ? {}\n : {\n EdgeRuntime:\n /**\n * Cloud providers can set this environment variable to allow users\n * and library authors to have different implementations based on\n * the runtime they are running with, if it's not using `edge-runtime`\n */\n process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? 'edge-runtime',\n\n // process should be only { env: {...} } for edge runtime.\n // For ignore avoid warn on `process.emit` usage but directly omit it.\n 'process.emit': false,\n }),\n 'process.turbopack': isTurbopack,\n 'process.env.TURBOPACK': isTurbopack,\n 'process.env.__NEXT_BUNDLER': isTurbopack\n ? 'Turbopack'\n : process.env.NEXT_RSPACK\n ? 'Rspack'\n : 'Webpack',\n // TODO: enforce `NODE_ENV` on `process.env`, and add a test:\n 'process.env.NODE_ENV':\n dev || config.experimental.allowDevelopmentBuild\n ? 'development'\n : 'production',\n 'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',\n 'process.env.__NEXT_DISABLE_DEV_OVERLAY_UX':\n process.env.NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX === '1',\n 'process.env.NEXT_RUNTIME': isEdgeServer\n ? 'edge'\n : isNodeServer\n ? 'nodejs'\n : '',\n 'process.env.NEXT_MINIMAL': '',\n 'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(\n config.experimental.appNavFailHandling\n ),\n 'process.env.__NEXT_TURBOPACK_SHARED_RUNTIME':\n config.experimental.turbopackSharedRuntime !== false,\n 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS': Boolean(\n config.experimental.cachedNavigations\n ),\n 'process.env.__NEXT_INSTANT_NAV_TOGGLE': isCacheComponentsEnabled,\n 'process.env.__NEXT_EXPERIMENTAL_COLD_CACHE_BADGE': Boolean(\n config.experimental.coldCacheBadge\n ),\n 'process.env.__NEXT_REQUEST_INSIGHTS':\n dev && !!config.experimental.requestInsights,\n 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,\n 'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true,\n\n 'process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS':\n config.supportsImmutableAssets || false,\n\n ...(config.experimental?.useSkewCookie || !config.deploymentId\n ? {\n 'process.env.NEXT_DEPLOYMENT_ID': false,\n }\n : isClient\n ? isTurbopack\n ? {\n // This is set at runtime by packages/next/src/client/register-deployment-id-global.ts\n 'process.env.NEXT_DEPLOYMENT_ID': {\n [DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID',\n },\n }\n : {\n // For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID\n // approach because we cannot forward this global variable to web workers easily.\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }\n : config.experimental?.runtimeServerDeploymentId\n ? {\n // Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is\n }\n : {\n 'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,\n }),\n\n // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment\n // variable to the client.\n 'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':\n process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING || false,\n 'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',\n ...(isTurbopack\n ? {}\n : {\n 'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],\n }),\n 'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH':\n config.experimental.manualClientBasePath ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.dynamic))\n ? 0\n : config.experimental.staleTimes?.dynamic\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME': JSON.stringify(\n isNaN(Number(config.experimental.staleTimes?.static))\n ? 5 * 60 // 5 minutes\n : config.experimental.staleTimes?.static\n ),\n 'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':\n config.experimental.clientRouterFilter ?? true,\n 'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':\n clientRouterFilters?.staticFilter ?? false,\n 'process.env.__NEXT_CLIENT_ROUTER_D_FILTER':\n clientRouterFilters?.dynamicFilter ?? false,\n 'process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS': Boolean(\n config.experimental.validateRSCRequestHeaders\n ),\n 'process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION': Boolean(\n config.experimental.serverComponentsHmrCancellation\n ),\n 'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(\n config.experimental.dynamicOnHover\n ),\n 'process.env.__NEXT_USE_OFFLINE': Boolean(config.experimental.useOffline),\n 'process.env.__NEXT_PREFETCH_INLINING': Boolean(\n config.experimental.prefetchInlining\n ),\n 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':\n config.experimental.optimisticClientCache ?? true,\n 'process.env.__NEXT_MIDDLEWARE_PREFETCH':\n config.experimental.proxyPrefetch ?? 'flexible',\n 'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,\n 'process.browser': isClient,\n 'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,\n // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory\n ...(dev && (isClient ?? isEdgeServer)\n ? {\n 'process.env.__NEXT_DIST_DIR': distDir,\n }\n : {}),\n // This is used in devtools to strip the project path in edge runtime,\n // as there's only a dummy `dir` value (`.`) as edge runtime doesn't have concept of file system.\n ...(dev && isEdgeServer\n ? {\n 'process.env.__NEXT_EDGE_PROJECT_DIR': isTurbopack\n ? path.relative(process.cwd(), projectPath)\n : projectPath,\n }\n : {}),\n 'process.env.__NEXT_BASE_PATH': config.basePath,\n 'process.env.__NEXT_CASE_SENSITIVE_ROUTES': Boolean(\n config.experimental.caseSensitiveRoutes\n ),\n 'process.env.__NEXT_REWRITES': rewrites as any,\n 'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,\n 'process.env.__NEXT_DEV_INDICATOR': config.devIndicators !== false,\n 'process.env.__NEXT_DEV_INDICATOR_POSITION':\n config.devIndicators === false\n ? 'bottom-left' // This will not be used as the indicator is disabled.\n : (config.devIndicators.position ?? 'bottom-left'),\n 'process.env.__NEXT_STRICT_MODE':\n config.reactStrictMode === null ? false : config.reactStrictMode,\n 'process.env.__NEXT_STRICT_MODE_APP':\n // When next.config.js does not have reactStrictMode it's enabled by default.\n config.reactStrictMode === null ? true : config.reactStrictMode,\n 'process.env.__NEXT_OPTIMIZE_CSS':\n (config.experimental.optimizeCss && !dev) ?? false,\n 'process.env.__NEXT_SCRIPT_WORKERS':\n (config.experimental.nextScriptWorkers && !dev) ?? false,\n 'process.env.__NEXT_SCROLL_RESTORATION':\n config.experimental.scrollRestoration ?? false,\n ...getImageConfig(config, dev),\n 'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,\n 'process.env.__NEXT_HAS_REWRITES': hasRewrites,\n 'process.env.__NEXT_CONFIG_OUTPUT': config.output || '',\n 'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,\n 'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,\n 'process.env.__NEXT_I18N_CONFIG': config.i18n || '',\n 'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':\n config.skipProxyUrlNormalize,\n 'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':\n config.experimental.externalProxyRewritesResolve ?? false,\n 'process.env.__NEXT_MANUAL_TRAILING_SLASH':\n config.skipTrailingSlashRedirect,\n 'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':\n (config.experimental.webVitalsAttribution &&\n config.experimental.webVitalsAttribution.length > 0) ??\n false,\n 'process.env.__NEXT_WEB_VITALS_ATTRIBUTION':\n config.experimental.webVitalsAttribution ?? false,\n 'process.env.__NEXT_LINK_NO_TOUCH_START':\n config.experimental.linkNoTouchStart ?? false,\n 'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,\n 'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':\n !!config.experimental.authInterrupts,\n 'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(\n process.env.NEXT_TELEMETRY_DISABLED\n ),\n ...(isNodeServer || isEdgeServer\n ? {\n // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)\n // This is typically found in unmaintained modules from the\n // pre-webpack era (common in server-side code)\n 'global.GENTLY': false,\n }\n : undefined),\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_EXPERIMENTAL_REACT':\n needsExperimentalReact(config),\n }\n : undefined),\n\n 'process.env.__NEXT_MULTI_ZONE_DRAFT_MODE':\n config.experimental.multiZoneDraftMode ?? false,\n 'process.env.__NEXT_TRUST_HOST_HEADER':\n config.experimental.trustHostHeader ?? false,\n 'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':\n config.experimental.allowedRevalidateHeaderKeys ?? [],\n ...(isNodeServer || isEdgeServer\n ? {\n 'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,\n 'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(\n process.cwd(),\n projectPath\n ),\n }\n : {}),\n\n 'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(\n (config.logging && config.logging.browserToTerminal) || false\n ),\n 'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,\n\n // The devtools need to know whether or not to show an option to clear the\n // bundler cache. This option may be removed later once Turbopack's\n // filesystem cache feature is more stable.\n //\n // This environment value is currently best-effort:\n // - It's possible to disable the webpack filesystem cache, but it's\n // unlikely for a user to do that.\n // - Rspack's filesystem cache is unstable and requires a different\n // configuration than webpack to enable (which we don't do).\n //\n // In the worst case we'll show an option to clear the cache, but it'll be a\n // no-op that just restarts the development server.\n 'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE':\n !isTurbopack ||\n (config.experimental.turbopackFileSystemCacheForDev ?? false),\n 'process.env.__NEXT_REACT_DEBUG_CHANNEL':\n config.experimental.reactDebugChannel ?? false,\n 'process.env.__NEXT_TRANSITION_INDICATOR':\n config.experimental.transitionIndicator ?? false,\n 'process.env.__NEXT_GESTURE_TRANSITION':\n config.experimental.gestureTransition ?? false,\n 'process.env.__NEXT_OPTIMISTIC_ROUTING':\n config.experimental.optimisticRouting ?? false,\n 'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':\n config.experimental.instrumentationClientRouterTransitionEvents ?? false,\n 'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,\n 'process.env.__NEXT_EXPOSE_TESTING_API':\n isCacheComponentsEnabled &&\n (dev || config.experimental.exposeTestingApiInProductionBuild === true),\n 'process.env.__NEXT_CACHE_LIFE': config.cacheLife,\n 'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':\n config.experimental.clientParamParsingOrigins || [],\n }\n\n const userDefines = config.compiler?.define ?? {}\n for (const key in userDefines) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.define\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefines[key]\n }\n\n if (isNodeServer || isEdgeServer) {\n const userDefinesServer = config.compiler?.defineServer ?? {}\n for (const key in userDefinesServer) {\n if (defineEnv.hasOwnProperty(key)) {\n throw new Error(\n `The \\`compiler.defineServer\\` option is configured to replace the \\`${key}\\` variable. This variable is either part of a Next.js built-in or is already configured.`\n )\n }\n defineEnv[key] = userDefinesServer[key]\n }\n }\n\n const serializedDefineEnv = serializeDefineEnv(defineEnv)\n\n // we delay inlining these values until after the build\n // with flying shuttle enabled so we can update them\n // without invalidating entries\n if (!dev && omitNonDeterministic) {\n // client uses window. instead of leaving process.env\n // in case process isn't polyfilled on client already\n // since by this point it won't be added by webpack\n const safeKey = (key: string) =>\n isClient ? `window.${key.split('.').pop()}` : key\n\n for (const key in nextPublicEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n for (const key in nextConfigEnv) {\n serializedDefineEnv[key] = safeKey(key)\n }\n if (!config.experimental.runtimeServerDeploymentId) {\n for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {\n serializedDefineEnv[key] = safeKey(key)\n }\n }\n }\n\n return serializedDefineEnv\n}\n"],"names":["path","needsExperimentalReact","getNextConfigEnv","getNextPublicEnvironmentVariables","DEFINE_ENV_EXPRESSION","Symbol","serializeDefineEnv","defineEnv","defineEnvStringified","Object","fromEntries","entries","map","key","value","JSON","stringify","getImageConfig","config","dev","deviceSizes","images","imageSizes","qualities","loader","dangerouslyAllowSVG","unoptimized","domains","remotePatterns","localPatterns","output","getDefineEnv","isTurbopack","clientRouterFilters","distDir","projectPath","fetchCacheKeyPrefix","hasRewrites","isClient","isEdgeServer","isNodeServer","middlewareMatchers","omitNonDeterministic","rewrites","nextPublicEnv","nextConfigEnv","isCacheComponentsEnabled","cacheComponents","isUseCacheEnabled","experimental","useCache","__NEXT_DEFINE_ENV","EdgeRuntime","process","env","NEXT_EDGE_RUNTIME_PROVIDER","NEXT_RSPACK","allowDevelopmentBuild","NEXT_PRIVATE_DISABLE_DEV_OVERLAY_UX","Boolean","appNavFailHandling","turbopackSharedRuntime","cachedNavigations","coldCacheBadge","requestInsights","supportsImmutableAssets","useSkewCookie","deploymentId","runtimeServerDeploymentId","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","manualClientBasePath","isNaN","Number","staleTimes","dynamic","static","clientRouterFilter","staticFilter","dynamicFilter","validateRSCRequestHeaders","serverComponentsHmrCancellation","dynamicOnHover","useOffline","prefetchInlining","optimisticClientCache","proxyPrefetch","crossOrigin","__NEXT_TEST_MODE","relative","cwd","basePath","caseSensitiveRoutes","trailingSlash","devIndicators","position","reactStrictMode","optimizeCss","nextScriptWorkers","scrollRestoration","i18n","skipProxyUrlNormalize","externalProxyRewritesResolve","skipTrailingSlashRedirect","webVitalsAttribution","length","linkNoTouchStart","assetPrefix","authInterrupts","NEXT_TELEMETRY_DISABLED","undefined","multiZoneDraftMode","trustHostHeader","allowedRevalidateHeaderKeys","logging","browserToTerminal","mcpServer","turbopackFileSystemCacheForDev","reactDebugChannel","transitionIndicator","gestureTransition","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","exposeTestingApiInProductionBuild","cacheLife","clientParamParsingOrigins","userDefines","compiler","define","hasOwnProperty","Error","userDefinesServer","defineServer","serializedDefineEnv","safeKey","split","pop"],"mappings":"AAOA,OAAOA,UAAU,YAAW;AAC5B,SAASC,sBAAsB,QAAQ,kCAAiC;AACxE,SACEC,gBAAgB,EAChBC,iCAAiC,QAC5B,oBAAmB;AA8B1B,MAAMC,wBAAwBC,OAAO;AAqBrC;;CAEC,GACD,SAASC,mBAAmBC,SAAoB;IAC9C,MAAMC,uBAA4CC,OAAOC,WAAW,CAClED,OAAOE,OAAO,CAACJ,WAAWK,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAC9CD;YACA,OAAOC,UAAU,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QAC5D,IAAK,MAAMvH,OAAOsH,kBAAmB;YACnC,IAAI5H,UAAU0H,cAAc,CAACpH,MAAM;gBACjC,MAAM,qBAEL,CAFK,IAAIqH,MACR,CAAC,oEAAoE,EAAErH,IAAI,yFAAyF,CAAC,GADjK,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF;YACAN,SAAS,CAACM,IAAI,GAAGsH,iBAAiB,CAACtH,IAAI;QACzC;IACF;IAEA,MAAMwH,sBAAsB/H,mBAAmBC;IAE/C,uDAAuD;IACvD,oDAAoD;IACpD,+BAA+B;IAC/B,IAAI,CAACY,OAAOuB,sBAAsB;QAChC,qDAAqD;QACrD,qDAAqD;QACrD,mDAAmD;QACnD,MAAM4F,UAAU,CAACzH,MACfyB,WAAW,CAAC,OAAO,EAAEzB,IAAI0H,KAAK,CAAC,KAAKC,GAAG,IAAI,GAAG3H;QAEhD,IAAK,MAAMA,OAAO+B,cAAe;YAC/ByF,mBAAmB,CAACxH,IAAI,GAAGyH,QAAQzH;QACrC;QACA,IAAK,MAAMA,OAAOgC,cAAe;YAC/BwF,mBAAmB,CAACxH,IAAI,GAAGyH,QAAQzH;QACrC;QACA,IAAI,CAACK,OAAO+B,YAAY,CAACmB,yBAAyB,EAAE;YAClD,KAAK,MAAMvD,OAAO;gBAAC;aAAiC,CAAE;gBACpDwH,mBAAmB,CAACxH,IAAI,GAAGyH,QAAQzH;YACrC;QACF;IACF;IAEA,OAAOwH;AACT","ignoreList":[0]}

@@ -62,3 +62,3 @@ import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes';

function isCatchAllRoute(pathname) {
// Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatability.
// Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatibility.
return !isOptionalCatchAll(pathname) && isCatchAll(pathname);

@@ -65,0 +65,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/build/normalize-catchall-routes.ts"],"sourcesContent":["import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'\nimport { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathname-normalizer'\n\n/**\n * This function will transform the appPaths in order to support catch-all routes and parallel routes.\n * It will traverse the appPaths, looking for catch-all routes and try to find parallel routes that could match\n * the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.\n *\n * @param appPaths The appPaths to transform\n */\nexport function normalizeCatchAllRoutes(\n appPaths: Record<string, string[]>,\n normalizer = new AppPathnameNormalizer()\n) {\n const catchAllRoutes = [\n ...new Set(\n Object.values(appPaths)\n .flat()\n .filter(isCatchAllRoute)\n // Sorting is important because we want to match the most specific path.\n .sort((a, b) => b.split('/').length - a.split('/').length)\n ),\n ]\n\n // interception routes should only be matched by a single entrypoint\n // we don't want to push a catch-all route to an interception route\n // because it would mean the interception would be handled by the wrong page component\n const filteredAppPaths = Object.keys(appPaths).filter(\n (route) => !isInterceptionRouteAppPath(route)\n )\n\n for (const appPath of filteredAppPaths) {\n for (const catchAllRoute of catchAllRoutes) {\n const normalizedCatchAllRoute = normalizer.normalize(catchAllRoute)\n const normalizedCatchAllRouteBasePath = normalizedCatchAllRoute.slice(\n 0,\n normalizedCatchAllRoute.search(catchAllRouteRegex)\n )\n\n if (\n // check if the appPath could match the catch-all\n appPath.startsWith(normalizedCatchAllRouteBasePath) &&\n // check if there's not already a slot value that could match the catch-all\n !appPaths[appPath].some((path) => hasMatchedSlots(path, catchAllRoute))\n ) {\n // optional catch-all routes are not currently supported, but leaving this logic in place\n // for when they are eventually supported.\n if (isOptionalCatchAll(catchAllRoute)) {\n // optional catch-all routes should match both the root segment and any segment after it\n // for example, `/[[...slug]]` should match `/` and `/foo` and `/foo/bar`\n appPaths[appPath].push(catchAllRoute)\n } else if (isCatchAll(catchAllRoute)) {\n // regular catch-all (single bracket) should only match segments after it\n // for example, `/[...slug]` should match `/foo` and `/foo/bar` but not `/`\n if (normalizedCatchAllRouteBasePath !== appPath) {\n appPaths[appPath].push(catchAllRoute)\n }\n }\n }\n }\n }\n}\n\nfunction hasMatchedSlots(path1: string, path2: string): boolean {\n const slots1 = path1.split('/').filter(isMatchableSlot)\n const slots2 = path2.split('/').filter(isMatchableSlot)\n\n // if the catch-all route does not have the same number of slots as the app path, it can't match\n if (slots1.length !== slots2.length) return false\n\n // compare the slots in both paths. For there to be a match, each slot must be the same\n for (let i = 0; i < slots1.length; i++) {\n if (slots1[i] !== slots2[i]) return false\n }\n\n return true\n}\n\n/**\n * Returns true for slots that should be considered when checking for match compatibility.\n * Excludes children slots because these are similar to having a segment-level `page`\n * which would cause a slot length mismatch when comparing it to a catch-all route.\n */\nfunction isMatchableSlot(segment: string): boolean {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nconst catchAllRouteRegex = /\\[?\\[\\.\\.\\./\n\nfunction isCatchAllRoute(pathname: string): boolean {\n // Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatability.\n return !isOptionalCatchAll(pathname) && isCatchAll(pathname)\n}\n\nfunction isOptionalCatchAll(pathname: string): boolean {\n return pathname.includes('[[...')\n}\n\nfunction isCatchAll(pathname: string): boolean {\n return pathname.includes('[...')\n}\n"],"names":["isInterceptionRouteAppPath","AppPathnameNormalizer","normalizeCatchAllRoutes","appPaths","normalizer","catchAllRoutes","Set","Object","values","flat","filter","isCatchAllRoute","sort","a","b","split","length","filteredAppPaths","keys","route","appPath","catchAllRoute","normalizedCatchAllRoute","normalize","normalizedCatchAllRouteBasePath","slice","search","catchAllRouteRegex","startsWith","some","path","hasMatchedSlots","isOptionalCatchAll","push","isCatchAll","path1","path2","slots1","isMatchableSlot","slots2","i","segment","pathname","includes"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,iDAAgD;AAC3F,SAASC,qBAAqB,QAAQ,0DAAyD;AAE/F;;;;;;CAMC,GACD,OAAO,SAASC,wBACdC,QAAkC,EAClCC,aAAa,IAAIH,uBAAuB;IAExC,MAAMI,iBAAiB;WAClB,IAAIC,IACLC,OAAOC,MAAM,CAACL,UACXM,IAA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IAAIwB,IAAI,GAAGA,IAAIH,OAAOrB,MAAM,EAAEwB,IAAK;QACtC,IAAIH,MAAM,CAACG,EAAE,KAAKD,MAAM,CAACC,EAAE,EAAE,OAAO;IACtC;IAEA,OAAO;AACT;AAEA;;;;CAIC,GACD,SAASF,gBAAgBG,OAAe;IACtC,OAAOA,QAAQb,UAAU,CAAC,QAAQa,YAAY;AAChD;AAEA,MAAMd,qBAAqB;AAE3B,SAAShB,gBAAgB+B,QAAgB;IACvC,mIAAmI;IACnI,OAAO,CAACV,mBAAmBU,aAAaR,WAAWQ;AACrD;AAEA,SAASV,mBAAmBU,QAAgB;IAC1C,OAAOA,SAASC,QAAQ,CAAC;AAC3B;AAEA,SAAST,WAAWQ,QAAgB;IAClC,OAAOA,SAASC,QAAQ,CAAC;AAC3B","ignoreList":[0]}
{"version":3,"sources":["../../../src/build/normalize-catchall-routes.ts"],"sourcesContent":["import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'\nimport { AppPathnameNormalizer } from '../server/normalizers/built/app/app-pathname-normalizer'\n\n/**\n * This function will transform the appPaths in order to support catch-all routes and parallel routes.\n * It will traverse the appPaths, looking for catch-all routes and try to find parallel routes that could match\n * the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.\n *\n * @param appPaths The appPaths to transform\n */\nexport function normalizeCatchAllRoutes(\n appPaths: Record<string, string[]>,\n normalizer = new AppPathnameNormalizer()\n) {\n const catchAllRoutes = [\n ...new Set(\n Object.values(appPaths)\n .flat()\n .filter(isCatchAllRoute)\n // Sorting is important because we want to match the most specific path.\n .sort((a, b) => b.split('/').length - a.split('/').length)\n ),\n ]\n\n // interception routes should only be matched by a single entrypoint\n // we don't want to push a catch-all route to an interception route\n // because it would mean the interception would be handled by the wrong page component\n const filteredAppPaths = Object.keys(appPaths).filter(\n (route) => !isInterceptionRouteAppPath(route)\n )\n\n for (const appPath of filteredAppPaths) {\n for (const catchAllRoute of catchAllRoutes) {\n const normalizedCatchAllRoute = normalizer.normalize(catchAllRoute)\n const normalizedCatchAllRouteBasePath = normalizedCatchAllRoute.slice(\n 0,\n normalizedCatchAllRoute.search(catchAllRouteRegex)\n )\n\n if (\n // check if the appPath could match the catch-all\n appPath.startsWith(normalizedCatchAllRouteBasePath) &&\n // check if there's not already a slot value that could match the catch-all\n !appPaths[appPath].some((path) => hasMatchedSlots(path, catchAllRoute))\n ) {\n // optional catch-all routes are not currently supported, but leaving this logic in place\n // for when they are eventually supported.\n if (isOptionalCatchAll(catchAllRoute)) {\n // optional catch-all routes should match both the root segment and any segment after it\n // for example, `/[[...slug]]` should match `/` and `/foo` and `/foo/bar`\n appPaths[appPath].push(catchAllRoute)\n } else if (isCatchAll(catchAllRoute)) {\n // regular catch-all (single bracket) should only match segments after it\n // for example, `/[...slug]` should match `/foo` and `/foo/bar` but not `/`\n if (normalizedCatchAllRouteBasePath !== appPath) {\n appPaths[appPath].push(catchAllRoute)\n }\n }\n }\n }\n }\n}\n\nfunction hasMatchedSlots(path1: string, path2: string): boolean {\n const slots1 = path1.split('/').filter(isMatchableSlot)\n const slots2 = path2.split('/').filter(isMatchableSlot)\n\n // if the catch-all route does not have the same number of slots as the app path, it can't match\n if (slots1.length !== slots2.length) return false\n\n // compare the slots in both paths. For there to be a match, each slot must be the same\n for (let i = 0; i < slots1.length; i++) {\n if (slots1[i] !== slots2[i]) return false\n }\n\n return true\n}\n\n/**\n * Returns true for slots that should be considered when checking for match compatibility.\n * Excludes children slots because these are similar to having a segment-level `page`\n * which would cause a slot length mismatch when comparing it to a catch-all route.\n */\nfunction isMatchableSlot(segment: string): boolean {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nconst catchAllRouteRegex = /\\[?\\[\\.\\.\\./\n\nfunction isCatchAllRoute(pathname: string): boolean {\n // Optional catch-all slots are not currently supported, and as such they are not considered when checking for match compatibility.\n return !isOptionalCatchAll(pathname) && isCatchAll(pathname)\n}\n\nfunction isOptionalCatchAll(pathname: string): boolean {\n return pathname.includes('[[...')\n}\n\nfunction isCatchAll(pathname: string): boolean {\n return pathname.includes('[...')\n}\n"],"names":["isInterceptionRouteAppPath","AppPathnameNormalizer","normalizeCatchAllRoutes","appPaths","normalizer","catchAllRoutes","Set","Object","values","flat","filter","isCatchAllRoute","sort","a","b","split","length","filteredAppPaths","keys","route","appPath","catchAllRoute","normalizedCatchAllRoute","normalize","normalizedCatchAllRouteBasePath","slice","search","catchAllRouteRegex","startsWith","some","path","hasMatchedSlots","isOptionalCatchAll","push","isCatchAll","path1","path2","slots1","isMatchableSlot","slots2","i","segment","pathname","includes"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,iDAAgD;AAC3F,SAASC,qBAAqB,QAAQ,0DAAyD;AAE/F;;;;;;CAMC,GACD,OAAO,SAASC,wBACdC,QAAkC,EAClCC,aAAa,IAAIH,uBAAuB;IAExC,MAAMI,iBAAiB;WAClB,IAAIC,IACLC,OAAOC,MAAM,CAACL,UACXM,IAAI,GACJC,MAAM,CAACC,gBACR,wEAAwE;SACvEC,IAAI,CAAC,CAACC,GAAGC,IAAMA,EAAEC,KAAK,CAAC,KAAKC,MAAM,GAAGH,EAAEE,KAAK,CAAC,KAAKC,MAAM;KAE9D;IAED,oEAAoE;IACpE,mEAAmE;IACnE,sFAAsF;IACtF,MAAMC,mBAAmBV,OAAOW,IAAI,CAACf,UAAUO,MAAM,CACnD,CAACS,QAAU,CAACnB,2BAA2BmB;IAGzC,KAAK,MAAMC,WAAWH,iBAAkB;QACtC,KAAK,MAAMI,iBAAiBhB,eAAgB;YAC1C,MAAMiB,0BAA0BlB,WAAWmB,SAAS,CAACF;YACrD,MAAMG,kCAAkCF,wBAAwBG,KAAK,CACnE,GACAH,wBAAwBI,MAAM,CAACC;YAGjC,IACE,iDAAiD;YACjDP,QAAQQ,UAAU,CAACJ,oCACnB,2EAA2E;YAC3E,CAACrB,QAAQ,CAACiB,QAAQ,CAACS,IAAI,CAAC,CAACC,OAASC,gBAAgBD,MAAMT,iBACxD;gBACA,yFAAyF;gBACzF,0CAA0C;gBAC1C,IAAIW,mBAAmBX,gBAAgB;oBACrC,wFAAwF;oBACxF,yEAAyE;oBACzElB,QAAQ,CAACiB,QAAQ,CAACa,IAAI,CAACZ;gBACzB,OAAO,IAAIa,WAAWb,gBAAgB;oBACpC,yEAAyE;oBACzE,2EAA2E;oBAC3E,IAAIG,oCAAoCJ,SAAS;wBAC/CjB,QAAQ,CAACiB,QAAQ,CAACa,IAAI,CAACZ;oBACzB;gBACF;YACF;QACF;IACF;AACF;AAEA,SAASU,gBAAgBI,KAAa,EAAEC,KAAa;IACnD,MAAMC,SAASF,MAAMpB,KAAK,CAAC,KAAKL,MAAM,CAAC4B;IACvC,MAAMC,SAASH,MAAMrB,KAAK,CAAC,KAAKL,MAAM,CAAC4B;IAEvC,gGAAgG;IAChG,IAAID,OAAOrB,MAAM,KAAKuB,OAAOvB,MAAM,EAAE,OAAO;IAE5C,uFAAuF;IACvF,IAAK,IAAIwB,IAAI,GAAGA,IAAIH,OAAOrB,MAAM,EAAEwB,IAAK;QACtC,IAAIH,MAAM,CAACG,EAAE,KAAKD,MAAM,CAACC,EAAE,EAAE,OAAO;IACtC;IAEA,OAAO;AACT;AAEA;;;;CAIC,GACD,SAASF,gBAAgBG,OAAe;IACtC,OAAOA,QAAQb,UAAU,CAAC,QAAQa,YAAY;AAChD;AAEA,MAAMd,qBAAqB;AAE3B,SAAShB,gBAAgB+B,QAAgB;IACvC,mIAAmI;IACnI,OAAO,CAACV,mBAAmBU,aAAaR,WAAWQ;AACrD;AAEA,SAASV,mBAAmBU,QAAgB;IAC1C,OAAOA,SAASC,QAAQ,CAAC;AAC3B;AAEA,SAAST,WAAWQ,QAAgB;IAClC,OAAOA,SAASC,QAAQ,CAAC;AAC3B","ignoreList":[0]}

@@ -14,3 +14,3 @@ import path from 'path';

}({});
const nextVersion = "16.3.1-canary.11";
const nextVersion = "16.3.1-canary.12";
const ArchName = arch();

@@ -17,0 +17,0 @@ const PlatformName = platform();

@@ -69,3 +69,3 @@ import path from 'path';

isPersistentCachingEnabled: persistentCaching,
nextVersion: "16.3.1-canary.11"
nextVersion: "16.3.1-canary.12"
}, {

@@ -72,0 +72,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode,

@@ -88,3 +88,3 @@ // Import cpu-profile first to start profiling early if enabled

deferredEntries: config.experimental.deferredEntries,
nextVersion: "16.3.1-canary.11"
nextVersion: "16.3.1-canary.12"
};

@@ -91,0 +91,0 @@ if (config.experimental.turbopackSeedCacheFromWorktree) {

@@ -1,2 +0,1 @@

import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr';
import { normalizeRouteRegex } from '../lib/load-custom-routes';

@@ -406,3 +405,3 @@ import { INSTRUMENTATION_HOOK_FILENAME, MIDDLEWARE_FILENAME, SERVER_PROPS_GET_INIT_PROPS_CONFLICT, SERVER_PROPS_SSG_CONFLICT, SSG_GET_INITIAL_PROPS_CONFLICT, WEBPACK_LAYERS, PROXY_FILENAME } from '../lib/constants';

}
export async function isPageStatic({ dir, page, distDir, configFileName, httpAgentOptions, locales, defaultLocale, parentId, pageRuntime, edgeInfo, pageType, cacheComponents, authInterrupts, useCacheTimeout, staticPageGenerationTimeout, originalAppPath, isrFlushToDisk, cacheMaxMemorySize, nextConfigOutput, cacheHandler, cacheHandlers, cacheLifeProfiles, pprConfig, buildId, deploymentId, clientAssetToken, sriEnabled }) {
export async function isPageStatic({ dir, page, distDir, configFileName, httpAgentOptions, locales, defaultLocale, parentId, pageRuntime, edgeInfo, pageType, cacheComponents, authInterrupts, useCacheTimeout, staticPageGenerationTimeout, originalAppPath, isrFlushToDisk, cacheMaxMemorySize, nextConfigOutput, cacheHandler, cacheHandlers, cacheLifeProfiles, buildId, deploymentId, clientAssetToken, sriEnabled }) {
// Skip page data collection for synthetic _global-error routes

@@ -508,6 +507,5 @@ if (page === UNDERSCORE_GLOBAL_ERROR_ROUTE) {

rootParamKeys = collectRootParamKeys(routeModule);
// A page supports partial prerendering if it is an app page and either
// the whole app has PPR enabled or this page has PPR enabled when we're
// in incremental mode.
isRoutePPREnabled = routeModule.definition.kind === RouteKind.APP_PAGE && checkIsRoutePPREnabled(pprConfig);
// A page supports partial prerendering when it is an app page and
// Cache Components is enabled.
isRoutePPREnabled = routeModule.definition.kind === RouteKind.APP_PAGE && cacheComponents;
// If force dynamic was set and we don't have PPR enabled, then set the

@@ -514,0 +512,0 @@ // revalidate to 0.

@@ -8,3 +8,3 @@ /**

import { setAttributesFromProps } from './set-attributes-from-props';
const version = "16.3.1-canary.11";
const version = "16.3.1-canary.12";
window.next = {

@@ -11,0 +11,0 @@ version,

@@ -13,3 +13,2 @@ import { workUnitAsyncStorage } from './server-async-storage';

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -16,0 +15,0 @@ if (error) {

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/handle-isr-error.tsx"],"sourcesContent":["import { workUnitAsyncStorage } from './server-async-storage'\n\n// if we are revalidating we want to re-throw the error so the\n// function crashes so we can maintain our previous cache\n// instead of caching the error page\nexport function handleISRError({ error }: { error: any }) {\n if (!workUnitAsyncStorage) {\n return\n }\n\n const store = workUnitAsyncStorage.getStore()\n switch (store?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n if (error) {\n console.error(error)\n }\n throw error\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return\n default:\n store satisfies never\n }\n}\n"],"names":["workUnitAsyncStorage","handleISRError","error","store","getStore","type","console","undefined"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,yBAAwB;AAE7D,8DAA8D;AAC9D,yDAAyD;AACzD,oCAAoC;AACpC,OAAO,SAASC,eAAe,EAAEC,KAAK,EAAkB;IACtD,IAAI,CAACF,sBAAsB;QACzB;IACF;IAEA,MAAMG,QAAQH,qBAAqBI,QAAQ;IAC3C,OAAQD,OAAOE;QACb,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,IAAIH,OAAO;gBACTI,QAAQJ,KAAK,CAACA;YAChB;YACA,MAAMA;QACR,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKK;YACH;QACF;YACEJ;IACJ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/handle-isr-error.tsx"],"sourcesContent":["import { workUnitAsyncStorage } from './server-async-storage'\n\n// if we are revalidating we want to re-throw the error so the\n// function crashes so we can maintain our previous cache\n// instead of caching the error page\nexport function handleISRError({ error }: { error: any }) {\n if (!workUnitAsyncStorage) {\n return\n }\n\n const store = workUnitAsyncStorage.getStore()\n switch (store?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n if (error) {\n console.error(error)\n }\n throw error\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return\n default:\n store satisfies never\n }\n}\n"],"names":["workUnitAsyncStorage","handleISRError","error","store","getStore","type","console","undefined"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,yBAAwB;AAE7D,8DAA8D;AAC9D,yDAAyD;AACzD,oCAAoC;AACpC,OAAO,SAASC,eAAe,EAAEC,KAAK,EAAkB;IACtD,IAAI,CAACF,sBAAsB;QACzB;IACF;IAEA,MAAMG,QAAQH,qBAAqBI,QAAQ;IAC3C,OAAQD,OAAOE;QACb,KAAK;QACL,KAAK;QACL,KAAK;YACH,IAAIH,OAAO;gBACTI,QAAQJ,KAAK,CAACA;YAChB;YACA,MAAMA;QACR,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKK;YACH;QACF;YACEJ;IACJ;AACF","ignoreList":[0]}

@@ -21,3 +21,2 @@ import { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external';

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':

@@ -59,3 +58,2 @@ case 'cache':

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':

@@ -89,3 +87,2 @@ case 'cache':

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':

@@ -92,0 +89,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/instant-samples.ts"],"sourcesContent":["import type { Params } from '../../server/request/params'\nimport type { ReadonlyURLSearchParams } from './readonly-url-search-params'\nimport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'\nimport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\nimport {\n createExhaustiveParamsProxy,\n createExhaustiveURLSearchParamsProxy,\n trackMissingSampleErrorAndThrow,\n} from '../../server/app-render/instant-validation/instant-samples'\nimport { InstantValidationError } from '../../server/app-render/instant-validation/instant-validation-error'\n\nexport function instrumentParamsForClientValidation<TPArams extends Params>(\n underlyingParams: TPArams\n): TPArams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.params ?? {})\n )\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingParams\n}\n\nexport function expectCompleteParamsInClientValidation(\n expression: string\n): void {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n const missingParams = Array.from(fallbackParams.keys())\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${workStore.route}\" called ${expression} but param${missingParams.length > 1 ? 's' : ''} ${missingParams.map((p) => `\"${p}\"`).join(', ')} ${missingParams.length > 1 ? 'are' : 'is'} not defined in the \\`unstable_samples\\` of \\`instant\\`. ` +\n `${expression} requires all route params to be provided.`\n )\n )\n }\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\nexport function instrumentSearchParamsForClientValidation(\n underlyingSearchParams: ReadonlyURLSearchParams\n): ReadonlyURLSearchParams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.searchParams ?? {})\n )\n return createExhaustiveURLSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingSearchParams\n}\n"],"names":["workUnitAsyncStorage","workAsyncStorage","createExhaustiveParamsProxy","createExhaustiveURLSearchParamsProxy","trackMissingSampleErrorAndThrow","InstantValidationError","instrumentParamsForClientValidation","underlyingParams","workStore","getStore","workUnitStore","type","validationSamples","declaredKeys","Set","Object","keys","params","route","expectCompleteParamsInClientValidation","expression","fallbackParams","fallbackRouteParams","size","missingParams","Array","from","length","map","p","join","instrumentSearchParamsForClientValidation","underlyingSearchParams","searchParams"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,2DAA0D;AAC/F,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SACEC,2BAA2B,EAC3BC,oCAAoC,EACpCC,+BAA+B,QAC1B,6DAA4D;AACnE,SAASC,sBAAsB,QAAQ,sEAAqE;AAE5G,OAAO,SAASC,oCACdC,gBAAyB;IAEzB,MAAMC,YAAYP,iBAAiBQ,QAAQ;IAC3C,MAAMC,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAID,aAAaE,eAAe;QAC9B,OAAQA,cAAcC,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAID,cAAcE,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACN,cAAcE,iBAAiB,CAACK,MAAM,IAAI,CAAC;wBAEzD,OAAOf,4BACLK,kBACAM,cACAL,UAAUU,KAAK;oBAEnB;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACER;QACJ;IACF;IACA,OAAOH;AACT;AAEA,OAAO,SAASY,uCACdC,UAAkB;IAElB,MAAMZ,YAAYP,iBAAiBQ,QAAQ;IAC3C,MAAMC,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAID,aAAaE,eAAe;QAC9B,OAAQA,cAAcC,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAID,cAAcE,iBAAiB,EAAE;wBACnC,MAAMS,iBAAiBX,cAAcY,mBAAmB;wBACxD,IAAID,kBAAkBA,eAAeE,IAAI,GAAG,GAAG;4BAC7C,MAAMC,gBAAgBC,MAAMC,IAAI,CAACL,eAAeL,IAAI;4BACpDZ,gCACE,qBAGC,CAHD,IAAIC,uBACF,CAAC,OAAO,EAAEG,UAAUU,KAAK,CAAC,SAAS,EAAEE,WAAW,UAAU,EAAEI,cAAcG,MAAM,GAAG,IAAI,MAAM,GAAG,CAAC,EAAEH,cAAcI,GAAG,CAAC,CAACC,IAAM,CAAC,CAAC,EAAEA,EAAE,CAAC,CAAC,EAAEC,IAAI,CAAC,MAAM,CAAC,EAAEN,cAAcG,MAAM,GAAG,IAAI,QAAQ,KAAK,yDAAyD,CAAC,GACpP,GAAGP,WAAW,0CAA0C,CAAC,GAF7D,qBAAA;uCAAA;4CAAA;8CAAA;4BAGA;wBAEJ;oBACF;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEV;QACJ;IACF;AACF;AAEA,OAAO,SAASqB,0CACdC,sBAA+C;IAE/C,MAAMxB,YAAYP,iBAAiBQ,QAAQ;IAC3C,MAAMC,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAID,aAAaE,eAAe;QAC9B,OAAQA,cAAcC,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAID,cAAcE,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACN,cAAcE,iBAAiB,CAACqB,YAAY,IAAI,CAAC;wBAE/D,OAAO9B,qCACL6B,wBACAnB,cACAL,UAAUU,KAAK;oBAEnB;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACER;QACJ;IACF;IACA,OAAOsB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/instant-samples.ts"],"sourcesContent":["import type { Params } from '../../server/request/params'\nimport type { ReadonlyURLSearchParams } from './readonly-url-search-params'\nimport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'\nimport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\nimport {\n createExhaustiveParamsProxy,\n createExhaustiveURLSearchParamsProxy,\n trackMissingSampleErrorAndThrow,\n} from '../../server/app-render/instant-validation/instant-samples'\nimport { InstantValidationError } from '../../server/app-render/instant-validation/instant-validation-error'\n\nexport function instrumentParamsForClientValidation<TPArams extends Params>(\n underlyingParams: TPArams\n): TPArams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.params ?? {})\n )\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingParams\n}\n\nexport function expectCompleteParamsInClientValidation(\n expression: string\n): void {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n const missingParams = Array.from(fallbackParams.keys())\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${workStore.route}\" called ${expression} but param${missingParams.length > 1 ? 's' : ''} ${missingParams.map((p) => `\"${p}\"`).join(', ')} ${missingParams.length > 1 ? 'are' : 'is'} not defined in the \\`unstable_samples\\` of \\`instant\\`. ` +\n `${expression} requires all route params to be provided.`\n )\n )\n }\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\nexport function instrumentSearchParamsForClientValidation(\n underlyingSearchParams: ReadonlyURLSearchParams\n): ReadonlyURLSearchParams {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples.searchParams ?? {})\n )\n return createExhaustiveURLSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender':\n case 'cache':\n case 'request':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n return underlyingSearchParams\n}\n"],"names":["workUnitAsyncStorage","workAsyncStorage","createExhaustiveParamsProxy","createExhaustiveURLSearchParamsProxy","trackMissingSampleErrorAndThrow","InstantValidationError","instrumentParamsForClientValidation","underlyingParams","workStore","getStore","workUnitStore","type","validationSamples","declaredKeys","Set","Object","keys","params","route","expectCompleteParamsInClientValidation","expression","fallbackParams","fallbackRouteParams","size","missingParams","Array","from","length","map","p","join","instrumentSearchParamsForClientValidation","underlyingSearchParams","searchParams"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,2DAA0D;AAC/F,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SACEC,2BAA2B,EAC3BC,oCAAoC,EACpCC,+BAA+B,QAC1B,6DAA4D;AACnE,SAASC,sBAAsB,QAAQ,sEAAqE;AAE5G,OAAO,SAASC,oCACdC,gBAAyB;IAEzB,MAAMC,YAAYP,iBAAiBQ,QAAQ;IAC3C,MAAMC,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAID,aAAaE,eAAe;QAC9B,OAAQA,cAAcC,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAID,cAAcE,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,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ACdC,sBAA+C;IAE/C,MAAMxB,YAAYP,iBAAiBQ,QAAQ;IAC3C,MAAMC,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAID,aAAaE,eAAe;QAC9B,OAAQA,cAAcC,IAAI;YACxB,KAAK;gBAAqB;oBACxB,IAAID,cAAcE,iBAAiB,EAAE;wBACnC,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACN,cAAcE,iBAAiB,CAACqB,YAAY,IAAI,CAAC;wBAE/D,OAAO9B,qCACL6B,wBACAnB,cACAL,UAAUU,KAAK;oBAEnB;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACER;QACJ;IACF;IACA,OAAOsB;AACT","ignoreList":[0]}

@@ -20,3 +20,2 @@ import { useContext } from 'react';

case 'prerender-client':
case 'prerender-ppr':
case 'validation-client':

@@ -23,0 +22,0 @@ const fallbackParams = workUnitStore.fallbackRouteParams;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/navigation-untracked.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { workUnitAsyncStorage } from './server-async-storage'\n\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams(): boolean {\n // The AsyncLocalStorage module is kept out of the client bundle via the\n // `./server-async-storage` browser alias; the guard ensures the stub is never\n // dereferenced in the browser.\n if (typeof window === 'undefined') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) return false\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'validation-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n return fallbackParams ? fallbackParams.size > 0 : false\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n\n return false\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n"],"names":["useContext","PathnameContext","workUnitAsyncStorage","hasFallbackRouteParams","window","workUnitStore","getStore","type","fallbackParams","fallbackRouteParams","size","useUntrackedPathname"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAO;AAClC,SAASC,eAAe,QAAQ,uDAAsD;AACtF,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D;;;;;;CAMC,GACD,SAASC;IACP,wEAAwE;IACxE,8EAA8E;IAC9E,+BAA+B;IAC/B,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAMC,gBAAgBH,qBAAqBI,QAAQ;QACnD,IAAI,CAACD,eAAe,OAAO;QAE3B,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAMC,iBAAiBH,cAAcI,mBAAmB;gBACxD,OAAOD,iBAAiBA,eAAeE,IAAI,GAAG,IAAI;YACpD,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEL;QACJ;QAEA,OAAO;IACT;IAEA,OAAO;AACT;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASM;IACd,qEAAqE;IACrE,8EAA8E;IAC9E,8EAA8E;IAC9E,uBAAuB;IACvB,IAAIR,0BAA0B;QAC5B,OAAO;IACT;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,sDAAsD;IACtD,OAAOH,WAAWC;AACpB","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/navigation-untracked.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { workUnitAsyncStorage } from './server-async-storage'\n\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams(): boolean {\n // The AsyncLocalStorage module is kept out of the client bundle via the\n // `./server-async-storage` browser alias; the guard ensures the stub is never\n // dereferenced in the browser.\n if (typeof window === 'undefined') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) return false\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n return fallbackParams ? fallbackParams.size > 0 : false\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n\n return false\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n"],"names":["useContext","PathnameContext","workUnitAsyncStorage","hasFallbackRouteParams","window","workUnitStore","getStore","type","fallbackParams","fallbackRouteParams","size","useUntrackedPathname"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAO;AAClC,SAASC,eAAe,QAAQ,uDAAsD;AACtF,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D;;;;;;CAMC,GACD,SAASC;IACP,wEAAwE;IACxE,8EAA8E;IAC9E,+BAA+B;IAC/B,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAMC,gBAAgBH,qBAAqBI,QAAQ;QACnD,IAAI,CAACD,eAAe,OAAO;QAE3B,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAMC,iBAAiBH,cAAcI,mBAAmB;gBACxD,OAAOD,iBAAiBA,eAAeE,IAAI,GAAG,IAAI;YACpD,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEL;QACJ;QAEA,OAAO;IACT;IAEA,OAAO;AACT;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASM;IACd,qEAAqE;IACrE,8EAA8E;IAC9E,8EAA8E;IAC9E,uBAAuB;IACvB,IAAIR,0BAA0B;QAC5B,OAAO;IACT;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,sDAAsD;IACtD,OAAOH,WAAWC;AACpB","ignoreList":[0]}

@@ -40,3 +40,4 @@ import { createHrefFromUrl } from './create-href-from-url';

const acc = {
metadataVaryPath: null
metadataVaryPath: null,
treeDivergedFromBase: false
};

@@ -43,0 +44,0 @@ const initialRouteTree = decodeTransportTreeIntoRouteTree(initialTransportData.t, // There's no base tree to overlay onto; the initial payload is a full

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n segmentCacheMap,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n segmentCacheMap // hydration writes are bound to the shared map\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n scrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","transportNodeToFlightRouterState","createInitialCacheNodeForHydration","resolveStaleAt","processRuntimePrefetchStream","segmentCacheMap","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","decodeTransportTreeIntoRouteTree","FetchStrategy","UnknownDynamicStaleTime","computeDynamicStaleAt","decodeStageUntilBoundary","discoverKnownRoute","createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","canonicalUrl","acc","metadataVaryPath","initialRouteTree","initialTask","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","staleAt","PPR","catch","cancel","processed","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","previousNextUrl","debugInfo"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gCAAgC,QAAQ,yBAAwB;AAGzE,SAASC,gCAAgC,QAAQ,oCAAmC;AACpF,SAASC,kCAAkC,QAAQ,oBAAmB;AACtE,SACEC,cAAc,EACdC,4BAA4B,EAC5BC,eAAe,EACfC,mCAAmC,EACnCC,+BAA+B,QAC1B,yBAAwB;AAC/B,SAASC,gCAAgC,QAAQ,0CAAyC;AAC1F,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SACEC,uBAAuB,EACvBC,qBAAqB,QAChB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,0BAAyB;AAClE,SAASC,kBAAkB,QAAQ,qCAAoC;AAUvE,OAAO,SAASC,yBAAyB,EACvCC,WAAW,EACXC,iB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A0E;QAC1E,uCAAuC;QACvC,IAAI1B,gCAAgC,MAAM;YACxChC,6BACE6C,KAAKC,GAAG,IACRd,8BACAO,aACAnB,uBAECgC,IAAI,CAAC,CAACO;gBACL,IAAIA,cAAc,MAAM;oBACtBzD,oCACE2C,KAAKC,GAAG,IACRzC,cAAcuD,UAAU,EACxBD,UAAUE,OAAO,EACjBF,UAAUG,iBAAiB,EAC3BH,UAAUI,cAAc,EACxBJ,UAAUK,sBAAsB,EAChCL,UAAUJ,OAAO,EACjBI,UAAUM,cAAc,EACxB,MACAhE,gBAAgB,+CAA+C;;gBAEnE;YACF,GACCwD,KAAK,CAAC;YACL,qEAAqE;YACrE,8CAA8C;YAChD;QACJ;IACF;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,YAAY;IACZ,EAAE;IACF,6EAA6E;IAC7E,8EAA8E;IAC9E,gEAAgE;IAChE,EAAE;IACF,yEAAyE;IACzE,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMS,eAAe;QACnBC,MAAMvB,YAAYwB,KAAK;QACvBC,OAAOzB,YAAY0B,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,WAAW;YACTA,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAtC;QACAuC,gBAAgB3D;QAChB,sEAAsE;QACtE4D,SACE,AAACpF,CAAAA,iCAAiC2C,gBAAgBzB,UAAUiC,QAAO,KACnE;QACFkC,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOhB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n segmentCacheMap,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null, treeDivergedFromBase: false }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n segmentCacheMap // hydration writes are bound to the shared map\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n scrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","transportNodeToFlightRouterState","createInitialCacheNodeForHydration","resolveStaleAt","processRuntimePrefetchStream","segmentCacheMap","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","decodeTransportTreeIntoRouteTree","FetchStrategy","UnknownDynamicStaleTime","computeDynamicStaleAt","decodeStageUntilBoundary","discoverKnownRoute","createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","canonicalUrl","acc","metadataVaryPath","treeDivergedFromBase","initialRouteTree","initialTask","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","staleAt","PPR","catch","cancel","processed","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","previousNextUrl","debugInfo"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gCAAgC,QAAQ,yBAAwB;AAGzE,SAASC,gCAAgC,QAAQ,oCAAmC;AACpF,SAASC,kCAAkC,QAAQ,oBAAmB;AACtE,SACEC,cAAc,EACdC,4BAA4B,EAC5BC,eAAe,EACfC,mCAAmC,EACnCC,+BAA+B,QAC1B,yBAAwB;AAC/B,SAASC,gCAAgC,QAAQ,0CAAyC;AAC1F,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SACEC,uBAAuB,EACvBC,qBAAqB,QAChB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,0BAAyB;AAClE,SAASC,kBAAkB,QAAQ,qCAAoC;AAUvE,OAAO,SAASC,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,oBAAoB,EACvBC,GAAGC,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AECiC,IAAI,CAAC,CAACO;gBACL,IAAIA,cAAc,MAAM;oBACtB1D,oCACE4C,KAAKC,GAAG,IACR1C,cAAcwD,UAAU,EACxBD,UAAUE,OAAO,EACjBF,UAAUG,iBAAiB,EAC3BH,UAAUI,cAAc,EACxBJ,UAAUK,sBAAsB,EAChCL,UAAUJ,OAAO,EACjBI,UAAUM,cAAc,EACxB,MACAjE,gBAAgB,+CAA+C;;gBAEnE;YACF,GACCyD,KAAK,CAAC;YACL,qEAAqE;YACrE,8CAA8C;YAChD;QACJ;IACF;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,YAAY;IACZ,EAAE;IACF,6EAA6E;IAC7E,8EAA8E;IAC9E,gEAAgE;IAChE,EAAE;IACF,yEAAyE;IACzE,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMS,eAAe;QACnBC,MAAMvB,YAAYwB,KAAK;QACvBC,OAAOzB,YAAY0B,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,WAAW;YACTA,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAvC;QACAwC,gBAAgB5D;QAChB,sEAAsE;QACtE6D,SACE,AAACrF,CAAAA,iCAAiC2C,gBAAgBzB,UAAUkC,QAAO,KACnE;QACFkC,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOhB;AACT","ignoreList":[0]}

@@ -75,8 +75,5 @@ 'use client';

}
// Typically, during a navigation, we decode the response using Flight's
// During a navigation, we decode the response using Flight's
// `createFromFetch` API, which accepts a `fetch` promise.
// TODO: Remove this check once the old PPR flag is removed
const isLegacyPPR = process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS;
const shouldImmediatelyDecode = !isLegacyPPR;
const res = await createFetch(url, headers, 'auto', shouldImmediatelyDecode, options.signal);
const res = await createFetch(url, headers, 'auto', true, options.signal);
// If the fetch succeeds while we're in the offline state, notify the

@@ -120,13 +117,5 @@ // offline module so it can short-circuit the polling loop.

}
let flightResponsePromise = res.flightResponsePromise;
if (flightResponsePromise === null) {
// Typically, `createFetch` would have already started decoding the
// Flight response. If it hasn't, though, we need to decode it now.
// TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR
// without Cache Components). Remove this branch once legacy PPR
// is deleted.
flightResponsePromise = createFromNextReadableStream(res.body, headers, {
allowPartialStream: postponed
});
}
// This request passed `true` to `shouldImmediatelyDecode`, so the Flight
// response promise is always initialized.
const flightResponsePromise = res.flightResponsePromise;
const [flightResponse, cacheData] = await Promise.all([

@@ -133,0 +122,0 @@ flightResponsePromise,

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/client/components/router-reducer/fetch-server-response.ts"],"sourcesContent":["'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { fetch } from '../segment-cache/fetch'\nimport type {\n FlightRouterState,\n InitialRSCPayload,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers'\nimport type { PartialTransportData } from '../../../shared/lib/rsc-transport'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport { urlToUrlWithoutFlightMarker } from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n stripIsPartialByte,\n createNonTaskyPrefetchResponseStream,\n} from '../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n readonly signal?: AbortSignal\n}\n\nexport type StaticStageData<\n T extends\n | NavigationFlightResponse\n | InitialRSCPayload = NavigationFlightResponse,\n> = {\n readonly response: T\n readonly isResponsePartial: boolean\n}\n\ntype SpaFetchServerResponseResult = {\n transportData: PartialTransportData | null\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n supportsPerSegmentPrefetching: boolean\n postponed: boolean\n dynamicStaleTime: number\n staticStageData: StaticStageData | null\n runtimePrefetchStream: ReadableStream<Uint8Array> | null\n responseHeaders: Headers\n debugInfo: Array<any> | null\n /**\n * Dev only: resolves once the server has flushed the shell-stage content to\n * the stream (or earlier, on a cache miss). The navigation defers revealing\n * the response (resolving its deferred RSCs) until this settles, so React\n * doesn't render a boundary's children before their row has been decoded and\n * commit a premature Suspense fallback. `null` outside the streaming dev\n * render.\n */\n revealAfter: Promise<void> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2' | '3'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', () => {\n isPageUnloading = true\n })\n\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n isPageUnloading = false\n })\n}\n\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url\n\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url)\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt'\n } else {\n url.pathname += '.txt'\n }\n }\n }\n\n // Typically, during a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n // TODO: Remove this check once the old PPR flag is removed\n const isLegacyPPR =\n process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS\n const shouldImmediatelyDecode = !isLegacyPPR\n const res = await createFetch<NavigationFlightResponse>(\n url,\n headers,\n 'auto',\n shouldImmediatelyDecode,\n options.signal\n )\n\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../offline') as typeof import('../offline')\n notifyOnline()\n }\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\n const contentType = res.headers.get('content-type') || ''\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL)\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain')\n }\n }\n }\n\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash\n }\n\n return doMpaNavigation(responseUrl.toString())\n }\n\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n let flightResponsePromise = res.flightResponsePromise\n if (flightResponsePromise === null) {\n // Typically, `createFetch` would have already started decoding the\n // Flight response. If it hasn't, though, we need to decode it now.\n // TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR\n // without Cache Components). Remove this branch once legacy PPR\n // is deleted.\n flightResponsePromise =\n createFromNextReadableStream<NavigationFlightResponse>(\n res.body,\n headers,\n { allowPartialStream: postponed }\n )\n }\n\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData,\n ])\n\n if (\n (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url)\n }\n\n if (flightResponse.n !== undefined) {\n // The server responded with an MPA navigation URL instead of a\n // SPA payload.\n return doMpaNavigation(flightResponse.n)\n }\n\n const staticStageData =\n cacheData !== null\n ? await resolveStaticStageData(cacheData, flightResponse, headers)\n : null\n\n return {\n transportData: flightResponse.t ?? null,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q as NormalizedSearch,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n staticStageData,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n revealAfter: flightResponse._revealAfter ?? null,\n }\n } catch (err) {\n if (options.signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request.\n // Rethrow so the caller treats it as canceled, rather than logging a\n // failure or falling back to an MPA navigation.\n throw err\n }\n\n // If the fetch rejected due to a network error, wait for connectivity\n // to be restored and then retry. checkOfflineError returns true for\n // network errors (and starts the polling loop); returns false for\n // intentional aborts/timeouts, which fall through to the MPA fallback.\n //\n // Note: when the user navigates multiple times while offline, each\n // navigation queues a separate retry here. Once connectivity returns,\n // all pending retries resume simultaneously. This is mitigated in PR 3\n // by reusing back-forward cache entries during offline navigation, which\n // avoids issuing new fetches in the first place.\n if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../offline') as typeof import('../offline')\n if (checkOfflineError(err)) {\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerResponse(url, options)\n }\n }\n\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\n\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString()\n }\n}\n\n// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null\n cacheData: Promise<FetchResponseCacheData | null>\n}\n\ntype FetchResponseCacheData = {\n isResponsePartial: boolean\n // Separate clones of the response body for stage extraction. The static\n // stage and shell stage are extracted from independent reads, so each\n // needs its own ReadableStream. Both are derived from a chain of `tee()`\n // calls in `processFetch`.\n staticBodyClone?: ReadableStream<Uint8Array>\n shellBodyClone?: ReadableStream<Uint8Array>\n}\n\n/**\n * Strips the leading isPartial byte from an RSC navigation response and\n * clones the body for segment cache extraction.\n *\n * When cache components is enabled, the server prepends a single byte:\n * '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped\n * before Flight decoding because it's not valid RSC data. The body is\n * cloned before Flight can consume it so the clone is available for later use.\n *\n * When cache components is disabled, returns the original response with\n * cacheData: null.\n */\nexport async function processFetch(response: Response): Promise<{\n response: Response\n cacheData: FetchResponseCacheData | null\n}> {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError(\n 'Expected RSC navigation response to have a body'\n )\n }\n\n const { stream, isPartial } = await stripIsPartialByte(response.body)\n\n let responseStream: ReadableStream<Uint8Array>\n let cacheData: FetchResponseCacheData\n\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n // Three readers needed: the main Flight decoder, the static-stage\n // extractor, and the shell-stage extractor. Tee twice.\n const [stream1, rest] = stream.tee()\n const [staticBodyClone, shellBodyClone] = rest.tee()\n responseStream = stream1\n cacheData = {\n isResponsePartial: isPartial,\n staticBodyClone,\n shellBodyClone,\n }\n } else {\n responseStream = stream\n cacheData = { isResponsePartial: isPartial }\n }\n\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n })\n\n // The Response constructor doesn't preserve `url` or `redirected` from\n // the original. We need both: `url` for React DevTools and `redirected`\n // for the redirect replay logic below.\n Object.defineProperty(strippedResponse, 'url', { value: response.url })\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected,\n })\n\n return { response: strippedResponse, cacheData }\n }\n\n return { response, cacheData: null }\n}\n\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */\nexport async function resolveStaticStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<StaticStageData<T> | null> {\n const { isResponsePartial, staticBodyClone } = cacheData\n\n if (staticBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n staticBodyClone.cancel()\n\n return { response: flightResponse, isResponsePartial: false }\n }\n\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const staticStageByteLength = await flightResponse.l\n const response = await decodeStageUntilBoundary<T>(\n staticBodyClone,\n staticStageByteLength,\n headers\n )\n\n return { response, isResponsePartial: true }\n }\n\n // No caching — cancel the unused clone.\n staticBodyClone.cancel()\n }\n\n return null\n}\n\n/**\n * Resolves the shell stage of a prerender response, performing a separate\n * Flight decode of the byte prefix when the shell differs from the main\n * response. Returns null when no separate decode is needed:\n *\n * - `a === undefined`: server didn't emit shell stage info.\n * - `a` resolves to `null`: the shell IS the main response — the caller can\n * reuse the existing decoded `flightResponse` if it needs a shell payload.\n *\n * Returns the decoded shell payload when `a` resolves to a number, i.e.\n * the shell is a strict prefix of the response and requires a separate\n * decode at that byte boundary.\n */\nexport async function resolveShellStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n const { shellBodyClone } = cacheData\n\n if (!shellBodyClone) {\n return null\n }\n\n if (flightResponse.a === undefined) {\n shellBodyClone.cancel()\n return null\n }\n\n const shellByteLength = await flightResponse.a\n if (shellByteLength === null) {\n // Shell == main response — caller reuses the existing flightResponse.\n shellBodyClone.cancel()\n return null\n }\n\n return decodeStageUntilBoundary<T>(shellBodyClone, shellByteLength, headers)\n}\n\n/**\n * Truncates and buffers a Flight stream clone at the given byte boundary and\n * decodes the prefix as a Flight payload. Used by the static-stage and\n * shell-stage extraction helpers.\n */\nexport async function decodeStageUntilBoundary<T>(\n responseBodyClone: ReadableStream<Uint8Array>,\n byteLength: number,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const { buffer } = await createNonTaskyPrefetchResponseStream(\n responseBodyClone,\n byteLength\n )\n return decodeBufferedStage<T>(buffer, headers)\n}\n\n/**\n * Decodes already-buffered Flight response bytes as a stage payload. The\n * bytes are delivered to Flight as a single chunk so all rows are processed\n * synchronously in one call — required for the thenable-status reads that\n * scope a response's late-resolving metadata (vary params, isPartial, ...)\n * to this decode.\n */\nexport function decodeBufferedStage<T>(\n buffer: Uint8Array,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(buffer)\n controller.close()\n },\n })\n return createFromNextReadableStream<T>(stream, headers, {\n allowPartialStream: true,\n })\n}\n\n// When an HMR refresh can be superseded, we decode its Flight response through\n// a wrapper stream we can close on abort. Closing the stream (rather than\n// letting the aborted fetch error it) makes React's Flight client mark\n// unresolved rows as halted: they suspend during render instead of rejecting,\n// so a superseded request never surfaces an error on an already-committed tree.\n// Because the stream is closed, there's also no unclosed-stream GC-root leak\n// (see #89610). The wrapper is created synchronously here so that the decode\n// starts at the same point `createFromNextFetch` would, preserving the\n// server-latency debug timing.\nfunction createHaltingFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal\n): Promise<T> & { _debugInfo?: Array<any> } {\n let closed = false\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n const wrapper = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n closed = true\n try {\n controller.close()\n } catch {\n // The controller may already be closed; nothing to do.\n }\n if (reader !== null) {\n reader.cancel().catch(() => {})\n }\n }\n if (signal.aborted) {\n onAbort()\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n },\n async pull(controller) {\n if (closed) {\n return\n }\n if (reader === null) {\n let response: Response\n try {\n response = await fetchPromise\n } catch (err) {\n // We don't inspect `err`. If the request was superseded, `onAbort`\n // already ran synchronously (abort listeners fire during\n // `signal.abort()`, before this rejection microtask), so `closed` is\n // true and the controller is already closed — erroring it would\n // throw, and a superseded request's failure is moot regardless of its\n // cause. Only a genuine, non-superseded failure reaches here with\n // `closed` still false; that is the case we surface.\n if (!closed) {\n controller.error(err)\n }\n return\n }\n if (closed) {\n // Aborted while awaiting the response. The `fetch` abort tears down\n // an in-flight request, but if it had already completed we still hold\n // an unread body; release it so it isn't left dangling.\n response.body?.cancel().catch(() => {})\n return\n }\n const body = response.body\n if (body === null) {\n controller.close()\n return\n }\n reader = body.getReader()\n }\n try {\n const { done, value } = await reader.read()\n if (closed) {\n return\n }\n if (done) {\n controller.close()\n } else {\n controller.enqueue(value)\n }\n } catch (err) {\n // Same as the fetch catch above: once superseded (`closed`) the\n // controller is already closed and the outcome is moot, so we swallow\n // the rejection unconditionally; only a real, non-superseded read\n // failure (`closed` still false) is surfaced.\n if (!closed) {\n controller.error(err)\n }\n }\n },\n })\n\n // React attaches `_debugInfo` to the returned promise at runtime.\n return createFromNextReadableStream<T>(wrapper, headers, {\n allowPartialStream: true,\n }) as Promise<T> & { _debugInfo?: Array<any> }\n}\n\n// Selects the Flight decode strategy: a halting wrapper for cancellable HMR\n// refreshes, otherwise the standard fetch-based decode. Gated to the dev server\n// (where HMR runs) so the wrapper is eliminated from production and\n// `--debug-prerender` bundles regardless of the flag.\nfunction decodeFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal | undefined\n): Promise<T> & { _debugInfo?: Array<any> } {\n if (\n process.env.__NEXT_DEV_SERVER &&\n process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION &&\n signal\n ) {\n return createHaltingFlightResponse<T>(fetchPromise, headers, signal)\n }\n return createFromNextFetch<T>(fetchPromise, headers)\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n await setCacheBustingSearchParam(fetchUrl, headers)\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n let fetchPromise = processed.then(({ response }) => response)\n\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because a\n // top-level prefetch response never blocks a navigation; if it hasn't already\n // been written into the cache by the time the navigation happens, the router\n // will go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n let browserResponse = await fetchPromise\n\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n\n let redirected = browserResponse.redirected\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20\n for (let n = 0; n < MAX_REDIRECTS; n++) {\n if (!browserResponse.redirected) {\n // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n await setCacheBustingSearchParam(fetchUrl, headers)\n processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n fetchPromise = processed.then(({ response }) => response)\n flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\n }\n\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponsePromise: flightResponsePromise,\n\n cacheData: processed.then(({ cacheData }) => cacheData),\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders | undefined,\n options?: { allowPartialStream?: boolean }\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream,\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n"],"names":["createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","InvariantError","fetch","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_RSC_UNION_QUERY","NEXT_URL","RSC_HEADER","RSC_CONTENT_TYPE_HEADER","NEXT_HMR_REFRESH_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_REQUEST_ID_HEADER","callServer","findSourceMapURL","prepareFlightRouterStateForRequest","setCacheBustingSearchParam","urlToUrlWithoutFlightMarker","getDeploymentId","getNavigationBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","stripIsPartialByte","createNonTaskyPrefetchResponseStream","UnknownDynamicStaleTime","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","doMpaNavigation","url","URL","location","origin","toString","isPageUnloading","window","addEventListener","fetchServerResponse","options","flightRouterState","nextUrl","headers","isHmrRefresh","NODE_ENV","originalUrl","__NEXT_CONFIG_OUTPUT","pathname","endsWith","isLegacyPPR","__NEXT_PPR","__NEXT_CACHE_COMPONENTS","shouldImmediatelyDecode","res","createFetch","signal","__NEXT_USE_OFFLINE","notifyOnline","responseUrl","canonicalUrl","redirected","contentType","get","interception","includes","postponed","isFlightResponse","startsWith","ok","body","hash","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","createFromNextReadableStream","allowPartialStream","flightResponse","cacheData","Promise","all","b","n","undefined","staticStageData","resolveStaticStageData","transportData","t","renderedSearch","q","couldBeIntercepted","supportsPerSegmentPrefetching","S","dynamicStaleTime","d","runtimePrefetchStream","p","responseHeaders","debugInfo","_debugInfo","revealAfter","_revealAfter","err","aborted","checkOfflineError","getOffline","waitForConnection","offline","console","error","processFetch","response","stream","isPartial","responseStream","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","stream1","rest","tee","staticBodyClone","shellBodyClone","isResponsePartial","strippedResponse","Response","status","statusText","Object","defineProperty","value","cancel","l","staticStageByteLength","decodeStageUntilBoundary","resolveShellStageData","a","shellByteLength","responseBodyClone","byteLength","buffer","decodeBufferedStage","ReadableStream","start","controller","enqueue","close","createHaltingFlightResponse","fetchPromise","closed","reader","wrapper","onAbort","catch","once","pull","getReader","done","read","decodeFlightResponse","__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION","createFromNextFetch","fetchPriority","__NEXT_TEST_MODE","deploymentId","self","__next_r","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","priority","fetchUrl","processed","then","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","searchParams","delete","rscResponse","href","flightStream","requestHeaders","debugChannel","unstable_allowPartialStream","promiseForResponse"],"mappings":"AAAA;AAEA,8CAA8C;AAC9C,6DAA6D;AAC7D,SACEA,4BAA4BC,+BAA+B,EAC3DC,mBAAmBC,sBAAsB,QACpC,kCAAiC;AAExC,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SAASC,KAAK,QAAQ,yBAAwB;AAO9C,SAGEC,6BAA6B,EAC7BC,oBAAoB,EACpBC,QAAQ,EACRC,UAAU,EACVC,uBAAuB,EACvBC,uBAAuB,EACvBC,wBAAwB,EACxBC,2BAA2B,EAC3BC,sBAAsB,QACjB,wBAAuB;AAC9B,SAASC,UAAU,QAAQ,wBAAuB;AAClD,SAASC,gBAAgB,QAAQ,gCAA+B;AAChE,SAASC,kCAAkC,QAAQ,4BAA2B;AAE9E,SAASC,0BAA0B,QAAQ,mCAAkC;AAC7E,SAASC,2BAA2B,QAAQ,qBAAoB;AAEhE,SAASC,eAAe,QAAQ,oCAAmC;AACnE,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,kBAAkB,EAClBC,oCAAoC,QAC/B,yBAAwB;AAC/B,SAASC,uBAAuB,QAAQ,2BA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1C,OAAO1C,yBAAyBuL,cAAc;QAC5CxK;QACAC;QACAyK,cAAc/J,sBAAsBA,mBAAmB8J;QACvDE,6BAA6BhJ,SAASoC;IACxC;AACF;AAEA,SAASmF,oBACP0B,kBAAqC,EACrCH,cAA8B;IAE9B,OAAOtL,gBAAgByL,oBAAoB;QACzC5K;QACAC;QACAyK,cAAc/J,sBAAsBA,mBAAmB8J;IACzD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/client/components/router-reducer/fetch-server-response.ts"],"sourcesContent":["'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { fetch } from '../segment-cache/fetch'\nimport type {\n FlightRouterState,\n InitialRSCPayload,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers'\nimport type { PartialTransportData } from '../../../shared/lib/rsc-transport'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport { urlToUrlWithoutFlightMarker } from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n stripIsPartialByte,\n createNonTaskyPrefetchResponseStream,\n} from '../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n readonly signal?: AbortSignal\n}\n\nexport type StaticStageData<\n T extends\n | NavigationFlightResponse\n | InitialRSCPayload = NavigationFlightResponse,\n> = {\n readonly response: T\n readonly isResponsePartial: boolean\n}\n\ntype SpaFetchServerResponseResult = {\n transportData: PartialTransportData | null\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n supportsPerSegmentPrefetching: boolean\n postponed: boolean\n dynamicStaleTime: number\n staticStageData: StaticStageData | null\n runtimePrefetchStream: ReadableStream<Uint8Array> | null\n responseHeaders: Headers\n debugInfo: Array<any> | null\n /**\n * Dev only: resolves once the server has flushed the shell-stage content to\n * the stream (or earlier, on a cache miss). The navigation defers revealing\n * the response (resolving its deferred RSCs) until this settles, so React\n * doesn't render a boundary's children before their row has been decoded and\n * commit a premature Suspense fallback. `null` outside the streaming dev\n * render.\n */\n revealAfter: Promise<void> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2' | '3'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', () => {\n isPageUnloading = true\n })\n\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n isPageUnloading = false\n })\n}\n\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url\n\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url)\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt'\n } else {\n url.pathname += '.txt'\n }\n }\n }\n\n // During a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n const res = await createFetch<NavigationFlightResponse>(\n url,\n headers,\n 'auto',\n true,\n options.signal\n )\n\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../offline') as typeof import('../offline')\n notifyOnline()\n }\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\n const contentType = res.headers.get('content-type') || ''\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL)\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain')\n }\n }\n }\n\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash\n }\n\n return doMpaNavigation(responseUrl.toString())\n }\n\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n // This request passed `true` to `shouldImmediatelyDecode`, so the Flight\n // response promise is always initialized.\n const flightResponsePromise = res.flightResponsePromise!\n\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData,\n ])\n\n if (\n (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url)\n }\n\n if (flightResponse.n !== undefined) {\n // The server responded with an MPA navigation URL instead of a\n // SPA payload.\n return doMpaNavigation(flightResponse.n)\n }\n\n const staticStageData =\n cacheData !== null\n ? await resolveStaticStageData(cacheData, flightResponse, headers)\n : null\n\n return {\n transportData: flightResponse.t ?? null,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q as NormalizedSearch,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n staticStageData,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n revealAfter: flightResponse._revealAfter ?? null,\n }\n } catch (err) {\n if (options.signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request.\n // Rethrow so the caller treats it as canceled, rather than logging a\n // failure or falling back to an MPA navigation.\n throw err\n }\n\n // If the fetch rejected due to a network error, wait for connectivity\n // to be restored and then retry. checkOfflineError returns true for\n // network errors (and starts the polling loop); returns false for\n // intentional aborts/timeouts, which fall through to the MPA fallback.\n //\n // Note: when the user navigates multiple times while offline, each\n // navigation queues a separate retry here. Once connectivity returns,\n // all pending retries resume simultaneously. This is mitigated in PR 3\n // by reusing back-forward cache entries during offline navigation, which\n // avoids issuing new fetches in the first place.\n if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../offline') as typeof import('../offline')\n if (checkOfflineError(err)) {\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerResponse(url, options)\n }\n }\n\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\n\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString()\n }\n}\n\n// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null\n cacheData: Promise<FetchResponseCacheData | null>\n}\n\ntype FetchResponseCacheData = {\n isResponsePartial: boolean\n // Separate clones of the response body for stage extraction. The static\n // stage and shell stage are extracted from independent reads, so each\n // needs its own ReadableStream. Both are derived from a chain of `tee()`\n // calls in `processFetch`.\n staticBodyClone?: ReadableStream<Uint8Array>\n shellBodyClone?: ReadableStream<Uint8Array>\n}\n\n/**\n * Strips the leading isPartial byte from an RSC navigation response and\n * clones the body for segment cache extraction.\n *\n * When cache components is enabled, the server prepends a single byte:\n * '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped\n * before Flight decoding because it's not valid RSC data. The body is\n * cloned before Flight can consume it so the clone is available for later use.\n *\n * When cache components is disabled, returns the original response with\n * cacheData: null.\n */\nexport async function processFetch(response: Response): Promise<{\n response: Response\n cacheData: FetchResponseCacheData | null\n}> {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError(\n 'Expected RSC navigation response to have a body'\n )\n }\n\n const { stream, isPartial } = await stripIsPartialByte(response.body)\n\n let responseStream: ReadableStream<Uint8Array>\n let cacheData: FetchResponseCacheData\n\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n // Three readers needed: the main Flight decoder, the static-stage\n // extractor, and the shell-stage extractor. Tee twice.\n const [stream1, rest] = stream.tee()\n const [staticBodyClone, shellBodyClone] = rest.tee()\n responseStream = stream1\n cacheData = {\n isResponsePartial: isPartial,\n staticBodyClone,\n shellBodyClone,\n }\n } else {\n responseStream = stream\n cacheData = { isResponsePartial: isPartial }\n }\n\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n })\n\n // The Response constructor doesn't preserve `url` or `redirected` from\n // the original. We need both: `url` for React DevTools and `redirected`\n // for the redirect replay logic below.\n Object.defineProperty(strippedResponse, 'url', { value: response.url })\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected,\n })\n\n return { response: strippedResponse, cacheData }\n }\n\n return { response, cacheData: null }\n}\n\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */\nexport async function resolveStaticStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<StaticStageData<T> | null> {\n const { isResponsePartial, staticBodyClone } = cacheData\n\n if (staticBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n staticBodyClone.cancel()\n\n return { response: flightResponse, isResponsePartial: false }\n }\n\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const staticStageByteLength = await flightResponse.l\n const response = await decodeStageUntilBoundary<T>(\n staticBodyClone,\n staticStageByteLength,\n headers\n )\n\n return { response, isResponsePartial: true }\n }\n\n // No caching — cancel the unused clone.\n staticBodyClone.cancel()\n }\n\n return null\n}\n\n/**\n * Resolves the shell stage of a prerender response, performing a separate\n * Flight decode of the byte prefix when the shell differs from the main\n * response. Returns null when no separate decode is needed:\n *\n * - `a === undefined`: server didn't emit shell stage info.\n * - `a` resolves to `null`: the shell IS the main response — the caller can\n * reuse the existing decoded `flightResponse` if it needs a shell payload.\n *\n * Returns the decoded shell payload when `a` resolves to a number, i.e.\n * the shell is a strict prefix of the response and requires a separate\n * decode at that byte boundary.\n */\nexport async function resolveShellStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n const { shellBodyClone } = cacheData\n\n if (!shellBodyClone) {\n return null\n }\n\n if (flightResponse.a === undefined) {\n shellBodyClone.cancel()\n return null\n }\n\n const shellByteLength = await flightResponse.a\n if (shellByteLength === null) {\n // Shell == main response — caller reuses the existing flightResponse.\n shellBodyClone.cancel()\n return null\n }\n\n return decodeStageUntilBoundary<T>(shellBodyClone, shellByteLength, headers)\n}\n\n/**\n * Truncates and buffers a Flight stream clone at the given byte boundary and\n * decodes the prefix as a Flight payload. Used by the static-stage and\n * shell-stage extraction helpers.\n */\nexport async function decodeStageUntilBoundary<T>(\n responseBodyClone: ReadableStream<Uint8Array>,\n byteLength: number,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const { buffer } = await createNonTaskyPrefetchResponseStream(\n responseBodyClone,\n byteLength\n )\n return decodeBufferedStage<T>(buffer, headers)\n}\n\n/**\n * Decodes already-buffered Flight response bytes as a stage payload. The\n * bytes are delivered to Flight as a single chunk so all rows are processed\n * synchronously in one call — required for the thenable-status reads that\n * scope a response's late-resolving metadata (vary params, isPartial, ...)\n * to this decode.\n */\nexport function decodeBufferedStage<T>(\n buffer: Uint8Array,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(buffer)\n controller.close()\n },\n })\n return createFromNextReadableStream<T>(stream, headers, {\n allowPartialStream: true,\n })\n}\n\n// When an HMR refresh can be superseded, we decode its Flight response through\n// a wrapper stream we can close on abort. Closing the stream (rather than\n// letting the aborted fetch error it) makes React's Flight client mark\n// unresolved rows as halted: they suspend during render instead of rejecting,\n// so a superseded request never surfaces an error on an already-committed tree.\n// Because the stream is closed, there's also no unclosed-stream GC-root leak\n// (see #89610). The wrapper is created synchronously here so that the decode\n// starts at the same point `createFromNextFetch` would, preserving the\n// server-latency debug timing.\nfunction createHaltingFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal\n): Promise<T> & { _debugInfo?: Array<any> } {\n let closed = false\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n const wrapper = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n closed = true\n try {\n controller.close()\n } catch {\n // The controller may already be closed; nothing to do.\n }\n if (reader !== null) {\n reader.cancel().catch(() => {})\n }\n }\n if (signal.aborted) {\n onAbort()\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n },\n async pull(controller) {\n if (closed) {\n return\n }\n if (reader === null) {\n let response: Response\n try {\n response = await fetchPromise\n } catch (err) {\n // We don't inspect `err`. If the request was superseded, `onAbort`\n // already ran synchronously (abort listeners fire during\n // `signal.abort()`, before this rejection microtask), so `closed` is\n // true and the controller is already closed — erroring it would\n // throw, and a superseded request's failure is moot regardless of its\n // cause. Only a genuine, non-superseded failure reaches here with\n // `closed` still false; that is the case we surface.\n if (!closed) {\n controller.error(err)\n }\n return\n }\n if (closed) {\n // Aborted while awaiting the response. The `fetch` abort tears down\n // an in-flight request, but if it had already completed we still hold\n // an unread body; release it so it isn't left dangling.\n response.body?.cancel().catch(() => {})\n return\n }\n const body = response.body\n if (body === null) {\n controller.close()\n return\n }\n reader = body.getReader()\n }\n try {\n const { done, value } = await reader.read()\n if (closed) {\n return\n }\n if (done) {\n controller.close()\n } else {\n controller.enqueue(value)\n }\n } catch (err) {\n // Same as the fetch catch above: once superseded (`closed`) the\n // controller is already closed and the outcome is moot, so we swallow\n // the rejection unconditionally; only a real, non-superseded read\n // failure (`closed` still false) is surfaced.\n if (!closed) {\n controller.error(err)\n }\n }\n },\n })\n\n // React attaches `_debugInfo` to the returned promise at runtime.\n return createFromNextReadableStream<T>(wrapper, headers, {\n allowPartialStream: true,\n }) as Promise<T> & { _debugInfo?: Array<any> }\n}\n\n// Selects the Flight decode strategy: a halting wrapper for cancellable HMR\n// refreshes, otherwise the standard fetch-based decode. Gated to the dev server\n// (where HMR runs) so the wrapper is eliminated from production and\n// `--debug-prerender` bundles regardless of the flag.\nfunction decodeFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal | undefined\n): Promise<T> & { _debugInfo?: Array<any> } {\n if (\n process.env.__NEXT_DEV_SERVER &&\n process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION &&\n signal\n ) {\n return createHaltingFlightResponse<T>(fetchPromise, headers, signal)\n }\n return createFromNextFetch<T>(fetchPromise, headers)\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n await setCacheBustingSearchParam(fetchUrl, headers)\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n let fetchPromise = processed.then(({ response }) => response)\n\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because a\n // top-level prefetch response never blocks a navigation; if it hasn't already\n // been written into the cache by the time the navigation happens, the router\n // will go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n let browserResponse = await fetchPromise\n\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n\n let redirected = browserResponse.redirected\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20\n for (let n = 0; n < MAX_REDIRECTS; n++) {\n if (!browserResponse.redirected) {\n // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n await setCacheBustingSearchParam(fetchUrl, headers)\n processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n fetchPromise = processed.then(({ response }) => response)\n flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\n }\n\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponsePromise: flightResponsePromise,\n\n cacheData: processed.then(({ cacheData }) => cacheData),\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders | undefined,\n options?: { allowPartialStream?: boolean }\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream,\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n"],"names":["createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","InvariantError","fetch","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_RSC_UNION_QUERY","NEXT_URL","RSC_HEADER","RSC_CONTENT_TYPE_HEADER","NEXT_HMR_REFRESH_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_REQUEST_ID_HEADER","callServer","findSourceMapURL","prepareFlightRouterStateForRequest","setCacheBustingSearchParam","urlToUrlWithoutFlightMarker","getDeploymentId","getNavigationBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","stripIsPartialByte","createNonTaskyPrefetchResponseStream","UnknownDynamicStaleTime","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","doMpaNavigation","url","URL","location","origin","toString","isPageUnloading","window","addEventListener","fetchServerResponse","options","flightRouterState","nextUrl","headers","isHmrRefresh","NODE_ENV","originalUrl","__NEXT_CONFIG_OUTPUT","pathname","endsWith","res","createFetch","signal","__NEXT_USE_OFFLINE","notifyOnline","responseUrl","canonicalUrl","redirected","contentType","get","interception","includes","postponed","isFlightResponse","startsWith","ok","body","hash","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","flightResponse","cacheData","Promise","all","b","n","undefined","staticStageData","resolveStaticStageData","transportData","t","renderedSearch","q","couldBeIntercepted","supportsPerSegmentPrefetching","S","dynamicStaleTime","d","runtimePrefetchStream","p","responseHeaders","debugInfo","_debugInfo","revealAfter","_revealAfter","err","aborted","checkOfflineError","getOffline","waitForConnection","offline","console","error","processFetch","response","__NEXT_CACHE_COMPONENTS","stream","isPartial","responseStream","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","stream1","rest","tee","staticBodyClone","shellBodyClone","isResponsePartial","strippedResponse","Response","status","statusText","Object","defineProperty","value","cancel","l","staticStageByteLength","decodeStageUntilBoundary","resolveShellStageData","a","shellByteLength","responseBodyClone","byteLength","buffer","decodeBufferedStage","ReadableStream","start","controller","enqueue","close","createFromNextReadableStream","allowPartialStream","createHaltingFlightResponse","fetchPromise","closed","reader","wrapper","onAbort","catch","once","pull","getReader","done","read","decodeFlightResponse","__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION","createFromNextFetch","fetchPriority","shouldImmediatelyDecode","__NEXT_TEST_MODE","deploymentId","self","__next_r","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","priority","fetchUrl","processed","then","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","searchParams","delete","rscResponse","href","flightStream","requestHeaders","debugChannel","unstable_allowPartialStream","promiseForResponse"],"mappings":"AAAA;AAEA,8CAA8C;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A6B;QAC7BQ,IAAI2G,gBAAgB3G,EAAE;QACtBtB,SAASiI,gBAAgBjI,OAAO;QAChCuB,MAAM0G,gBAAgB1G,IAAI;QAC1BqD,QAAQqD,gBAAgBrD,MAAM;QAE9B,uEAAuE;QACvE,0EAA0E;QAC1E,+BAA+B;QAC/BjD,uBAAuBA;QAEvBE,WAAWkG,UAAUC,IAAI,CAAC,CAAC,EAAEnG,SAAS,EAAE,GAAKA;IAC/C;IAEA,OAAOyG;AACT;AAEA,OAAO,SAASrC,6BACduC,YAAwC,EACxCC,cAA0C,EAC1C5I,OAA0C;IAE1C,OAAO1C,yBAAyBqL,cAAc;QAC5CtK;QACAC;QACAuK,cAAc7J,sBAAsBA,mBAAmB4J;QACvDE,6BAA6B9I,SAASqG;IACxC;AACF;AAEA,SAASe,oBACP2B,kBAAqC,EACrCH,cAA8B;IAE9B,OAAOpL,gBAAgBuL,oBAAoB;QACzC1K;QACAC;QACAuK,cAAc7J,sBAAsBA,mBAAmB4J;IACzD;AACF","ignoreList":[0]}

@@ -9,3 +9,4 @@ /**

import { ROOT_SEGMENT_REQUEST_KEY, appendSegmentRequestKeyPart, createSegmentRequestKeyPart } from '../../../shared/lib/segment-cache/segment-value-encoding';
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';
import { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';
import { matchSegment } from '../match-segments';
import { appendLayoutVaryPath, finalizeLayoutVaryPath, finalizeMetadataVaryPath, finalizePageVaryPath, getPartialLayoutVaryPath, getPartialPageVaryPath, getShellSegmentVaryPath } from './vary-path';

@@ -26,3 +27,4 @@ import { convertFlightRouterStateToRouteTree, convertRootFlightRouterStateToRouteTree } from './cache';

const acc = {
metadataVaryPath: null
metadataVaryPath: null,
treeDivergedFromBase: false
};

@@ -51,3 +53,4 @@ let routeTree;

headVaryParams,
dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds)
dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),
treeDivergedFromBase: acc.treeDivergedFromBase
};

@@ -147,5 +150,10 @@ }

*/ export function decodeTransportTreeIntoRouteTree(transportNode, baseRouterState, renderedSearch, acc) {
return decodeTransportNode(transportNode, baseRouterState ?? undefined, ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, acc);
return decodeTransportNode(transportNode, baseRouterState ?? undefined, baseRouterState ?? undefined, ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, acc);
}
function decodeTransportNode(node, base, requestKey, parentPartialVaryPath, parentRenderedSearch, acc) {
function decodeTransportNode(node, base, // The base node to compare segment identities against (see
// NavigationSeed.treeDivergedFromBase). Tracked separately from `base`:
// inheritance drops the base inside authoritative subtrees, where the
// comparison must continue, and keeps it through inactive parallel routes,
// where the comparison must stop.
compareBase, requestKey, parentPartialVaryPath, parentRenderedSearch, acc) {
const nodeData = node.d;

@@ -156,2 +164,23 @@ const inheritsFromBase = nodeData !== undefined && nodeData.r === null;

const originalSegment = transportSegmentToSegment(node.s);
if (compareBase !== undefined && !acc.treeDivergedFromBase) {
// Every transport node echoes the segment's identity, even "skipped"
// ones, so each position can be compared against the base.
const transportSegment = node.s;
if (typeof transportSegment !== 'string' && transportSegment.k == null) {
// The server omitted the param value for the client to parse from the
// URL (see the TODO in transportSegmentToSegment). Nothing to compare;
// the children are still checked.
} else {
const baseSegment = compareBase[0];
if (typeof originalSegment === 'string' && typeof baseSegment === 'string' && originalSegment.startsWith(PAGE_SEGMENT_KEY) && baseSegment.startsWith(PAGE_SEGMENT_KEY)) {
// Page segments match modulo embedded search params, which are
// validated separately (see getRenderedSearch).
} else if (originalSegment === DEFAULT_SEGMENT_KEY) {
// A default filled in by the server is not a claim about the
// position's identity.
} else if (!matchSegment(baseSegment, originalSegment)) {
acc.treeDivergedFromBase = true;
}
}
}
const baseHints = inheritedBase !== undefined ? inheritedBase[4] ?? 0 : 0;

@@ -182,4 +211,21 @@ let prefetchHints = node.h ?? baseHints;

const childSegment = transportSegmentToSegment(childNode.s);
let childCompareBase;
if (compareBase !== undefined && !acc.treeDivergedFromBase) {
const childCompareCandidate = compareBase[1][parallelRouteKey];
if (childCompareCandidate === undefined) {
// A slot the base tree doesn't have. Unless the server merely
// filled it with a default, the trees have different structures.
if (childSegment !== DEFAULT_SEGMENT_KEY) {
acc.treeDivergedFromBase = true;
}
} else if ((childCompareCandidate[2] ?? null) !== null) {
// The base branch carries a refresh state: an inactive parallel
// route reused from a different route (e.g. a "default" slot). The
// server's answer is expected to differ, so skip the branch.
} else {
childCompareBase = childCompareCandidate;
}
}
const childRequestKey = appendSegmentRequestKeyPart(requestKey, parallelRouteKey, createSegmentRequestKeyPart(childSegment));
const childTree = decodeTransportNode(childNode, childBase, childRequestKey, partialVaryPath, renderedSearch, acc);
const childTree = decodeTransportNode(childNode, childBase, childCompareBase, childRequestKey, partialVaryPath, renderedSearch, acc);
if (slots === null) {

@@ -186,0 +232,0 @@ slots = new Map();

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/client/components/segment-cache/decode-server-response.ts"],"sourcesContent":["/**\n * Decoding of RSC server responses (the transport format defined in\n * shared/lib/rsc-transport) into the client's own representations. This is\n * the only place on the client that consumes transport types; everything\n * downstream operates on RouteTree / NavigationSeed / CacheNode.\n */\n\nimport type {\n FlightRouterState,\n HeadData,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type {\n PartialTransportData,\n PartialTransportNode,\n} from '../../../shared/lib/rsc-transport'\nimport { transportSegmentToSegment } from '../../../shared/lib/rsc-transport'\nimport type { VaryParamsIterable } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n type SegmentRequestKey,\n ROOT_SEGMENT_REQUEST_KEY,\n appendSegmentRequestKeyPart,\n createSegmentRequestKeyPart,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport type { NormalizedSearch } from './cache-key'\nimport type {\n PageVaryPath,\n PartialSegmentVaryPath,\n SegmentVaryPath,\n} from './vary-path'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizeMetadataVaryPath,\n finalizePageVaryPath,\n getPartialLayoutVaryPath,\n getPartialPageVaryPath,\n getShellSegmentVaryPath,\n} from './vary-path'\nimport {\n type RouteTree,\n type RSCSegmentData,\n type RefreshState,\n type RouteTreeAccumulator,\n convertFlightRouterStateToRouteTree,\n convertRootFlightRouterStateToRouteTree,\n} from './cache'\nimport { computeDynamicStaleAt } from './bfcache'\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree<RSCSegmentData | null>\n metadataVaryPath: PageVaryPath | null\n head: HeadData | null\n isHeadPartial: boolean\n headVaryParams: VaryParamsIterable | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n transportData: PartialTransportData | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server responds with a\n // transport tree that covers only the parts of the route that have changed.\n // Decode it into a full RouteTree, overlaying it on the base tree so that\n // the slots the response carries no information about are reused from the\n // client's current state.\n //\n // The returned RouteTree carries the response's render output on each node\n // (RSCSegmentData). Pass a null transportData to convert the base tree\n // alone (e.g. for refreshes and history restores, before a response\n // is received).\n const acc: { metadataVaryPath: PageVaryPath | null } = {\n metadataVaryPath: null,\n }\n let routeTree: RouteTree<RSCSegmentData | null>\n let head: HeadData | null = null\n let isHeadPartial = true\n let headVaryParams: VaryParamsIterable | null = null\n if (transportData !== null) {\n routeTree = decodeTransportTreeIntoRouteTree(\n transportData.t,\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n const transportHead = transportData.h\n if (transportHead !== undefined) {\n head = transportHead.r\n isHeadPartial = transportHead.p\n headVaryParams = transportHead.v\n }\n } else {\n routeTree = convertRootFlightRouterStateToRouteTree(\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n }\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n renderedSearch,\n head,\n isHeadPartial,\n headVaryParams,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\n/**\n * Creates a RouteTree node for a segment, with its identity and cache-key\n * information (vary paths, page-ness, the normalized segment value)\n * initialized, and the remaining fields set to their defaults. The caller\n * finishes initializing those in place after recursing into the children.\n * Shared by the FlightRouterState converter and the transport decoder so the\n * two cannot drift, and so every node they produce has the same property\n * order (one hidden class).\n */\nexport function createRouteTreeNode<TData>(\n originalSegment: FlightRouterStateSegment,\n isRootParam: boolean,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<TData | null> {\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n if (Array.isArray(originalSegment)) {\n isPage = false\n const paramCacheKey = originalSegment[1]\n const paramName = originalSegment[0]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n paramCacheKey,\n paramName,\n isRootParam\n )\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n segment = originalSegment\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n return {\n requestKey,\n segment,\n shellVaryPath: getShellSegmentVaryPath(varyPath),\n refreshState: null,\n data: null,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. If isPage were\n // wrong it would break the behavior and we'd catch it quickly.\n varyPath: varyPath as any,\n isPage: isPage as boolean as any,\n slots: null,\n prefetchHints: 0,\n }\n}\n\n/**\n * Decodes a response's transport tree into a RouteTree, using the client's\n * current router state as the base for the parts of the route the response\n * carries no information about.\n *\n * The response is an overlay over the base:\n *\n * - Nodes with rendered output — and nodes with no data at all, which are\n * server-sent structure whose output the client fetches lazily — are\n * authoritative: their identity, hints, and subtree come entirely from\n * the response.\n * - Skipped nodes (data with a null rsc) sit on the path from the root down\n * to the rendered subtrees. The client is expected to already have them,\n * so their refresh state and hints are inherited from the base tree, and\n * any slot the response doesn't mention is reused from the base as-is.\n *\n * TODO: The base is a FlightRouterState only because that's the\n * representation the client router currently renders from (the router\n * reducer's `state.tree`, which the CacheNode tree and layout-router are\n * keyed against). Once the rendering path is updated to use RouteTree as its\n * source of truth, the base tree here can be a RouteTree, and the base-only\n * conversion path (convertFlightRouterStateToRouteTree) goes away with it.\n */\nexport function decodeTransportTreeIntoRouteTree(\n transportNode: PartialTransportNode,\n baseRouterState: FlightRouterState | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n return decodeTransportNode(\n transportNode,\n baseRouterState ?? undefined,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nfunction decodeTransportNode(\n node: PartialTransportNode,\n base: FlightRouterState | undefined,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n const nodeData = node.d\n const inheritsFromBase = nodeData !== undefined && nodeData.r === null\n // The base node this position inherits from, when it does.\n const inheritedBase = inheritsFromBase ? base : undefined\n\n const originalSegment = transportSegmentToSegment(node.s)\n\n const baseHints = inheritedBase !== undefined ? (inheritedBase[4] ?? 0) : 0\n let prefetchHints = node.h ?? baseHints\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n // Inherited positions keep the base tree's refresh state. Its rendered\n // search is updated to this response's, since all pages within the same\n // response share the same search value. (The refresh state acts like a\n // \"context provider\" for inactive parallel routes.)\n const baseCompressedRefreshState =\n inheritedBase !== undefined ? (inheritedBase[2] ?? null) : null\n const refreshState: RefreshState | null =\n baseCompressedRefreshState !== null\n ? {\n canonicalUrl: baseCompressedRefreshState[0] as string,\n renderedSearch: parentRenderedSearch,\n }\n : null\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n const tree = createRouteTreeNode<RSCSegmentData>(\n originalSegment,\n isRootParam,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n acc\n )\n tree.refreshState = refreshState\n const partialVaryPath = tree.isPage\n ? getPartialPageVaryPath(tree.varyPath)\n : getPartialLayoutVaryPath(tree.varyPath)\n\n let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null\n const transportChildren = node.c\n const baseChildren =\n inheritedBase !== undefined ? inheritedBase[1] : undefined\n if (transportChildren !== undefined) {\n for (const [parallelRouteKey, childNode] of transportChildren) {\n const childBase =\n baseChildren !== undefined ? baseChildren[parallelRouteKey] : undefined\n const childSegment = transportSegmentToSegment(childNode.s)\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childSegment)\n )\n const childTree = decodeTransportNode(\n childNode,\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n if (baseChildren !== undefined) {\n // Slots the response carries no information about are reused from the\n // base tree, structure-only.\n for (const parallelRouteKey in baseChildren) {\n if (\n transportChildren !== undefined &&\n transportChildren.has(parallelRouteKey)\n ) {\n continue\n }\n const childBase = baseChildren[parallelRouteKey]\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childBase[0])\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n\n if (inheritsFromBase) {\n // Recompute the propagated \"subtree\" prefetch hints for this segment,\n // since its children may combine response and base subtrees. Mirrors the\n // propagation done on the server in createTransportTreeFromLoaderTree.\n let propagated = prefetchHints & ~SubtreePrefetchHints\n if (slots !== null) {\n for (const childTree of slots.values()) {\n propagated = propagateSubtreeBits(propagated, childTree.prefetchHints)\n }\n }\n prefetchHints = propagated\n }\n\n if (nodeData !== undefined) {\n tree.data = {\n rsc: nodeData.r,\n isPartial: nodeData.p,\n varyParams: nodeData.v,\n }\n }\n\n tree.slots = slots\n tree.prefetchHints = prefetchHints\n return tree\n}\n"],"names":["PrefetchHint","SubtreePrefetchHints","propagateSubtreeBits","transportSegmentToSegment","ROOT_SEGMENT_REQUEST_KEY","appendSegmentRequestKeyPart","createSegmentRequestKeyPart","PAGE_SEGMENT_KEY","appendLayoutVaryPath","finalizeLayoutVaryPath","finalizeMetadataVaryPath","finalizePageVaryPath","getPartialLayoutVaryPath","getPartialPageVaryPath","getShellSegmentVaryPath","convertFlightRouterStateToRouteTree","convertRootFlightRouterStateToRouteTree","computeDynamicStaleAt","convertServerPatchToFullTree","now","currentTree","transportData","renderedSearch","dynamicStaleTimeSeconds","acc","metadataVaryPath","routeTree","head","isHeadPartial","headVaryParams","decodeTransportTreeIntoRouteTree","t","transportHead","h","undefined","r","p","v","dynamicStaleAt","createRouteTreeNode","originalSegment","isRootParam","requestKey","parentPartialVaryPath","segment","partialVaryPath","isPage","varyPath","Array","isArray","paramCacheKey","paramName","endsWith","shellVaryPath","refreshState","data","slots","prefetchHints","transportNode","baseRouterState","decodeTransportNode","node","base","parentRenderedSearch","nodeData","d","inheritsFromBase","inheritedBase","s","baseHints","IsRootLayoutOrAbove","baseCompressedRefreshState","canonicalUrl","tree","transportChildren","c","baseChildren","parallelRouteKey","childNode","childBase","childSegment","childRequestKey","childTree","Map","set","has","propagated","values","rsc","isPartial","varyParams"],"mappings":"AAAA;;;;;CAKC,GAOD,SACEA,YAAY,EACZC,oBAAoB,EACpBC,oBAAoB,QACf,uCAAsC;AAK7C,SAASC,yBAAyB,QAAQ,oCAAmC;AAE7E,SAEEC,wBAAwB,EACxBC,2BAA2B,EAC3BC,2BAA2B,QACtB,2DAA0D;AACjE,SAASC,gBAAgB,QAAQ,8BAA6B;AAO9D,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,EACpBC,wBAAwB,EACxBC,sBAAsB,EACtBC,uBAAuB,QAClB,cAAa;AACpB,SAKEC,mCAAmC,EACnCC,uCAAuC,QAClC,UAAS;AAChB,SAASC,qBAAqB,QAAQ,YAAW;AAYjD,OAAO,SAASC,6BACdC,GAAW,EACXC,WAA8B,EAC9BC,aAA0C,EAC1CC,cAAsB,EACtBC,uBAA+B;IAE/B,qEAAqE;IACrE,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,0BAA0B;IAC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ACtBwC,kBAAkBW,GAAG,CAACR,mBACtB;gBACA;YACF;YACA,MAAME,YAAYH,YAAY,CAACC,iBAAiB;YAChD,MAAMI,kBAAkB5E,4BACtBqC,YACAmC,kBACAvE,4BAA4ByE,SAAS,CAAC,EAAE;YAE1C,MAAMG,YAAYnE,oCAChBgE,WACAE,iBACApC,iBACAvB,gBACAE;YAEF,IAAIgC,UAAU,MAAM;gBAClBA,QAAQ,IAAI2B;YACd;YACA3B,MAAM4B,GAAG,CAACP,kBAAkBK;QAC9B;IACF;IAEA,IAAIhB,kBAAkB;QACpB,sEAAsE;QACtE,yEAAyE;QACzE,uEAAuE;QACvE,IAAIoB,aAAa7B,gBAAgB,CAACxD;QAClC,IAAIuD,UAAU,MAAM;YAClB,KAAK,MAAM0B,aAAa1B,MAAM+B,MAAM,GAAI;gBACtCD,aAAapF,qBAAqBoF,YAAYJ,UAAUzB,aAAa;YACvE;QACF;QACAA,gBAAgB6B;IAClB;IAEA,IAAItB,aAAa9B,WAAW;QAC1BuC,KAAKlB,IAAI,GAAG;YACViC,KAAKxB,SAAS7B,CAAC;YACfsD,WAAWzB,SAAS5B,CAAC;YACrBsD,YAAY1B,SAAS3B,CAAC;QACxB;IACF;IAEAoC,KAAKjB,KAAK,GAAGA;IACbiB,KAAKhB,aAAa,GAAGA;IACrB,OAAOgB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/client/components/segment-cache/decode-server-response.ts"],"sourcesContent":["/**\n * Decoding of RSC server responses (the transport format defined in\n * shared/lib/rsc-transport) into the client's own representations. This is\n * the only place on the client that consumes transport types; everything\n * downstream operates on RouteTree / NavigationSeed / CacheNode.\n */\n\nimport type {\n FlightRouterState,\n HeadData,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type {\n PartialTransportData,\n PartialTransportNode,\n} from '../../../shared/lib/rsc-transport'\nimport { transportSegmentToSegment } from '../../../shared/lib/rsc-transport'\nimport type { VaryParamsIterable } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n type SegmentRequestKey,\n ROOT_SEGMENT_REQUEST_KEY,\n appendSegmentRequestKeyPart,\n createSegmentRequestKeyPart,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport {\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport type { NormalizedSearch } from './cache-key'\nimport type {\n PageVaryPath,\n PartialSegmentVaryPath,\n SegmentVaryPath,\n} from './vary-path'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizeMetadataVaryPath,\n finalizePageVaryPath,\n getPartialLayoutVaryPath,\n getPartialPageVaryPath,\n getShellSegmentVaryPath,\n} from './vary-path'\nimport {\n type RouteTree,\n type RSCSegmentData,\n type RefreshState,\n type RouteTreeAccumulator,\n convertFlightRouterStateToRouteTree,\n convertRootFlightRouterStateToRouteTree,\n} from './cache'\nimport { computeDynamicStaleAt } from './bfcache'\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree<RSCSegmentData | null>\n metadataVaryPath: PageVaryPath | null\n head: HeadData | null\n isHeadPartial: boolean\n headVaryParams: VaryParamsIterable | null\n dynamicStaleAt: number\n // Whether the response rendered a segment whose identity differs from the\n // base tree's at the same position (inactive parallel route branches are\n // expected to differ and don't count). Only meaningful when the base is a\n // request tree derived from a cached route entry, as during a prefetch:\n // divergence then means the entry doesn't describe what the server renders\n // — the URL has a rewrite that behaves dynamically (see\n // fetchSegmentPrefetchesUsingDynamicRequest). During a navigation the base\n // is the current page's tree, so divergence carries no signal. False when\n // there was no base to compare against.\n treeDivergedFromBase: boolean\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n transportData: PartialTransportData | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server responds with a\n // transport tree that covers only the parts of the route that have changed.\n // Decode it into a full RouteTree, overlaying it on the base tree so that\n // the slots the response carries no information about are reused from the\n // client's current state.\n //\n // The returned RouteTree carries the response's render output on each node\n // (RSCSegmentData). Pass a null transportData to convert the base tree\n // alone (e.g. for refreshes and history restores, before a response\n // is received).\n const acc: RouteTreeAccumulator = {\n metadataVaryPath: null,\n treeDivergedFromBase: false,\n }\n let routeTree: RouteTree<RSCSegmentData | null>\n let head: HeadData | null = null\n let isHeadPartial = true\n let headVaryParams: VaryParamsIterable | null = null\n if (transportData !== null) {\n routeTree = decodeTransportTreeIntoRouteTree(\n transportData.t,\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n const transportHead = transportData.h\n if (transportHead !== undefined) {\n head = transportHead.r\n isHeadPartial = transportHead.p\n headVaryParams = transportHead.v\n }\n } else {\n routeTree = convertRootFlightRouterStateToRouteTree(\n currentTree,\n renderedSearch as NormalizedSearch,\n acc\n )\n }\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n renderedSearch,\n head,\n isHeadPartial,\n headVaryParams,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n treeDivergedFromBase: acc.treeDivergedFromBase,\n }\n}\n\n/**\n * Creates a RouteTree node for a segment, with its identity and cache-key\n * information (vary paths, page-ness, the normalized segment value)\n * initialized, and the remaining fields set to their defaults. The caller\n * finishes initializing those in place after recursing into the children.\n * Shared by the FlightRouterState converter and the transport decoder so the\n * two cannot drift, and so every node they produce has the same property\n * order (one hidden class).\n */\nexport function createRouteTreeNode<TData>(\n originalSegment: FlightRouterStateSegment,\n isRootParam: boolean,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<TData | null> {\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n if (Array.isArray(originalSegment)) {\n isPage = false\n const paramCacheKey = originalSegment[1]\n const paramName = originalSegment[0]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n paramCacheKey,\n paramName,\n isRootParam\n )\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n segment = originalSegment\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n return {\n requestKey,\n segment,\n shellVaryPath: getShellSegmentVaryPath(varyPath),\n refreshState: null,\n data: null,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. If isPage were\n // wrong it would break the behavior and we'd catch it quickly.\n varyPath: varyPath as any,\n isPage: isPage as boolean as any,\n slots: null,\n prefetchHints: 0,\n }\n}\n\n/**\n * Decodes a response's transport tree into a RouteTree, using the client's\n * current router state as the base for the parts of the route the response\n * carries no information about.\n *\n * The response is an overlay over the base:\n *\n * - Nodes with rendered output — and nodes with no data at all, which are\n * server-sent structure whose output the client fetches lazily — are\n * authoritative: their identity, hints, and subtree come entirely from\n * the response.\n * - Skipped nodes (data with a null rsc) sit on the path from the root down\n * to the rendered subtrees. The client is expected to already have them,\n * so their refresh state and hints are inherited from the base tree, and\n * any slot the response doesn't mention is reused from the base as-is.\n *\n * TODO: The base is a FlightRouterState only because that's the\n * representation the client router currently renders from (the router\n * reducer's `state.tree`, which the CacheNode tree and layout-router are\n * keyed against). Once the rendering path is updated to use RouteTree as its\n * source of truth, the base tree here can be a RouteTree, and the base-only\n * conversion path (convertFlightRouterStateToRouteTree) goes away with it.\n */\nexport function decodeTransportTreeIntoRouteTree(\n transportNode: PartialTransportNode,\n baseRouterState: FlightRouterState | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n return decodeTransportNode(\n transportNode,\n baseRouterState ?? undefined,\n baseRouterState ?? undefined,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nfunction decodeTransportNode(\n node: PartialTransportNode,\n base: FlightRouterState | undefined,\n // The base node to compare segment identities against (see\n // NavigationSeed.treeDivergedFromBase). Tracked separately from `base`:\n // inheritance drops the base inside authoritative subtrees, where the\n // comparison must continue, and keeps it through inactive parallel routes,\n // where the comparison must stop.\n compareBase: FlightRouterState | undefined,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n const nodeData = node.d\n const inheritsFromBase = nodeData !== undefined && nodeData.r === null\n // The base node this position inherits from, when it does.\n const inheritedBase = inheritsFromBase ? base : undefined\n\n const originalSegment = transportSegmentToSegment(node.s)\n\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n // Every transport node echoes the segment's identity, even \"skipped\"\n // ones, so each position can be compared against the base.\n const transportSegment = node.s\n if (typeof transportSegment !== 'string' && transportSegment.k == null) {\n // The server omitted the param value for the client to parse from the\n // URL (see the TODO in transportSegmentToSegment). Nothing to compare;\n // the children are still checked.\n } else {\n const baseSegment = compareBase[0]\n if (\n typeof originalSegment === 'string' &&\n typeof baseSegment === 'string' &&\n originalSegment.startsWith(PAGE_SEGMENT_KEY) &&\n baseSegment.startsWith(PAGE_SEGMENT_KEY)\n ) {\n // Page segments match modulo embedded search params, which are\n // validated separately (see getRenderedSearch).\n } else if (originalSegment === DEFAULT_SEGMENT_KEY) {\n // A default filled in by the server is not a claim about the\n // position's identity.\n } else if (!matchSegment(baseSegment, originalSegment)) {\n acc.treeDivergedFromBase = true\n }\n }\n }\n\n const baseHints = inheritedBase !== undefined ? (inheritedBase[4] ?? 0) : 0\n let prefetchHints = node.h ?? baseHints\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n // Inherited positions keep the base tree's refresh state. Its rendered\n // search is updated to this response's, since all pages within the same\n // response share the same search value. (The refresh state acts like a\n // \"context provider\" for inactive parallel routes.)\n const baseCompressedRefreshState =\n inheritedBase !== undefined ? (inheritedBase[2] ?? null) : null\n const refreshState: RefreshState | null =\n baseCompressedRefreshState !== null\n ? {\n canonicalUrl: baseCompressedRefreshState[0] as string,\n renderedSearch: parentRenderedSearch,\n }\n : null\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n const tree = createRouteTreeNode<RSCSegmentData>(\n originalSegment,\n isRootParam,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n acc\n )\n tree.refreshState = refreshState\n const partialVaryPath = tree.isPage\n ? getPartialPageVaryPath(tree.varyPath)\n : getPartialLayoutVaryPath(tree.varyPath)\n\n let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null\n const transportChildren = node.c\n const baseChildren =\n inheritedBase !== undefined ? inheritedBase[1] : undefined\n if (transportChildren !== undefined) {\n for (const [parallelRouteKey, childNode] of transportChildren) {\n const childBase =\n baseChildren !== undefined ? baseChildren[parallelRouteKey] : undefined\n const childSegment = transportSegmentToSegment(childNode.s)\n\n let childCompareBase: FlightRouterState | undefined\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n const childCompareCandidate = compareBase[1][parallelRouteKey]\n if (childCompareCandidate === undefined) {\n // A slot the base tree doesn't have. Unless the server merely\n // filled it with a default, the trees have different structures.\n if (childSegment !== DEFAULT_SEGMENT_KEY) {\n acc.treeDivergedFromBase = true\n }\n } else if ((childCompareCandidate[2] ?? null) !== null) {\n // The base branch carries a refresh state: an inactive parallel\n // route reused from a different route (e.g. a \"default\" slot). The\n // server's answer is expected to differ, so skip the branch.\n } else {\n childCompareBase = childCompareCandidate\n }\n }\n\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childSegment)\n )\n const childTree = decodeTransportNode(\n childNode,\n childBase,\n childCompareBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n if (baseChildren !== undefined) {\n // Slots the response carries no information about are reused from the\n // base tree, structure-only.\n for (const parallelRouteKey in baseChildren) {\n if (\n transportChildren !== undefined &&\n transportChildren.has(parallelRouteKey)\n ) {\n continue\n }\n const childBase = baseChildren[parallelRouteKey]\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childBase[0])\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n\n if (inheritsFromBase) {\n // Recompute the propagated \"subtree\" prefetch hints for this segment,\n // since its children may combine response and base subtrees. Mirrors the\n // propagation done on the server in createTransportTreeFromLoaderTree.\n let propagated = prefetchHints & ~SubtreePrefetchHints\n if (slots !== null) {\n for (const childTree of slots.values()) {\n propagated = propagateSubtreeBits(propagated, childTree.prefetchHints)\n }\n }\n prefetchHints = propagated\n }\n\n if (nodeData !== undefined) {\n tree.data = {\n rsc: nodeData.r,\n isPartial: nodeData.p,\n varyParams: nodeData.v,\n }\n }\n\n tree.slots = slots\n tree.prefetchHints = prefetchHints\n return tree\n}\n"],"names":["PrefetchHint","SubtreePrefetchHints","propagateSubtreeBits","transportSegmentToSegment","ROOT_SEGMENT_REQUEST_KEY","appendSegmentRequestKeyPart","createSegmentRequestKeyPart","DEFAULT_SEGMENT_KEY","PAGE_SEGMENT_KEY","matchSegment","appendLayoutVaryPath","finalizeLayoutVaryPath","finalizeMetadataVaryPath","finalizePageVaryPath","getPartialLayoutVaryPath","getPartialPageVaryPath","getShellSegmentVaryPath","convertFlightRouterStateToRouteTree","convertRootFlightRouterStateToRouteTree","computeDynamicStaleAt","convertServerPatchToFullTree","now","currentTree","transportData","renderedSearch","dynamicStaleTimeSeconds","acc","metadataVaryPath","treeDivergedFromBase","routeTree","head","isHeadPartial","headVaryParams","decodeTransportTreeIntoRouteTree","t","transportHead","h","undefined","r","p","v","dynamicStaleAt","createRouteTreeNode","originalSegment","isRootParam","requestKey","parentPartialVaryPath","segment","partialVaryPath","isPage","varyPath","Array","isArray","paramCacheKey","paramName","endsWith","shellVaryPath","refreshState","data","slots","prefetchHints","transportNode","baseRouterState","decodeTransportNode","node","base","compareBase","parentRenderedSearch","nodeData","d","inheritsFromBase","inheritedBase","s","transportSegment","k","baseSegment","startsWith","baseHints","IsRootLayoutOrAbove","baseCompressedRefreshState","canonicalUrl","tree","transportChildren","c","baseChildren","parallelRouteKey","childNode","childBase","childSegment","childCompareBase","childCompareCandidate","childRequestKey","childTree","Map","set","has","propagated","values","rsc","isPartial","varyParams"],"mappings":"AAAA;;;;;CAKC,GAOD,SACEA,YAAY,EACZC,oBAAoB,EACpBC,oBA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9B,SAAS9B,CAAC;YACf6D,WAAW/B,SAAS7B,CAAC;YACrB6D,YAAYhC,SAAS5B,CAAC;QACxB;IACF;IAEAyC,KAAKtB,KAAK,GAAGA;IACbsB,KAAKrB,aAAa,GAAGA;IACrB,OAAOqB;AACT","ignoreList":[0]}

@@ -188,3 +188,5 @@ import { PrefetchHint } from '../../../shared/lib/app-router-types';

headVaryParams: null,
dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime)
dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),
// Not derived from a server response; no base to diverge from.
treeDivergedFromBase: false
};

@@ -191,0 +193,0 @@ return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, null, route, // Not an HMR refresh, so there's no request generation to cancel.

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport type { CacheMap } from './cache-map'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n map\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n scrollRef: state.scrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["PrefetchHint","fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","beginLockedNavigation","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","segmentCacheMap","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","resolveStaleAt","writePrerenderResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","createLinkPrefetchPartialError","convertServerPatchToFullTree","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","map","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","fetchStrategy","Full","routeTree","prefetchHints","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","metadataVaryPath","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","search","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","t","r","processed","PPRRuntime","rootVaryParamsIterable","revealAfter","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","promise","updateCapturedSPAToTree"],"mappings":"AAKA,SAASA,YAAY,QAAQ,uCAAsC;AACnE,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,eAAe,EACfC,qBAAqB,QAGhB,oCAAmC;AAC1C,SAASC,iBAAiB,QAAQ,yCAAwC;AAC1E,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,WAAW,EACXC,eAAe,EAEfC,mBAAmB,EACnBC,2CAA2C,EAC3CC,cAAc,EACdC,+BAA+B,EAC/BC,4BAA4B,EAC5BC,mCAAmC,QAE9B,UAA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C,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC,EAChCC,cAAqC;IAErC,MAAM8B,OAAOjD;IACb,MAAMkD,gBAAgBD,SAAS,OAAOA,KAAKC,aAAa,GAAGnD,cAAcmE,GAAG;IAE5E,MAAMnC,WAAWnC,eAAec,IAAIoB,IAAI,EAAEf;IAE1C,6EAA6E;IAC7E,uEAAuE;IACvE,2EAA2E;IAC3E,uEAAuE;IACvE,uCAAuC;IACvC,MAAM,EAAEoI,2BAA2B,EAAE,GACnC3H,QAAQ;IACV,MAAM4H,yBAAyBD;IAC/B,MAAME,eAAexJ,qBACnBkC,UACAjB,0BACAoC,eACApD,iBAAiB2F,OAAO,EACxB,MACA2D;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBE,OAAO;IACtC;IAEA,uEAAuE;IACvE,2EAA2E;IAC3E,2EAA2E;IAC3E,2EAA2E;IAC3E,+BAA+B;IAC/B,MAAMtD,SAAS,MAAMtE,aACnBjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC,gBACAkI,aAAajK,eAAe;IAG9B,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAAC4G,OAAO6B,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAEwB,uBAAuB,EAAE,GAC/B/H,QAAQ;QACV+H,wBAAwBzI,0BAA0BkF,OAAOhB,IAAI;IAC/D;IAEA,OAAOgB;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport type { CacheMap } from './cache-map'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n // Not derived from a server response; no base to diverge from.\n treeDivergedFromBase: false,\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n map\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n scrollRef: state.scrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["PrefetchHint","fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","beginLockedNavigation","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","segmentCacheMap","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","resolveStaleAt","writePrerenderResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","createLinkPrefetchPartialError","convertServerPatchToFullTree","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","map","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","fetchStrategy","Full","routeTree","prefetchHints","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","metadataVaryPath","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","treeDivergedFromBase","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","search","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","t","r","processed","PPRRuntime","rootVaryParamsIterable","revealAfter","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","promise","updateCapturedSPAToTree"],"mappings":"AAKA,SAASA,YAAY,QAAQ,uCAAsC;AACnE,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,eAAe,EACfC,qBAAqB,QAGhB,oCAAmC;AAC1C,SAASC,iBAAiB,QAAQ,yCAAwC;AAC1E,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,WAAW,EACXC,eAAe,EAEfC,mBAAmB,EACnBC,2CAA2C,EAC3CC,cAAc,EACdC,+BAA+B,EAC/BC,4BAA4B,EAC5BC,mCAAmC,QAE9B,UAAS;AAChB,SAASC,kBAAkB,QAAQ,sBAAqB;AACxD,SAASC,cAAc,QAA+B,cAAa;AAEnE,SAASC,oBAAoB,QAAQ,cAAa;AAClD,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,UAAS;AACzD,SAASC,2BAA2B,QAAQ,WAAU;AAEtD,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,qBAAqB,QAAQ,2BAA0B;AAChE,SAASC,uBAAuB,EAAEC,qBAAqB,QAAQ,YAAW;AAC1E,SAASC,8BAA8B,QAAQ,uCAAsC;AACrF,SACEC,4BAA4B,QAEvB,2BAA0B;AAEjC;;;;;;;CAOC,GACD,OAAO,SAASC,SACdC,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC;IAEhC,IAAIC,iBAAwC;IAE5C,oEAAoE;IACpE,0EAA0E;IAC1E,wEAAwE;IACxE,sEAAsE;IACtE,6DAA6D;IAC7D,aAAa;IACb,IAAIC,QAAQC,GAAG,CAACC,yBAAyB,EAAE;Q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ACAC,cACAC,gBACAmI,aAAalK,eAAe;IAG9B,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAAC6G,OAAO6B,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAEwB,uBAAuB,EAAE,GAC/BhI,QAAQ;QACVgI,wBAAwB1I,0BAA0BmF,OAAOjB,IAAI;IAC/D;IAEA,OAAOiB;AACT","ignoreList":[0]}

@@ -47,3 +47,3 @@ /**

import { isValueExpired } from './cache-map';
import { doesStaticSegmentAppearInURL } from '../../route-params';
import { canonicalizeURLPart, doesStaticSegmentAppearInURL } from '../../route-params';
import { splitPathnameIntoParts } from './cache-key';

@@ -76,3 +76,4 @@ import { appendLayoutVaryPath, finalizeLayoutVaryPath, finalizePageVaryPath, finalizeMetadataVaryPath, getShellSegmentVaryPath } from './vary-path';

dynamicChildParamType: null,
pattern: null
pattern: null,
hasConflictingDynamicChildren: false
};

@@ -130,5 +131,7 @@ }

/**
* Gets or creates the dynamic child node for a KnownRoutePart.
* A node can have at most one dynamic child (you can't have both [slug] and
* [id] at the same route level), so we either return existing or create new.
* Gets or creates the dynamic child node for a KnownRoutePart. A node can
* have at most one dynamic child. Sibling filesystem routes can't declare two
* different params at the same level, but parallel route branches can (e.g.
* @modal/[...catchAll] alongside [username]) — the caller detects that case
* and marks the level as conflicted instead of calling this.
*/ function discoverDynamicChild(part, paramName, paramType) {

@@ -192,2 +195,3 @@ if (part.dynamicChild !== null) {

const paramName = segment[0];
const paramCacheKey = segment[1];
const paramType = segment[2];

@@ -207,2 +211,51 @@ const staticSiblings = segment[3];

}
// The param's cache key holds the value parsed from the *rendered*
// pathname. If the URL part(s) this segment would consume don't equal
// that value, the response was rewrite-affected in a way that shifts
// which URL part maps to which segment (e.g. a proxy injected a leading
// locale segment). A static segment catches this above by failing to
// match its URL part; a dynamic segment consumes whatever part is in
// front of it, so compare against the rendered value instead. Bail out.
switch(paramType){
case 'd':
{
// Canonicalize the URL part to the same encoded form the server used
// for the cache key.
if (urlPart !== null && canonicalizeURLPart(urlPart) !== paramCacheKey) {
return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);
}
break;
}
case 'c':
case 'oc':
{
// Catch-alls consume every remaining URL part; their cache keys are
// the rendered parts joined with '/' (empty string for an empty
// optional catch-all). Comparing the joined remainder also catches a
// rewrite that appended segments the URL doesn't have.
const joinedRemainingParts = pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/');
if (joinedRemainingParts !== paramCacheKey) {
return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);
}
break;
}
case 'ci(..)(..)':
case 'ci(.)':
case 'ci(..)':
case 'ci(...)':
case 'di(..)(..)':
case 'di(.)':
case 'di(..)':
case 'di(...)':
break;
default:
paramType;
}
if (parentKnownRoutePart.hasConflictingDynamicChildren || parentKnownRoutePart.dynamicChild !== null && (parentKnownRoutePart.dynamicChildParamName !== paramName || parentKnownRoutePart.dynamicChildParamType !== paramType)) {
// A different parallel route branch already claimed the dynamic child
// at this level with a different param. Mark the level as conflicted
// so matching bails out, and don't store a pattern via this branch.
parentKnownRoutePart.hasConflictingDynamicChildren = true;
return handleMismatchDueToRewrite(existingEntry, now, pathname, search, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);
}
// URL matches route structure. Build the known route tree.

@@ -421,4 +474,6 @@ knownRoutePart = discoverDynamicChild(parentKnownRoutePart, paramName, paramType);

}
// Try dynamic child
if (part.dynamicChild !== null) {
// Try dynamic child. Skip it entirely if parallel route branches disagree
// about the dynamic segment at this level — any pattern stored beneath it
// was learned under a conflicting model.
if (part.dynamicChild !== null && !part.hasConflictingDynamicChildren) {
const dynamicPart = part.dynamicChild;

@@ -425,0 +480,0 @@ const paramName = part.dynamicChildParamName;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/client/components/segment-cache/optimistic-routes.ts"],"sourcesContent":["/**\n * Optimistic Routing (Known Routes)\n *\n * This module enables the client to predict route structure for URLs that\n * haven't been prefetched yet, based on previously learned route patterns.\n * When successful, this allows skipping the route tree prefetch request\n * entirely.\n *\n * The core idea is that many URLs map to the same route structure. For example,\n * /blog/post-1 and /blog/post-2 both resolve to /blog/[slug]. Once we've\n * prefetched one, we can predict the structure of the other.\n *\n * However, we can't always make this prediction. Static siblings (like\n * /blog/featured alongside /blog/[slug]) have different route structures.\n * When we learn a dynamic route, we also learn its static siblings so we\n * know when NOT to apply the prediction.\n *\n * Main entry points:\n *\n * 1. discoverKnownRoute: Called after receiving a route tree from the server.\n * Traverses the route tree, compares URL parts to segments, and populates\n * the known route tree if they match. Routes are always inserted into the\n * cache.\n *\n * 2. matchKnownRoute: Called when looking up a route with no cache entry.\n * Matches the candidate URL against learned patterns. Returns a synthetic\n * cache entry if successful, or null to fall back to server resolution.\n *\n * Rewrite detection happens during traversal: if a URL path part doesn't match\n * the corresponding route segment, we stop populating the known route tree\n * (since the mapping is incorrect) but still insert the route into the cache.\n *\n * The known route tree is append-only with no eviction. Route patterns are\n * derived from the filesystem, so they don't become stale within a session.\n * Cache invalidation on deploy clears everything anyway.\n *\n * Current limitations (deopt to server resolution):\n * - Rewrites: Detected during traversal (tree not populated, but route cached)\n * - Intercepted routes: The route tree varies by referrer (Next-Url header),\n * so we can't predict the correct structure from the URL alone. Patterns are\n * still stored during discovery (so the trie stays populated for non-\n * intercepted siblings), but matching bails out when the pattern is marked\n * as interceptable.\n */\n\nimport type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport type {\n RouteTree,\n RSCSegmentData,\n FulfilledRouteCacheEntry,\n} from './cache'\nimport {\n EntryStatus,\n writeRouteIntoCache,\n fulfillRouteCacheEntry,\n getCurrentRouteCacheVersion,\n type PendingRouteCacheEntry,\n createMetadataRouteTree,\n} from './cache'\nimport { isValueExpired } from './cache-map'\nimport { doesStaticSegmentAppearInURL } from '../../route-params'\nimport type { NormalizedPathname, NormalizedSearch } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n finalizeMetadataVaryPath,\n getShellSegmentVaryPath,\n type PartialSegmentVaryPath,\n type PageVaryPath,\n} from './vary-path'\n\n/**\n * The known route tree is analogous to a route table. A different routing\n * implementation might use regexes or URLPattern; ours uses a trie indexed\n * by URL path segments.\n *\n * Each node (KnownRoutePart) represents a position in the URL and can have:\n * - staticChildren: Map of literal segments to child nodes\n * - dynamicChild: A single dynamic segment node ([slug], [...params], etc.)\n * - pattern: A cache entry template for routes that terminate here\n *\n * This tree only contains segments that correspond to actual filesystem routes.\n * Route groups like (marketing) and parallel routes like @modal are not\n * included since they don't appear in URLs. Similarly, if a URL is rewritten\n * to a different filesystem path, the original URL segments don't appear here\n * — only the resolved filesystem route structure is stored.\n *\n * Example tree after learning /blog/[slug], /blog/featured, and /about:\n *\n * ├── about\n * └── blog\n * ├── featured\n * └── [slug]\n *\n * When matching /blog/hello:\n * 1. \"blog\" matches static child\n * 2. \"hello\" doesn't match \"featured\", falls through to [slug]\n * 3. Returns [slug]'s pattern with resolved param { slug: \"hello\" }\n */\ntype KnownRoutePartBase = {\n // Known static paths at this level. The null vs Map distinction is\n // semantically meaningful:\n // - null: Static siblings are UNKNOWN at this level (e.g., webpack dev mode\n // where routes are compiled on-demand). If there's a dynamicChild, we\n // can't safely match it because the URL might be an unknown static sibling.\n // - Map (even if empty): Static siblings are KNOWN. We can safely match a\n // dynamicChild if the URL doesn't match any entry in the Map.\n staticChildren: Map<string, KnownRoutePart> | null\n\n // The cache entry that serves as a pattern for this route.\n // When a URL matches, we clone this and substitute param values.\n // null means we know this path exists (from static siblings) but haven't\n // learned its structure yet.\n pattern: FulfilledRouteCacheEntry | null\n\n // TODO: For prefix rewrite support. When true, this part may not appear in\n // the candidate URL because it was injected by a rewrite.\n // mayBeSkippedInURL: boolean\n}\n\n// The dynamic child fields are structured as a union so that narrowing on\n// dynamicChild also narrows dynamicChildParamName and dynamicChildParamType.\ntype KnownRoutePartWithoutDynamicChild = KnownRoutePartBase & {\n dynamicChild: null\n dynamicChildParamName: null\n dynamicChildParamType: null\n}\n\ntype KnownRoutePartWithDynamicChild = KnownRoutePartBase & {\n dynamicChild: KnownRoutePart\n dynamicChildParamName: string\n dynamicChildParamType: DynamicParamTypesShort\n}\n\ntype KnownRoutePart =\n | KnownRoutePartWithoutDynamicChild\n | KnownRoutePartWithDynamicChild\n\n/**\n * Param values extracted during URL matching. Used to reify the template.\n * Values are always strings: catch-all [...param] and optional catch-all\n * [[...param]] values are joined with '/' at the time they're resolved, which\n * matches how the rest of the system models catch-all cache keys (an empty\n * optional catch-all is the empty string). Keeping a single value type keeps\n * reads of this map monomorphic.\n */\ntype ResolvedParams = Map<string, string>\n\n/**\n * Read the pattern from a KnownRoutePart, evicting it if expired.\n *\n * This prevents stale patterns (e.g. from InliningHintsStale route entries\n * with staleAt = -1) from being cloned into synthetic entries indefinitely.\n * Once evicted, the pattern slot can be repopulated by the next\n * discoverKnownRoute call with a fresh entry from a /_tree response.\n */\nfunction readPattern(\n now: number,\n part: KnownRoutePart\n): FulfilledRouteCacheEntry | null {\n const pattern = part.pattern\n if (pattern === null) {\n return null\n }\n if (isValueExpired(now, getCurrentRouteCacheVersion(), pattern)) {\n // The pattern is expired. Null it out so the slot can be repopulated.\n part.pattern = null\n return null\n }\n return pattern\n}\n\nfunction createEmptyPart(): KnownRoutePart {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n }\n}\n\n// The root of the known route tree.\nlet knownRouteTreeRoot: KnownRoutePart = createEmptyPart()\n\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the route entry is marked as having a\n * dynamic rewrite, which prevents it from being used as a template for future\n * predictions. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */\nexport function discoverKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n pendingEntry: PendingRouteCacheEntry | null,\n routeTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const tree = routeTree\n\n const pathnameParts = splitPathnameIntoParts(pathname)\n\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n if (hasDynamicRewrite) {\n fulfilledEntry.hasDynamicRewrite = true\n }\n // Populate the known route tree (handles rewrite detection internally).\n // The entry is already in the cache; this just stores it as a pattern\n // if the URL matches the route structure.\n discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n fulfilledEntry,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n return fulfilledEntry\n }\n\n // No pending entry - discoverKnownRoutePart will create one and insert it\n // into the cache, or return an existing pattern if one exists.\n return discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n null,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n}\n\n/**\n * Bail out of populating the known route tree when discovery detects that the\n * URL doesn't match the route structure (a rewrite). The route entry is still\n * inserted into the cache for direct lookup — we just don't store it as a\n * pattern, since the URL and the tree describe different shapes.\n */\nfunction handleMismatchDueToRewrite(\n existingEntry: FulfilledRouteCacheEntry | null,\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n}\n\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart.\n * A node can have at most one dynamic child (you can't have both [slug] and\n * [id] at the same route level), so we either return existing or create new.\n */\nfunction discoverDynamicChild(\n part: KnownRoutePart,\n paramName: string,\n paramType: DynamicParamTypesShort\n): KnownRoutePart {\n if (part.dynamicChild !== null) {\n return part.dynamicChild\n }\n const newChild = createEmptyPart()\n // Type assertion needed because we're converting from \"without\" to \"with\"\n // dynamic child variant.\n const mutablePart = part as unknown as KnownRoutePartWithDynamicChild\n mutablePart.dynamicChild = newChild\n mutablePart.dynamicChildParamName = paramName\n mutablePart.dynamicChildParamType = paramType\n return newChild\n}\n\n/**\n * Recursive workhorse for discoverKnownRoute.\n *\n * Walks the route tree and URL parts in parallel, building out the known\n * route tree as it goes. At each step:\n * 1. Determines if the current segment appears in the URL (dynamic/static)\n * 2. Validates URL matches route structure (detects rewrites)\n * 3. Creates/updates the corresponding KnownRoutePart node\n * 4. Records static siblings for future matching\n * 5. Recurses into child slots (parallel routes)\n *\n * If a URL/route mismatch is detected (rewrite), we stop building the known\n * route tree but still cache the route entry for direct lookup.\n */\nfunction discoverKnownRoutePart(\n parentKnownRoutePart: KnownRoutePart,\n routeTree: RouteTree<RSCSegmentData | null>,\n pathnameParts: readonly string[],\n partIndex: number,\n existingEntry: FulfilledRouteCacheEntry | null,\n // These are passed through unchanged for entry creation at the leaf\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const segment = routeTree.segment\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n let knownRoutePart: KnownRoutePart = parentKnownRoutePart\n let nextPartIndex = partIndex\n\n if (typeof segment === 'string') {\n if (doesStaticSegmentAppearInURL(segment)) {\n // A visible static segment must consume exactly one URL part that\n // equals the segment. If the URL is exhausted or the URL part doesn't\n // match, the URL doesn't fit the route shape — the response was\n // rewrite-affected. Bail out.\n if (urlPart === null || urlPart !== segment) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart)\n if (existingChild === undefined) {\n existingChild = createEmptyPart()\n parentKnownRoutePart.staticChildren.set(urlPart, existingChild)\n }\n knownRoutePart = existingChild\n\n // Advance to next URL part.\n nextPartIndex = partIndex + 1\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n const paramName: string = segment[0]\n const paramType: DynamicParamTypesShort = segment[2]\n const staticSiblings: readonly string[] | null = segment[3]\n\n if (paramType !== 'oc' && urlPart === null) {\n // Every dynamic segment except the optional catch-all (`[[...param]]`)\n // must consume at least one URL part at runtime. If discovery reached\n // this segment with no URL parts left to consume, the URL doesn't fit\n // the route shape — the response was rewrite-affected. Bail out.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (\n staticSiblings !== null &&\n urlPart !== null &&\n staticSiblings.includes(urlPart)\n ) {\n // The route tree says this is a dynamic sibling, but the canonical URL\n // is a known static sibling. This is a mismatch.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // URL matches route structure. Build the known route tree.\n knownRoutePart = discoverDynamicChild(\n parentKnownRoutePart,\n paramName,\n paramType\n )\n\n // Record static siblings as placeholder parts.\n // IMPORTANT: We use the null vs Map distinction to track whether\n // siblings are known at this level:\n // - staticChildren: null = siblings unknown (can't safely match dynamic)\n // - staticChildren: Map = siblings known (even if empty)\n // This matters in dev mode where webpack may not know all siblings yet.\n if (staticSiblings !== null) {\n // Siblings are known - ensure we have a Map (even if empty)\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n for (const sibling of staticSiblings) {\n if (!parentKnownRoutePart.staticChildren.has(sibling)) {\n parentKnownRoutePart.staticChildren.set(sibling, createEmptyPart())\n }\n }\n }\n\n // Advance to next URL part. Catch-all segments (`[...param]` and\n // `[[...param]]`) absorb every remaining URL part at runtime (see\n // `matchKnownRoutePart`, which slices the rest of `pathnameParts`).\n if (paramType === 'c' || paramType === 'oc') {\n nextPartIndex = pathnameParts.length\n } else {\n nextPartIndex = partIndex + 1\n }\n }\n\n // Recurse into child routes. A route tree can have multiple parallel routes\n // (e.g., @modal alongside children). Each parallel route is a separate\n // branch, but they all share the same URL - we just need to traverse all\n // branches to build out the known route tree.\n const slots = routeTree.slots\n let resultFromChildren: FulfilledRouteCacheEntry | null = null\n if (slots !== null) {\n for (const childRouteTree of slots.values()) {\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue\n }\n const result = discoverKnownRoutePart(\n knownRoutePart,\n childRouteTree,\n pathnameParts,\n nextPartIndex,\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result\n }\n if (resultFromChildren !== null) {\n return resultFromChildren\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node (`__PAGE__` leaf). If there are still URL parts\n // left to consume, the route tree is shorter than the URL, which means\n // the URL doesn't match the route structure (likely a rewrite).\n if (nextPartIndex < pathnameParts.length) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node. Create/get the route cache entry and store as a\n // pattern. First, check if there's already a pattern for this route.\n const existingPattern = readPattern(now, knownRoutePart)\n if (existingPattern !== null) {\n // If this route has a dynamic rewrite, mark the existing pattern.\n if (hasDynamicRewrite) {\n existingPattern.hasDynamicRewrite = true\n }\n return existingPattern\n }\n\n // Get or create the entry\n let entry: FulfilledRouteCacheEntry\n if (existingEntry !== null) {\n // Already have a fulfilled entry, use it directly. It's already in the\n // route cache map.\n entry = existingEntry\n } else {\n // Create the entry and insert it into the route cache map.\n entry = writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (hasDynamicRewrite) {\n entry.hasDynamicRewrite = true\n }\n\n // Store as pattern\n knownRoutePart.pattern = entry\n return entry\n}\n\n/**\n * Attempts to match a URL against learned route patterns.\n *\n * Returns a synthetic FulfilledRouteCacheEntry if the URL matches a known\n * pattern, or null if no match is found (fall back to server resolution).\n */\nexport function matchKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch\n): FulfilledRouteCacheEntry | null {\n const pathnameParts = splitPathnameIntoParts(pathname)\n const resolvedParams: ResolvedParams = new Map()\n const match = matchKnownRoutePart(\n now,\n knownRouteTreeRoot,\n pathnameParts,\n 0,\n resolvedParams\n )\n\n if (match === null) {\n return null\n }\n\n const matchedPart = match.part\n const pattern = match.pattern\n\n // If the pattern could be intercepted, we can't safely use it for prediction.\n // Interception routes resolve to different route trees depending on the\n // referrer (the Next-Url header), which means the same URL can map to\n // different page components depending on where the navigation originated.\n // Since the known route tree only stores a single pattern per URL shape, we\n // can't distinguish between the intercepted and non-intercepted cases, so we\n // bail out to server resolution.\n //\n // TODO: We could store interception behavior in the known route tree itself\n // (e.g., which segments use interception markers and what they resolve to).\n // With enough information embedded in the trie, we could match interception\n // routes entirely on the client without a server round-trip.\n if (pattern.couldBeIntercepted) {\n return null\n }\n\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const acc: ReifyAccumulator = { metadataVaryPath: null }\n const reifiedTree = reifyRouteTree(\n pattern.tree,\n resolvedParams,\n search,\n null, // Start with null partial vary path at the root\n acc\n )\n\n // The metadata tree is a flat page node without the intermediate layout\n // structure. Clone it with the updated metadata vary path collected during\n // the main tree traversal.\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n // This shouldn't be reachable for a valid route tree.\n return null\n }\n const reifiedMetadata = createMetadataRouteTree(metadataVaryPath)\n\n // Create a synthetic (predicted) entry and store it as the new pattern.\n //\n // Why replace the pattern? We intentionally update the pattern with this\n // synthetic entry so that if our prediction was wrong (server returns a\n // different pathname due to dynamic rewrite), the entry gets marked with\n // hasDynamicRewrite. Future predictions for this route will see the flag\n // and bail out to server resolution instead of making the same mistake.\n const syntheticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n tree: reifiedTree,\n metadata: reifiedMetadata,\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n hasDynamicRewrite: false,\n renderedSearch: search,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version,\n }\n\n matchedPart.pattern = syntheticEntry\n\n return syntheticEntry\n}\n\n/**\n * Result of a successful match: the matched tree node and its pattern.\n * We return both because the caller needs to update the pattern after\n * creating a synthetic entry (for dynamic rewrite detection).\n */\ntype KnownRouteMatch = {\n part: KnownRoutePart\n pattern: FulfilledRouteCacheEntry\n} | null\n\n/**\n * Recursively matches a URL against the known route tree.\n *\n * Matching priority (most specific first):\n * 1. Static children - exact path segment match\n * 2. Dynamic child - [param], [...param], [[...param]]\n * 3. Direct pattern - when no more URL parts remain\n *\n * Collects resolved param values in resolvedParams as it traverses.\n * Returns null if no match found (caller should fall back to server).\n */\nfunction matchKnownRoutePart(\n now: number,\n part: KnownRoutePart,\n pathnameParts: string[],\n partIndex: number,\n resolvedParams: ResolvedParams\n): KnownRouteMatch {\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n return null\n }\n\n // Static children take priority over dynamic. This ensures /blog/featured\n // matches its own route rather than /blog/[slug].\n if (urlPart !== null) {\n const staticChild = part.staticChildren.get(urlPart)\n if (staticChild !== undefined) {\n // Check if this is an \"unknown\" placeholder part. These are created when\n // we learn about static siblings (from the route tree's staticSiblings\n // field) but haven't prefetched them yet. We know the path exists but\n // don't know its structure, so we can't predict it.\n if (\n staticChild.pattern === null &&\n staticChild.dynamicChild === null &&\n staticChild.staticChildren === null\n ) {\n // Bail out - server must resolve this route.\n return null\n }\n const match = matchKnownRoutePart(\n now,\n staticChild,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n if (match !== null) {\n return match\n }\n // Static child is a real node (not a placeholder) but its subtree\n // didn't match the remaining URL parts. This means the route exists\n // in the static subtree but hasn't been fully discovered yet. Do not\n // fall through to try the dynamic child — the static match is\n // authoritative. Bail out to server resolution.\n return null\n }\n }\n\n // Try dynamic child\n if (part.dynamicChild !== null) {\n const dynamicPart = part.dynamicChild\n const paramName = part.dynamicChildParamName\n const paramType = part.dynamicChildParamType\n const dynamicPattern = readPattern(now, dynamicPart)\n\n switch (paramType) {\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (\n dynamicPattern !== null &&\n !dynamicPattern.hasDynamicRewrite &&\n urlPart !== null\n ) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n break\n case 'oc': {\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) {\n if (urlPart !== null) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n const directPattern = readPattern(now, part)\n if (directPattern === null || directPattern.hasDynamicRewrite) {\n resolvedParams.set(paramName, '')\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n }\n break\n }\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, urlPart)\n return matchKnownRoutePart(\n now,\n dynamicPart,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n }\n break\n // Intercepted routes use relative path markers like (.), (..), (...)\n // Their behavior depends on navigation context (soft vs hard nav),\n // so we can't predict them client-side. Defer to server.\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n return null\n default:\n paramType satisfies never\n }\n }\n\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n\n return null\n}\n\n/**\n * Accumulator for collecting data during reifyRouteTree traversal.\n * metadataVaryPath is collected from the first page node encountered\n * (parallel routes may have multiple pages, but metadata uses the first).\n */\ntype ReifyAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\n/**\n * \"Reify\" means to make concrete - we take an abstract pattern (the template\n * route tree) and produce a concrete instance with actual param values.\n *\n * This function clones a RouteTree, substituting dynamic segment values from\n * resolvedParams and computing new vary paths. The vary path encodes param\n * values so segment cache entries can be correctly keyed.\n *\n * Example: Pattern for /blog/[slug] with resolvedParams { slug: \"hello\" }\n * produces a tree where segment [slug] has cacheKey \"hello\".\n */\nfunction reifyRouteTree(\n pattern: RouteTree<null>,\n resolvedParams: ResolvedParams,\n search: NormalizedSearch,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n acc: ReifyAccumulator\n): RouteTree<null> {\n const originalSegment = pattern.segment\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam =\n (pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n let newSegment = originalSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const newValue = resolvedParams.get(paramName)\n if (newValue !== undefined) {\n // Catch-all values are already joined into a single string when they're\n // resolved in matchKnownRoutePart, so the value can be used directly.\n const newCacheKey = newValue\n newSegment = [paramName, newCacheKey, paramType, staticSiblings]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n newCacheKey,\n paramName,\n isRootParam\n )\n } else {\n // Param not found in resolvedParams - keep original and inherit partial\n // TODO: This should never happen. Bail out with null.\n partialVaryPath = parentPartialVaryPath\n }\n } else {\n // Static segment: inherit partial vary path from parent\n partialVaryPath = parentPartialVaryPath\n }\n\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots: Map<string, RouteTree<null>> | null = null\n const patternSlots = pattern.slots\n if (patternSlots !== null) {\n newSlots = new Map()\n for (const [key, childPattern] of patternSlots) {\n newSlots.set(\n key,\n reifyRouteTree(\n childPattern,\n resolvedParams,\n search,\n partialVaryPath,\n acc\n )\n )\n }\n }\n\n if (pattern.isPage) {\n // Page segment: finalize with search params\n const newVaryPath = finalizePageVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n // Collect metadata vary path (first page wins, same as original algorithm)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n // Route cache patterns never carry seed data (see\n // stripDataFromRouteTree), so neither do trees reified from them.\n data: null,\n varyPath: newVaryPath,\n isPage: true,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n } else {\n // Layout segment: finalize without search params\n const newVaryPath = finalizeLayoutVaryPath(\n pattern.requestKey,\n partialVaryPath\n )\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n data: null,\n varyPath: newVaryPath,\n isPage: false,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n }\n}\n\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */\nexport function resetKnownRoutes(): void {\n knownRouteTreeRoot = createEmptyPart()\n}\n"],"names":["PrefetchHint","EntryStatus","writeRouteIntoCache","fulfillRouteCacheEntry","getCurrentRouteCacheVersion","createMetadataRouteTree","isValueExpired","doesStaticSegmentAppearInURL","splitPathnameIntoParts","appendLayoutVaryPath","finalizeLayoutVaryPath","finalizePageVaryPath","finalizeMetadataVaryPath","getShellSegmentVaryPath","readPattern","now","part","pattern","createEmptyPart","staticChildren","dynamicChild","dynamicChildParamName","dynamicChildParamType","knownRouteTreeRoot","discoverKnownRoute","pathname","search","nextUrl","pendingEntry","routeTree","metadataVaryPath","couldBeIntercepted","canonicalUrl","supportsPerSegmentPrefetching","hasDynamicRewrite","tree","pathnameParts","fulfilledEntry","discoverKnownRoutePart","handleMismatchDueToRewrite","existingEntry","fullTree","discoverDynamicChild","paramName","paramType","newChild","mutablePart","parentKnownRoutePart","partIndex","segment","urlPart","length","knownRoutePart","nextPartIndex","Map","existingChild","get","undefined","set","staticSiblings","includes","sibling","has","slots","resultFromChildren","childRouteTree","values","refreshState","result","existingPattern","entry","matchKnownRoute","resolvedParams","match","matchKnownRoutePart","matchedPart","acc","reifiedTree","reifyRouteTree","reifiedMetadata","syntheticEntry","status","Fulfilled","blockedTasks","metadata","renderedSearch","ref","size","staleAt","version","staticChild","dynamicPart","dynamicPattern","slice","join","directPattern","parentPartialVaryPath","originalSegment","isRootParam","prefetchHints","IsRootLayoutOrAbove","newSegment","partialVaryPath","newValue","newCacheKey","newSlots","patternSlots","key","childPattern","isPage","newVaryPath","requestKey","shellVaryPath","data","varyPath","resetKnownRoutes"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAGD,SAASA,YAAY,QAAQ,uCAAsC;AAMnE,SACEC,WAAW,EACXC,mBAAmB,EACnBC,sBAAsB,EACtBC,2BAA2B,EAE3BC,uBAAuB,QAClB,UAAS;AAChB,SAASC,cAAc,QAAQ,cAAa;AAC5C,SAASC,4BAA4B,QAAQ,qBAAoB;AAEjE,SAASC,sBAAsB,QAAQ,cAAa;AACpD,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,wBAAwB,EACxBC,uBAAuB,QAGlB,cAAa;AA+EpB;;;;;;;CAOC,GACD,SAASC,YACPC,GAAW,EACXC,IAAoB;IAEpB,MAAMC,UAAUD,KAAKC,OAAO;IAC5B,IAAIA,YAAY,MAAM;QACpB,OAAO;IACT;IACA,IAAIX,eAAeS,KAAKX,+BAA+Ba,UAAU;QAC/D,sEAAsE;QACtED,KAAKC,OAAO,GAAG;QACf,OAAO;IACT;IACA,OAAOA;AACT;AAEA,SAASC;IACP,OAAO;QACLC,gBAAgB;QAChBC,cAAc;QACdC,uBAAuB;QACvBC,uBAAuB;QACvBL,SAAS;IACX;AACF;AAEA,oCAAoC;AACpC,IAAIM,qBAAqCL;AAEzC;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASM,mBACdT,GAAW,EACXU,QAAgB,EAChBC,MAAwB,EACxBC,OAAsB,EACtBC,YAA2C,EAC3CC,SAA2C,EAC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qBAClBM,QAAQ8F,UAAU,EAClBrF,QACA4E;QAEF,2EAA2E;QAC3E,IAAI1B,IAAI9C,gBAAgB,KAAK,MAAM;YACjC8C,IAAI9C,gBAAgB,GAAGlB,yBACrBK,QAAQ8F,UAAU,EAClBrF,QACA4E;QAEJ;QACA,OAAO;YACLS,YAAY9F,QAAQ8F,UAAU;YAC9B9D,SAASoD;YACTW,eAAenG,wBAAwBiG;YACvC3C,cAAclD,QAAQkD,YAAY;YAClC,kDAAkD;YAClD,kEAAkE;YAClE8C,MAAM;YACNC,UAAUJ;YACVD,QAAQ;YACR9C,OAAO0C;YACPN,eAAelF,QAAQkF,aAAa;QACtC;IACF,OAAO;QACL,iDAAiD;QACjD,MAAMW,cAAcpG,uBAClBO,QAAQ8F,UAAU,EAClBT;QAEF,OAAO;YACLS,YAAY9F,QAAQ8F,UAAU;YAC9B9D,SAASoD;YACTW,eAAenG,wBAAwBiG;YACvC3C,cAAclD,QAAQkD,YAAY;YAClC8C,MAAM;YACNC,UAAUJ;YACVD,QAAQ;YACR9C,OAAO0C;YACPN,eAAelF,QAAQkF,aAAa;QACtC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,SAASgB;IACd5F,qBAAqBL;AACvB","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/client/components/segment-cache/optimistic-routes.ts"],"sourcesContent":["/**\n * Optimistic Routing (Known Routes)\n *\n * This module enables the client to predict route structure for URLs that\n * haven't been prefetched yet, based on previously learned route patterns.\n * When successful, this allows skipping the route tree prefetch request\n * entirely.\n *\n * The core idea is that many URLs map to the same route structure. For example,\n * /blog/post-1 and /blog/post-2 both resolve to /blog/[slug]. Once we've\n * prefetched one, we can predict the structure of the other.\n *\n * However, we can't always make this prediction. Static siblings (like\n * /blog/featured alongside /blog/[slug]) have different route structures.\n * When we learn a dynamic route, we also learn its static siblings so we\n * know when NOT to apply the prediction.\n *\n * Main entry points:\n *\n * 1. discoverKnownRoute: Called after receiving a route tree from the server.\n * Traverses the route tree, compares URL parts to segments, and populates\n * the known route tree if they match. Routes are always inserted into the\n * cache.\n *\n * 2. matchKnownRoute: Called when looking up a route with no cache entry.\n * Matches the candidate URL against learned patterns. Returns a synthetic\n * cache entry if successful, or null to fall back to server resolution.\n *\n * Rewrite detection happens during traversal: if a URL path part doesn't match\n * the corresponding route segment, we stop populating the known route tree\n * (since the mapping is incorrect) but still insert the route into the cache.\n *\n * The known route tree is append-only with no eviction. Route patterns are\n * derived from the filesystem, so they don't become stale within a session.\n * Cache invalidation on deploy clears everything anyway.\n *\n * Current limitations (deopt to server resolution):\n * - Rewrites: Detected during traversal (tree not populated, but route cached)\n * - Intercepted routes: The route tree varies by referrer (Next-Url header),\n * so we can't predict the correct structure from the URL alone. Patterns are\n * still stored during discovery (so the trie stays populated for non-\n * intercepted siblings), but matching bails out when the pattern is marked\n * as interceptable.\n */\n\nimport type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport type {\n RouteTree,\n RSCSegmentData,\n FulfilledRouteCacheEntry,\n} from './cache'\nimport {\n EntryStatus,\n writeRouteIntoCache,\n fulfillRouteCacheEntry,\n getCurrentRouteCacheVersion,\n type PendingRouteCacheEntry,\n createMetadataRouteTree,\n} from './cache'\nimport { isValueExpired } from './cache-map'\nimport {\n canonicalizeURLPart,\n doesStaticSegmentAppearInURL,\n} from '../../route-params'\nimport type { NormalizedPathname, NormalizedSearch } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n finalizeMetadataVaryPath,\n getShellSegmentVaryPath,\n type PartialSegmentVaryPath,\n type PageVaryPath,\n} from './vary-path'\n\n/**\n * The known route tree is analogous to a route table. A different routing\n * implementation might use regexes or URLPattern; ours uses a trie indexed\n * by URL path segments.\n *\n * Each node (KnownRoutePart) represents a position in the URL and can have:\n * - staticChildren: Map of literal segments to child nodes\n * - dynamicChild: A single dynamic segment node ([slug], [...params], etc.)\n * - pattern: A cache entry template for routes that terminate here\n *\n * This tree only contains segments that correspond to actual filesystem routes.\n * Route groups like (marketing) and parallel routes like @modal are not\n * included since they don't appear in URLs. Similarly, if a URL is rewritten\n * to a different filesystem path, the original URL segments don't appear here\n * — only the resolved filesystem route structure is stored.\n *\n * Example tree after learning /blog/[slug], /blog/featured, and /about:\n *\n * ├── about\n * └── blog\n * ├── featured\n * └── [slug]\n *\n * When matching /blog/hello:\n * 1. \"blog\" matches static child\n * 2. \"hello\" doesn't match \"featured\", falls through to [slug]\n * 3. Returns [slug]'s pattern with resolved param { slug: \"hello\" }\n */\ntype KnownRoutePartBase = {\n // Known static paths at this level. The null vs Map distinction is\n // semantically meaningful:\n // - null: Static siblings are UNKNOWN at this level (e.g., webpack dev mode\n // where routes are compiled on-demand). If there's a dynamicChild, we\n // can't safely match it because the URL might be an unknown static sibling.\n // - Map (even if empty): Static siblings are KNOWN. We can safely match a\n // dynamicChild if the URL doesn't match any entry in the Map.\n staticChildren: Map<string, KnownRoutePart> | null\n\n // The cache entry that serves as a pattern for this route.\n // When a URL matches, we clone this and substitute param values.\n // null means we know this path exists (from static siblings) but haven't\n // learned its structure yet.\n pattern: FulfilledRouteCacheEntry | null\n\n // True when parallel route branches disagree about the dynamic segment at\n // this level — different param name or type, e.g. an @modal/[...catchAll]\n // slot alongside [username]. The trie can only model one dynamic child per\n // level, so prediction below this level would bind one branch's URL parts\n // to another branch's params. Once set, discovery stops storing patterns\n // beneath this level and matching bails out to server resolution.\n //\n // TODO: Consider including conflicting sibling dynamic params in the route\n // tree, like we do for static siblings, and attempting to match both.\n hasConflictingDynamicChildren: boolean\n\n // TODO: For prefix rewrite support. When true, this part may not appear in\n // the candidate URL because it was injected by a rewrite. Today, discovery\n // refuses to store a pattern for such routes (see the cache key comparison\n // in discoverKnownRoutePart); this field would let them be predicted.\n // mayBeSkippedInURL: boolean\n}\n\n// The dynamic child fields are structured as a union so that narrowing on\n// dynamicChild also narrows dynamicChildParamName and dynamicChildParamType.\ntype KnownRoutePartWithoutDynamicChild = KnownRoutePartBase & {\n dynamicChild: null\n dynamicChildParamName: null\n dynamicChildParamType: null\n}\n\ntype KnownRoutePartWithDynamicChild = KnownRoutePartBase & {\n dynamicChild: KnownRoutePart\n dynamicChildParamName: string\n dynamicChildParamType: DynamicParamTypesShort\n}\n\ntype KnownRoutePart =\n | KnownRoutePartWithoutDynamicChild\n | KnownRoutePartWithDynamicChild\n\n/**\n * Param values extracted during URL matching. Used to reify the template.\n * Values are always strings: catch-all [...param] and optional catch-all\n * [[...param]] values are joined with '/' at the time they're resolved, which\n * matches how the rest of the system models catch-all cache keys (an empty\n * optional catch-all is the empty string). Keeping a single value type keeps\n * reads of this map monomorphic.\n */\ntype ResolvedParams = Map<string, string>\n\n/**\n * Read the pattern from a KnownRoutePart, evicting it if expired.\n *\n * This prevents stale patterns (e.g. from InliningHintsStale route entries\n * with staleAt = -1) from being cloned into synthetic entries indefinitely.\n * Once evicted, the pattern slot can be repopulated by the next\n * discoverKnownRoute call with a fresh entry from a /_tree response.\n */\nfunction readPattern(\n now: number,\n part: KnownRoutePart\n): FulfilledRouteCacheEntry | null {\n const pattern = part.pattern\n if (pattern === null) {\n return null\n }\n if (isValueExpired(now, getCurrentRouteCacheVersion(), pattern)) {\n // The pattern is expired. Null it out so the slot can be repopulated.\n part.pattern = null\n return null\n }\n return pattern\n}\n\nfunction createEmptyPart(): KnownRoutePart {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n hasConflictingDynamicChildren: false,\n }\n}\n\n// The root of the known route tree.\nlet knownRouteTreeRoot: KnownRoutePart = createEmptyPart()\n\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the route entry is marked as having a\n * dynamic rewrite, which prevents it from being used as a template for future\n * predictions. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */\nexport function discoverKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n pendingEntry: PendingRouteCacheEntry | null,\n routeTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const tree = routeTree\n\n const pathnameParts = splitPathnameIntoParts(pathname)\n\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n if (hasDynamicRewrite) {\n fulfilledEntry.hasDynamicRewrite = true\n }\n // Populate the known route tree (handles rewrite detection internally).\n // The entry is already in the cache; this just stores it as a pattern\n // if the URL matches the route structure.\n discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n fulfilledEntry,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n return fulfilledEntry\n }\n\n // No pending entry - discoverKnownRoutePart will create one and insert it\n // into the cache, or return an existing pattern if one exists.\n return discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n null,\n now,\n pathname,\n search,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n}\n\n/**\n * Bail out of populating the known route tree when discovery detects that the\n * URL doesn't match the route structure (a rewrite). The route entry is still\n * inserted into the cache for direct lookup — we just don't store it as a\n * pattern, since the URL and the tree describe different shapes.\n */\nfunction handleMismatchDueToRewrite(\n existingEntry: FulfilledRouteCacheEntry | null,\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n}\n\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart. A node can\n * have at most one dynamic child. Sibling filesystem routes can't declare two\n * different params at the same level, but parallel route branches can (e.g.\n * @modal/[...catchAll] alongside [username]) — the caller detects that case\n * and marks the level as conflicted instead of calling this.\n */\nfunction discoverDynamicChild(\n part: KnownRoutePart,\n paramName: string,\n paramType: DynamicParamTypesShort\n): KnownRoutePart {\n if (part.dynamicChild !== null) {\n return part.dynamicChild\n }\n const newChild = createEmptyPart()\n // Type assertion needed because we're converting from \"without\" to \"with\"\n // dynamic child variant.\n const mutablePart = part as unknown as KnownRoutePartWithDynamicChild\n mutablePart.dynamicChild = newChild\n mutablePart.dynamicChildParamName = paramName\n mutablePart.dynamicChildParamType = paramType\n return newChild\n}\n\n/**\n * Recursive workhorse for discoverKnownRoute.\n *\n * Walks the route tree and URL parts in parallel, building out the known\n * route tree as it goes. At each step:\n * 1. Determines if the current segment appears in the URL (dynamic/static)\n * 2. Validates URL matches route structure (detects rewrites)\n * 3. Creates/updates the corresponding KnownRoutePart node\n * 4. Records static siblings for future matching\n * 5. Recurses into child slots (parallel routes)\n *\n * If a URL/route mismatch is detected (rewrite), we stop building the known\n * route tree but still cache the route entry for direct lookup.\n */\nfunction discoverKnownRoutePart(\n parentKnownRoutePart: KnownRoutePart,\n routeTree: RouteTree<RSCSegmentData | null>,\n pathnameParts: readonly string[],\n partIndex: number,\n existingEntry: FulfilledRouteCacheEntry | null,\n // These are passed through unchanged for entry creation at the leaf\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n fullTree: RouteTree<RSCSegmentData | null>,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const segment = routeTree.segment\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n let knownRoutePart: KnownRoutePart = parentKnownRoutePart\n let nextPartIndex = partIndex\n\n if (typeof segment === 'string') {\n if (doesStaticSegmentAppearInURL(segment)) {\n // A visible static segment must consume exactly one URL part that\n // equals the segment. If the URL is exhausted or the URL part doesn't\n // match, the URL doesn't fit the route shape — the response was\n // rewrite-affected. Bail out.\n if (urlPart === null || urlPart !== segment) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart)\n if (existingChild === undefined) {\n existingChild = createEmptyPart()\n parentKnownRoutePart.staticChildren.set(urlPart, existingChild)\n }\n knownRoutePart = existingChild\n\n // Advance to next URL part.\n nextPartIndex = partIndex + 1\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n const paramName: string = segment[0]\n const paramCacheKey: string = segment[1]\n const paramType: DynamicParamTypesShort = segment[2]\n const staticSiblings: readonly string[] | null = segment[3]\n\n if (paramType !== 'oc' && urlPart === null) {\n // Every dynamic segment except the optional catch-all (`[[...param]]`)\n // must consume at least one URL part at runtime. If discovery reached\n // this segment with no URL parts left to consume, the URL doesn't fit\n // the route shape — the response was rewrite-affected. Bail out.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (\n staticSiblings !== null &&\n urlPart !== null &&\n staticSiblings.includes(urlPart)\n ) {\n // The route tree says this is a dynamic sibling, but the canonical URL\n // is a known static sibling. This is a mismatch.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // The param's cache key holds the value parsed from the *rendered*\n // pathname. If the URL part(s) this segment would consume don't equal\n // that value, the response was rewrite-affected in a way that shifts\n // which URL part maps to which segment (e.g. a proxy injected a leading\n // locale segment). A static segment catches this above by failing to\n // match its URL part; a dynamic segment consumes whatever part is in\n // front of it, so compare against the rendered value instead. Bail out.\n switch (paramType) {\n case 'd': {\n // Canonicalize the URL part to the same encoded form the server used\n // for the cache key.\n if (\n urlPart !== null &&\n canonicalizeURLPart(urlPart) !== paramCacheKey\n ) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n break\n }\n case 'c':\n case 'oc': {\n // Catch-alls consume every remaining URL part; their cache keys are\n // the rendered parts joined with '/' (empty string for an empty\n // optional catch-all). Comparing the joined remainder also catches a\n // rewrite that appended segments the URL doesn't have.\n const joinedRemainingParts = pathnameParts\n .slice(partIndex)\n .map(canonicalizeURLPart)\n .join('/')\n if (joinedRemainingParts !== paramCacheKey) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n break\n }\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n // Interception params embed relative markers in their values, and\n // patterns containing them are never used for prediction anyway (see\n // matchKnownRoutePart), so skip the comparison.\n break\n default:\n paramType satisfies never\n }\n\n if (\n parentKnownRoutePart.hasConflictingDynamicChildren ||\n (parentKnownRoutePart.dynamicChild !== null &&\n (parentKnownRoutePart.dynamicChildParamName !== paramName ||\n parentKnownRoutePart.dynamicChildParamType !== paramType))\n ) {\n // A different parallel route branch already claimed the dynamic child\n // at this level with a different param. Mark the level as conflicted\n // so matching bails out, and don't store a pattern via this branch.\n parentKnownRoutePart.hasConflictingDynamicChildren = true\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // URL matches route structure. Build the known route tree.\n knownRoutePart = discoverDynamicChild(\n parentKnownRoutePart,\n paramName,\n paramType\n )\n\n // Record static siblings as placeholder parts.\n // IMPORTANT: We use the null vs Map distinction to track whether\n // siblings are known at this level:\n // - staticChildren: null = siblings unknown (can't safely match dynamic)\n // - staticChildren: Map = siblings known (even if empty)\n // This matters in dev mode where webpack may not know all siblings yet.\n if (staticSiblings !== null) {\n // Siblings are known - ensure we have a Map (even if empty)\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n for (const sibling of staticSiblings) {\n if (!parentKnownRoutePart.staticChildren.has(sibling)) {\n parentKnownRoutePart.staticChildren.set(sibling, createEmptyPart())\n }\n }\n }\n\n // Advance to next URL part. Catch-all segments (`[...param]` and\n // `[[...param]]`) absorb every remaining URL part at runtime (see\n // `matchKnownRoutePart`, which slices the rest of `pathnameParts`).\n if (paramType === 'c' || paramType === 'oc') {\n nextPartIndex = pathnameParts.length\n } else {\n nextPartIndex = partIndex + 1\n }\n }\n\n // Recurse into child routes. A route tree can have multiple parallel routes\n // (e.g., @modal alongside children). Each parallel route is a separate\n // branch, but they all share the same URL - we just need to traverse all\n // branches to build out the known route tree.\n const slots = routeTree.slots\n let resultFromChildren: FulfilledRouteCacheEntry | null = null\n if (slots !== null) {\n for (const childRouteTree of slots.values()) {\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue\n }\n const result = discoverKnownRoutePart(\n knownRoutePart,\n childRouteTree,\n pathnameParts,\n nextPartIndex,\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result\n }\n if (resultFromChildren !== null) {\n return resultFromChildren\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node (`__PAGE__` leaf). If there are still URL parts\n // left to consume, the route tree is shorter than the URL, which means\n // the URL doesn't match the route structure (likely a rewrite).\n if (nextPartIndex < pathnameParts.length) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node. Create/get the route cache entry and store as a\n // pattern. First, check if there's already a pattern for this route.\n const existingPattern = readPattern(now, knownRoutePart)\n if (existingPattern !== null) {\n // If this route has a dynamic rewrite, mark the existing pattern.\n if (hasDynamicRewrite) {\n existingPattern.hasDynamicRewrite = true\n }\n return existingPattern\n }\n\n // Get or create the entry\n let entry: FulfilledRouteCacheEntry\n if (existingEntry !== null) {\n // Already have a fulfilled entry, use it directly. It's already in the\n // route cache map.\n entry = existingEntry\n } else {\n // Create the entry and insert it into the route cache map.\n entry = writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (hasDynamicRewrite) {\n entry.hasDynamicRewrite = true\n }\n\n // Store as pattern\n knownRoutePart.pattern = entry\n return entry\n}\n\n/**\n * Attempts to match a URL against learned route patterns.\n *\n * Returns a synthetic FulfilledRouteCacheEntry if the URL matches a known\n * pattern, or null if no match is found (fall back to server resolution).\n */\nexport function matchKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch\n): FulfilledRouteCacheEntry | null {\n const pathnameParts = splitPathnameIntoParts(pathname)\n const resolvedParams: ResolvedParams = new Map()\n const match = matchKnownRoutePart(\n now,\n knownRouteTreeRoot,\n pathnameParts,\n 0,\n resolvedParams\n )\n\n if (match === null) {\n return null\n }\n\n const matchedPart = match.part\n const pattern = match.pattern\n\n // If the pattern could be intercepted, we can't safely use it for prediction.\n // Interception routes resolve to different route trees depending on the\n // referrer (the Next-Url header), which means the same URL can map to\n // different page components depending on where the navigation originated.\n // Since the known route tree only stores a single pattern per URL shape, we\n // can't distinguish between the intercepted and non-intercepted cases, so we\n // bail out to server resolution.\n //\n // TODO: We could store interception behavior in the known route tree itself\n // (e.g., which segments use interception markers and what they resolve to).\n // With enough information embedded in the trie, we could match interception\n // routes entirely on the client without a server round-trip.\n if (pattern.couldBeIntercepted) {\n return null\n }\n\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const acc: ReifyAccumulator = { metadataVaryPath: null }\n const reifiedTree = reifyRouteTree(\n pattern.tree,\n resolvedParams,\n search,\n null, // Start with null partial vary path at the root\n acc\n )\n\n // The metadata tree is a flat page node without the intermediate layout\n // structure. Clone it with the updated metadata vary path collected during\n // the main tree traversal.\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n // This shouldn't be reachable for a valid route tree.\n return null\n }\n const reifiedMetadata = createMetadataRouteTree(metadataVaryPath)\n\n // Create a synthetic (predicted) entry and store it as the new pattern.\n //\n // Why replace the pattern? We intentionally update the pattern with this\n // synthetic entry so that if our prediction was wrong (server returns a\n // different pathname due to dynamic rewrite), the entry gets marked with\n // hasDynamicRewrite. Future predictions for this route will see the flag\n // and bail out to server resolution instead of making the same mistake.\n const syntheticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n tree: reifiedTree,\n metadata: reifiedMetadata,\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n hasDynamicRewrite: false,\n renderedSearch: search,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version,\n }\n\n matchedPart.pattern = syntheticEntry\n\n return syntheticEntry\n}\n\n/**\n * Result of a successful match: the matched tree node and its pattern.\n * We return both because the caller needs to update the pattern after\n * creating a synthetic entry (for dynamic rewrite detection).\n */\ntype KnownRouteMatch = {\n part: KnownRoutePart\n pattern: FulfilledRouteCacheEntry\n} | null\n\n/**\n * Recursively matches a URL against the known route tree.\n *\n * Matching priority (most specific first):\n * 1. Static children - exact path segment match\n * 2. Dynamic child - [param], [...param], [[...param]]\n * 3. Direct pattern - when no more URL parts remain\n *\n * Collects resolved param values in resolvedParams as it traverses.\n * Returns null if no match found (caller should fall back to server).\n */\nfunction matchKnownRoutePart(\n now: number,\n part: KnownRoutePart,\n pathnameParts: string[],\n partIndex: number,\n resolvedParams: ResolvedParams\n): KnownRouteMatch {\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n return null\n }\n\n // Static children take priority over dynamic. This ensures /blog/featured\n // matches its own route rather than /blog/[slug].\n if (urlPart !== null) {\n const staticChild = part.staticChildren.get(urlPart)\n if (staticChild !== undefined) {\n // Check if this is an \"unknown\" placeholder part. These are created when\n // we learn about static siblings (from the route tree's staticSiblings\n // field) but haven't prefetched them yet. We know the path exists but\n // don't know its structure, so we can't predict it.\n if (\n staticChild.pattern === null &&\n staticChild.dynamicChild === null &&\n staticChild.staticChildren === null\n ) {\n // Bail out - server must resolve this route.\n return null\n }\n const match = matchKnownRoutePart(\n now,\n staticChild,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n if (match !== null) {\n return match\n }\n // Static child is a real node (not a placeholder) but its subtree\n // didn't match the remaining URL parts. This means the route exists\n // in the static subtree but hasn't been fully discovered yet. Do not\n // fall through to try the dynamic child — the static match is\n // authoritative. Bail out to server resolution.\n return null\n }\n }\n\n // Try dynamic child. Skip it entirely if parallel route branches disagree\n // about the dynamic segment at this level — any pattern stored beneath it\n // was learned under a conflicting model.\n if (part.dynamicChild !== null && !part.hasConflictingDynamicChildren) {\n const dynamicPart = part.dynamicChild\n const paramName = part.dynamicChildParamName\n const paramType = part.dynamicChildParamType\n const dynamicPattern = readPattern(now, dynamicPart)\n\n switch (paramType) {\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (\n dynamicPattern !== null &&\n !dynamicPattern.hasDynamicRewrite &&\n urlPart !== null\n ) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n break\n case 'oc': {\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) {\n if (urlPart !== null) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n const directPattern = readPattern(now, part)\n if (directPattern === null || directPattern.hasDynamicRewrite) {\n resolvedParams.set(paramName, '')\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n }\n break\n }\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, urlPart)\n return matchKnownRoutePart(\n now,\n dynamicPart,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n }\n break\n // Intercepted routes use relative path markers like (.), (..), (...)\n // Their behavior depends on navigation context (soft vs hard nav),\n // so we can't predict them client-side. Defer to server.\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n return null\n default:\n paramType satisfies never\n }\n }\n\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null) {\n const pattern = readPattern(now, part)\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n\n return null\n}\n\n/**\n * Accumulator for collecting data during reifyRouteTree traversal.\n * metadataVaryPath is collected from the first page node encountered\n * (parallel routes may have multiple pages, but metadata uses the first).\n */\ntype ReifyAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\n/**\n * \"Reify\" means to make concrete - we take an abstract pattern (the template\n * route tree) and produce a concrete instance with actual param values.\n *\n * This function clones a RouteTree, substituting dynamic segment values from\n * resolvedParams and computing new vary paths. The vary path encodes param\n * values so segment cache entries can be correctly keyed.\n *\n * Example: Pattern for /blog/[slug] with resolvedParams { slug: \"hello\" }\n * produces a tree where segment [slug] has cacheKey \"hello\".\n */\nfunction reifyRouteTree(\n pattern: RouteTree<null>,\n resolvedParams: ResolvedParams,\n search: NormalizedSearch,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n acc: ReifyAccumulator\n): RouteTree<null> {\n const originalSegment = pattern.segment\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam =\n (pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n let newSegment = originalSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const newValue = resolvedParams.get(paramName)\n if (newValue !== undefined) {\n // Catch-all values are already joined into a single string when they're\n // resolved in matchKnownRoutePart, so the value can be used directly.\n const newCacheKey = newValue\n newSegment = [paramName, newCacheKey, paramType, staticSiblings]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n newCacheKey,\n paramName,\n isRootParam\n )\n } else {\n // Param not found in resolvedParams - keep original and inherit partial\n // TODO: This should never happen. Bail out with null.\n partialVaryPath = parentPartialVaryPath\n }\n } else {\n // Static segment: inherit partial vary path from parent\n partialVaryPath = parentPartialVaryPath\n }\n\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots: Map<string, RouteTree<null>> | null = null\n const patternSlots = pattern.slots\n if (patternSlots !== null) {\n newSlots = new Map()\n for (const [key, childPattern] of patternSlots) {\n newSlots.set(\n key,\n reifyRouteTree(\n childPattern,\n resolvedParams,\n search,\n partialVaryPath,\n acc\n )\n )\n }\n }\n\n if (pattern.isPage) {\n // Page segment: finalize with search params\n const newVaryPath = finalizePageVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n // Collect metadata vary path (first page wins, same as original algorithm)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n // Route cache patterns never carry seed data (see\n // stripDataFromRouteTree), so neither do trees reified from them.\n data: null,\n varyPath: newVaryPath,\n isPage: true,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n } else {\n // Layout segment: finalize without search params\n const newVaryPath = finalizeLayoutVaryPath(\n pattern.requestKey,\n partialVaryPath\n )\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n data: null,\n varyPath: newVaryPath,\n isPage: false,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n }\n}\n\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */\nexport function resetKnownRoutes(): void {\n knownRouteTreeRoot = createEmptyPart()\n}\n"],"names":["PrefetchHint","EntryStatus","writeRouteIntoCache","fulfillRouteCacheEntry","getCurrentRouteCacheVersion","createMetadataRouteTree","isValueExpired","canonicalizeURLPart","doesStaticSegmentAppearInURL","splitPathnameIntoParts","appendLayoutVaryPath","finalizeLayoutVaryPath","finalizePageVaryPath","finalizeMetadataVaryPath","getShellSegmentVaryPath","readPattern","now","part","pattern","createEmptyPart","staticChildren","dynamicChild","dynamicChildParamName","dynamicChildParamType","hasConflictingDynamicChildren","knownRouteTreeRoot","discoverKnownRoute","pathname","search","nextUrl","pendingEntry","routeTree","metadataVaryPath","couldBeIntercepted","canonicalUrl","supportsPerSegmentPrefetching","hasDynamicRewrite","tree","pathnameParts","fulfilledEntry","discoverKnownRoutePart","handleMismatchDueToRewrite","existingEntry","fullTree","discoverDynamicChild","paramName","paramType","newChild","mutablePart","parentKnownRoutePart","partIndex","segment","urlPart","length","knownRoutePart","nextPartIndex","Map","existingChild","get","undefined","set","paramCacheKey","staticSiblings","includes","joinedRemainingParts","slice","map","join","sibling","has","slots","resultFromChildren","childRouteTree","values","refreshState","result","existingPattern","entry","matchKnownRoute","resolvedParams","match","matchKnownRoutePart","matchedPart","acc","reifiedTree","reifyRouteTree","reifiedMetadata","syntheticEntry","status","Fulfilled","blockedTasks","metadata","renderedSearch","ref","size","staleAt","version","staticChild","dynamicPart","dynamicPattern","directPattern","parentPartialVaryPath","originalSegment","isRootParam","prefetchHints","IsRootLayoutOrAbove","newSegment","partialVaryPath","newValue","newCacheKey","newSlots","patternSlots","key","childPattern","isPage","newVaryPath","requestKey","shellVaryPath","data","varyPath","resetKnownRoutes"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAGD,SAASA,YAAY,QAAQ,uCAAsC;AAMnE,SACEC,WAAW,EACXC,mBAAmB,EACnBC,sBAAsB,EACtBC,2BAA2B,EAE3BC,uBAAuB,QAClB,UAAS;AAChB,SAASC,cAAc,QAAQ,cAAa;AAC5C,SACEC,mBAAmB,EACnBC,4BAA4B,QACvB,qBAAoB;AAE3B,SAASC,sBAAsB,QAAQ,cAAa;AACpD,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,wBAAwB,EACxBC,uBAAuB,QAGlB,cAAa;AA4FpB;;;;;;;CAOC,GACD,SAASC,YACPC,GAAW,EACXC,IAAoB;IAEpB,MAAMC,UAAUD,KAAKC,OAAO;IAC5B,IAAIA,YAAY,MAAM;QACpB,OAAO;IACT;IACA,IAAIZ,eAAeU,KAAKZ,+BAA+Bc,UAAU;QAC/D,sEAAsE;QACtED,K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QoD,KAAK;IAClC,IAAIyC,iBAAiB,MAAM;QACzBD,WAAW,IAAItD;QACf,KAAK,MAAM,CAACwD,KAAKC,aAAa,IAAIF,aAAc;YAC9CD,SAASlD,GAAG,CACVoD,KACA3B,eACE4B,cACAlC,gBACAnD,QACA+E,iBACAxB;QAGN;IACF;IAEA,IAAIjE,QAAQgG,MAAM,EAAE;QAClB,4CAA4C;QAC5C,MAAMC,cAAcvG,qBAClBM,QAAQkG,UAAU,EAClBxF,QACA+E;QAEF,2EAA2E;QAC3E,IAAIxB,IAAInD,gBAAgB,KAAK,MAAM;YACjCmD,IAAInD,gBAAgB,GAAGnB,yBACrBK,QAAQkG,UAAU,EAClBxF,QACA+E;QAEJ;QACA,OAAO;YACLS,YAAYlG,QAAQkG,UAAU;YAC9BjE,SAASuD;YACTW,eAAevG,wBAAwBqG;YACvCzC,cAAcxD,QAAQwD,YAAY;YAClC,kDAAkD;YAClD,kEAAkE;YAClE4C,MAAM;YACNC,UAAUJ;YACVD,QAAQ;YACR5C,OAAOwC;YACPN,eAAetF,QAAQsF,aAAa;QACtC;IACF,OAAO;QACL,iDAAiD;QACjD,MAAMW,cAAcxG,uBAClBO,QAAQkG,UAAU,EAClBT;QAEF,OAAO;YACLS,YAAYlG,QAAQkG,UAAU;YAC9BjE,SAASuD;YACTW,eAAevG,wBAAwBqG;YACvCzC,cAAcxD,QAAQwD,YAAY;YAClC4C,MAAM;YACNC,UAAUJ;YACVD,QAAQ;YACR5C,OAAOwC;YACPN,eAAetF,QAAQsF,aAAa;QACtC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,SAASgB;IACd/F,qBAAqBN;AACvB","ignoreList":[0]}
import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils';
import { isPostpone } from '../../server/lib/router-utils/is-postpone';
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
import { isNextRouterError } from './is-next-router-error';
import { isDynamicPostpone, isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering';
import { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering';
import { isDynamicServerError } from './hooks-server-context';

@@ -19,3 +18,3 @@ /**

*/ export function unstable_rethrow(error) {
if (isNextRouterError(error) || isBailoutToCSRError(error) || isDynamicServerError(error) || isDynamicPostpone(error) || isPostpone(error) || isHangingPromiseRejectionError(error) || isPrerenderInterruptedError(error)) {
if (isNextRouterError(error) || isBailoutToCSRError(error) || isDynamicServerError(error) || isHangingPromiseRejectionError(error) || isPrerenderInterruptedError(error)) {
throw error;

@@ -22,0 +21,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/client/components/unstable-rethrow.ts"],"sourcesContent":["import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isPostpone } from '../../server/lib/router-utils/is-postpone'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport {\n isDynamicPostpone,\n isPrerenderInterruptedError,\n} from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isDynamicPostpone(error) ||\n isPostpone(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n"],"names":["isHangingPromiseRejectionError","isPostpone","isBailoutToCSRError","isNextRouterError","isDynamicPostpone","isPrerenderInterruptedError","isDynamicServerError","unstable_rethrow","error","Error","cause"],"mappings":"AAAA,SAASA,8BAA8B,QAAQ,uCAAsC;AACrF,SAASC,UAAU,QAAQ,4CAA2C;AACtE,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SACEC,iBAAiB,EACjBC,2BAA2B,QACtB,4CAA2C;AAClD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,iBAAiBC,KAAc;IAC7C,IACEL,kBAAkBK,UAClBN,oBAAoBM,UACpBF,qBAAqBE,UACrBJ,kBAAkBI,UAClBP,WAAWO,UACXR,+BAA+BQ,UAC/BH,4BAA4BG,QAC5B;QACA,MAAMA;IACR;IAEA,IAAIA,iBAAiBC,SAAS,WAAWD,OAAO;QAC9CD,iBAAiBC,MAAME,KAAK;IAC9B;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/client/components/unstable-rethrow.ts"],"sourcesContent":["import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n"],"names":["isHangingPromiseRejectionError","isBailoutToCSRError","isNextRouterError","isPrerenderInterruptedError","isDynamicServerError","unstable_rethrow","error","Error","cause"],"mappings":"AAAA,SAASA,8BAA8B,QAAQ,uCAAsC;AACrF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,2BAA2B,QAAQ,4CAA2C;AACvF,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,iBAAiBC,KAAc;IAC7C,IACEJ,kBAAkBI,UAClBL,oBAAoBK,UACpBF,qBAAqBE,UACrBN,+BAA+BM,UAC/BH,4BAA4BG,QAC5B;QACA,MAAMA;IACR;IAEA,IAAIA,iBAAiBC,SAAS,WAAWD,OAAO;QAC9CD,iBAAiBC,MAAME,KAAK;IAC9B;AACF","ignoreList":[0]}

@@ -28,3 +28,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build.

import { isNextRouterError } from './components/is-next-router-error';
export const version = "16.3.1-canary.11";
export const version = "16.3.1-canary.12";
export let router;

@@ -31,0 +31,0 @@ export const emitter = mitt();

@@ -37,3 +37,3 @@ import { addSearchParamsIfPageSegment, DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../shared/lib/segment';

// `%2F` → `%252F`), we decode the URL part first and re-encode it.
function canonicalizeURLPart(part) {
export function canonicalizeURLPart(part) {
try {

@@ -40,0 +40,0 @@ return encodeURIComponent(decodeURIComponent(part));

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/client/route-params.ts"],"sourcesContent":["import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport { hasBasePath } from './has-base-path'\nimport { removeBasePath } from './remove-base-path'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return (\n rewrittenQuery === '' ? '' : '?' + rewrittenQuery\n ) as NormalizedSearch\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return urlToUrlWithoutFlightMarker(new URL(response.url))\n .search as NormalizedSearch\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n if (rewrittenPath !== null) {\n return rewrittenPath as NormalizedPathname\n }\n\n const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n return (\n hasBasePath(pathname) ? removeBasePath(pathname) : pathname\n ) as NormalizedPathname\n}\n\n// Pathname parts come from `URL.pathname.split('/')`, so they are already\n// in the encoded form the URL parser produces. The server-side equivalent\n// (`get-dynamic-param.ts`) starts from a decoded param value and applies\n// `encodeURIComponent` once. The two encodings are not the same — for\n// example, the URL parser leaves `,` and `:` untouched while\n// `encodeURIComponent` percent-encodes them. To produce the same canonical\n// form on the client (and avoid double-encoding `%xx` sequences such as\n// `%2F` → `%252F`), we decode the URL part first and re-encode it.\nfunction canonicalizeURLPart(part: string): string {\n try {\n return encodeURIComponent(decodeURIComponent(part))\n } catch {\n // `decodeURIComponent` throws on malformed sequences. Fall back to the\n // already-encoded form rather than failing the navigation.\n return part\n }\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return canonicalizeURLPart(s.slice(prefix))\n }\n\n return canonicalizeURLPart(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return canonicalizeURLPart(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n const prefix = paramType.length - 2\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n\n return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment.startsWith(PAGE_SEGMENT_KEY) ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue,\n renderedSearch: NormalizedSearch\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(\n paramValue,\n urlSearchParamsToParsedUrlQuery(new URLSearchParams(renderedSearch))\n ) as string\n return pageSegmentWithSearchParams\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n const length = pathname.endsWith('/index.txt') ? 10 : 4\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = pathname.slice(0, -length)\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc'\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/')\n }\n return paramCacheKey\n}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n if (result[key] === undefined) {\n result[key] = value\n } else if (Array.isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [result[key], value]\n }\n }\n return result\n}\n"],"names":["addSearchParamsIfPageSegment","DEFAULT_SEGMENT_KEY","PAGE_SEGMENT_KEY","ROOT_SEGMENT_REQUEST_KEY","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_RSC_UNION_QUERY","hasBasePath","removeBasePath","getRenderedSearch","response","rewrittenQuery","headers","get","urlToUrlWithoutFlightMarker","URL","url","search","getRenderedPathname","rewrittenPath","pathname","canonicalizeURLPart","part","encodeURIComponent","decodeURIComponent","parseDynamicParamFromURLPart","paramType","pathnameParts","partIndex","length","slice","map","s","prefix","i","doesStaticSegmentAppearInURL","segment","startsWith","endsWith","getCacheKeyForDynamicParam","paramValue","renderedSearch","pageSegmentWithSearchParams","urlSearchParamsToParsedUrlQuery","URLSearchParams","join","urlWithoutFlightParameters","searchParams","delete","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","getParamValueFromCacheKey","paramCacheKey","isCatchAll","split","result","key","value","entries","undefined","Array","isArray","push"],"mappings":"AACA,SACEA,4BAA4B,EAC5BC,mBAAmB,EACnBC,gBAAgB,QACX,wBAAuB;AAC9B,SAASC,wBAAwB,QAAQ,qDAAoD;AAC7F,SACEC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,oBAAoB,QACf,kCAAiC;AACxC,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,SAASC,cAAc,QAAQ,qBAAoB;AAUnD,OAAO,SAASC,kBACdC,QAAyC;IAEzC,0EAA0E;IAC1E,2EAA2E;IAC3E,4EAA4E;IAC5E,MAAMC,iBAAiBD,SAASE,OAAO,CAACC,GAAG,CAACR;IAC5C,IAAIM,mBAAmB,MAAM;QAC3B,OACEA,mBAAmB,KAAK,KAAK,MAAMA;IAEvC;IACA,2EAA2E;IAC3E,6BAA6B;IAC7B,OAAOG,4BAA4B,IAAIC,IAAIL,SAASM,GAAG,GACpDC,MAAM;AACX;AAEA,OAAO,SAASC,oBACdR,QAAyC;IAEzC,qEAAqE;IACrE,6EAA6E;IAC7E,wEAAwE;IACxE,MAAMS,gBAAgBT,SAASE,OAAO,CAACC,GAAG,CAACT;IAC3C,IAAI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QACnB,OAAO;YACLF,MAAM,CAACC,IAAI,GAAG;gBAACD,MAAM,CAACC,IAAI;gBAAEC;aAAM;QACpC;IACF;IACA,OAAOF;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../src/client/route-params.ts"],"sourcesContent":["import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport { hasBasePath } from './has-base-path'\nimport { removeBasePath } from './remove-base-path'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return (\n rewrittenQuery === '' ? '' : '?' + rewrittenQuery\n ) as NormalizedSearch\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return urlToUrlWithoutFlightMarker(new URL(response.url))\n .search as NormalizedSearch\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n if (rewrittenPath !== null) {\n return rewrittenPath as NormalizedPathname\n }\n\n const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n return (\n hasBasePath(pathname) ? removeBasePath(pathname) : pathname\n ) as NormalizedPathname\n}\n\n// Pathname parts come from `URL.pathname.split('/')`, so they are already\n// in the encoded form the URL parser produces. The server-side equivalent\n// (`get-dynamic-param.ts`) starts from a decoded param value and applies\n// `encodeURIComponent` once. The two encodings are not the same — for\n// example, the URL parser leaves `,` and `:` untouched while\n// `encodeURIComponent` percent-encodes them. To produce the same canonical\n// form on the client (and avoid double-encoding `%xx` sequences such as\n// `%2F` → `%252F`), we decode the URL part first and re-encode it.\nexport function canonicalizeURLPart(part: string): string {\n try {\n return encodeURIComponent(decodeURIComponent(part))\n } catch {\n // `decodeURIComponent` throws on malformed sequences. Fall back to the\n // already-encoded form rather than failing the navigation.\n return part\n }\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return canonicalizeURLPart(s.slice(prefix))\n }\n\n return canonicalizeURLPart(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return canonicalizeURLPart(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n const prefix = paramType.length - 2\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n\n return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment.startsWith(PAGE_SEGMENT_KEY) ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue,\n renderedSearch: NormalizedSearch\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(\n paramValue,\n urlSearchParamsToParsedUrlQuery(new URLSearchParams(renderedSearch))\n ) as string\n return pageSegmentWithSearchParams\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n const length = pathname.endsWith('/index.txt') ? 10 : 4\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = pathname.slice(0, -length)\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc'\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/')\n }\n return paramCacheKey\n}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n if (result[key] === undefined) {\n result[key] = value\n } else if (Array.isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [result[key], value]\n }\n }\n return result\n}\n"],"names":["addSearchParamsIfPageSegment","DEFAULT_SEGMENT_KEY","PAGE_SEGMENT_KEY","ROOT_SEGMENT_REQUEST_KEY","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_RSC_UNION_QUERY","hasBasePath","removeBasePath","getRenderedSearch","response","rewrittenQuery","headers","get","urlToUrlWithoutFlightMarker","URL","url","search","getRenderedPathname","rewrittenPath","pathname","canonicalizeURLPart","part","encodeURIComponent","decodeURIComponent","parseDynamicParamFromURLPart","paramType","pathnameParts","partIndex","length","slice","map","s","prefix","i","doesStaticSegmentAppearInURL","segment","startsWith","endsWith","getCacheKeyForDynamicParam","paramValue","renderedSearch","pageSegmentWithSearchParams","urlSearchParamsToParsedUrlQuery","URLSearchParams","join","urlWithoutFlightParameters","searchParams","delete","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","getParamValueFromCacheKey","paramCacheKey","isCatchAll","split","result","key","value","entries","undefined","Array","isArray","push"],"mappings":"AACA,SACEA,4BAA4B,EAC5BC,mBAAmB,EACnBC,gBAAgB,QACX,wBAAuB;AAC9B,SAASC,wBAAwB,QAAQ,qDAAoD;AAC7F,SACEC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,oBAAoB,QACf,kCAAiC;AACxC,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,SAASC,cAAc,QAAQ,qBAAoB;AAUnD,OAAO,SAASC,kBACdC,QAAyC;IAEzC,0EAA0E;IAC1E,2EAA2E;IAC3E,4EAA4E;IAC5E,MAAMC,iBAAiBD,SAASE,OAAO,CAACC,GAAG,CAACR;IAC5C,IAAIM,mBAAmB,MAAM;QAC3B,OACEA,mBAAmB,KAAK,KAAK,MAAMA;IAEvC;IACA,2EAA2E;IAC3E,6BAA6B;IAC7B,OAAOG,4BAA4B,IAAIC,IAAIL,SAASM,GAAG,GACpDC,MAA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AI,KAAKG,WAAW;YAC7BJ,MAAM,CAACC,IAAI,GAAGC;QAChB,OAAO,IAAIG,MAAMC,OAAO,CAACN,MAAM,CAACC,IAAI,GAAG;YACrCD,MAAM,CAACC,IAAI,CAACM,IAAI,CAACL;QACnB,OAAO;YACLF,MAAM,CAACC,IAAI,GAAG;gBAACD,MAAM,CAACC,IAAI;gBAAEC;aAAM;QACpC;IACF;IACA,OAAOF;AACT","ignoreList":[0]}
import { isDynamicServerError } from '../../client/components/hooks-server-context';
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';
import { isNextRouterError } from '../../client/components/is-next-router-error';
import { isDynamicPostpone } from '../../server/app-render/dynamic-rendering';
export const isDynamicUsageError = (err)=>isDynamicServerError(err) || isBailoutToCSRError(err) || isNextRouterError(err) || isDynamicPostpone(err);
export const isDynamicUsageError = (err)=>isDynamicServerError(err) || isBailoutToCSRError(err) || isNextRouterError(err);
//# sourceMappingURL=is-dynamic-usage-error.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/export/helpers/is-dynamic-usage-error.ts"],"sourcesContent":["import { isDynamicServerError } from '../../client/components/hooks-server-context'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\nimport { isDynamicPostpone } from '../../server/app-render/dynamic-rendering'\n\nexport const isDynamicUsageError = (err: unknown) =>\n isDynamicServerError(err) ||\n isBailoutToCSRError(err) ||\n isNextRouterError(err) ||\n isDynamicPostpone(err)\n"],"names":["isDynamicServerError","isBailoutToCSRError","isNextRouterError","isDynamicPostpone","isDynamicUsageError","err"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,+CAA8C;AACnF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,iBAAiB,QAAQ,+CAA8C;AAChF,SAASC,iBAAiB,QAAQ,4CAA2C;AAE7E,OAAO,MAAMC,sBAAsB,CAACC,MAClCL,qBAAqBK,QACrBJ,oBAAoBI,QACpBH,kBAAkBG,QAClBF,kBAAkBE,KAAI","ignoreList":[0]}
{"version":3,"sources":["../../../../src/export/helpers/is-dynamic-usage-error.ts"],"sourcesContent":["import { isDynamicServerError } from '../../client/components/hooks-server-context'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\n\nexport const isDynamicUsageError = (err: unknown) =>\n isDynamicServerError(err) ||\n isBailoutToCSRError(err) ||\n isNextRouterError(err)\n"],"names":["isDynamicServerError","isBailoutToCSRError","isNextRouterError","isDynamicUsageError","err"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,+CAA8C;AACnF,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,iBAAiB,QAAQ,+CAA8C;AAEhF,OAAO,MAAMC,sBAAsB,CAACC,MAClCJ,qBAAqBI,QACrBH,oBAAoBG,QACpBF,kBAAkBE,KAAI","ignoreList":[0]}

@@ -616,3 +616,3 @@ import { createStaticWorker } from '../build';

// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
if (!options.buildExport && nextConfig.cacheComponents) {
// TODO: add message

@@ -619,0 +619,0 @@ throw Object.defineProperty(new Error('Invariant: PPR cannot be enabled in export mode'), "__NEXT_ERROR_CODE", {

@@ -24,3 +24,2 @@ import '../server/node-environment';

import { createIncrementalCache } from './helpers/create-incremental-cache';
import { isPostpone } from '../server/lib/router-utils/is-postpone';
import { isDynamicUsageError } from './helpers/is-dynamic-usage-error';

@@ -407,7 +406,2 @@ import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr';

process.on('unhandledRejection', (err)=>{
// if it's a postpone error, it'll be handled later
// when the postponed promise is actually awaited.
if (isPostpone(err)) {
return;
}
// we don't want to log these errors

@@ -414,0 +408,0 @@ if (isDynamicUsageError(err)) {

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/export/worker.ts"],"sourcesContent":["import type {\n ExportPagesInput,\n ExportPageInput,\n ExportPageResult,\n ExportRouteResult,\n WorkerRenderOpts,\n ExportPagesResult,\n ExportPathEntry,\n} from './types'\nimport type { AppPageModule } from '../server/route-modules/app-page/module'\nimport type { PagesModule } from '../server/route-modules/pages/module.compiled'\n\nimport '../server/node-environment'\nimport { installBindings } from '../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../server/lib/install-code-frame'\n\nprocess.env.NEXT_IS_EXPORT_WORKER = 'true'\n\nimport { extname, join, dirname, sep } from 'path'\nimport fs from 'fs/promises'\nimport { loadComponents } from '../server/load-components'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { trace } from '../trace'\nimport { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'\nimport { addRequestMeta } from '../server/request-meta'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\n\nimport { createRequestResponseMocks } from '../server/lib/mock-request'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { hasNextSupport } from '../server/ci-info'\nimport { exportAppRoute } from './routes/app-route'\nimport { exportAppPage } from './routes/app-page'\nimport { exportPagesPage } from './routes/pages'\nimport { getParams } from './helpers/get-params'\nimport { createIncrementalCache } from './helpers/create-incremental-cache'\nimport { isPostpone } from '../server/lib/router-utils/is-postpone'\nimport { isDynamicUsageError } from './helpers/is-dynamic-usage-error'\nimport { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'\nimport {\n turborepoTraceAccess,\n TurborepoAccessTraceResult,\n} from '../build/turborepo-access-trace'\nimport type { Params } from '../server/request/params'\nimport {\n createOpaqueFallbackRouteParams,\n type OpaqueFallbackRouteParams,\n} from '../server/request/fallback-params'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'\nimport { isStaticGenBailoutError } from '../client/components/static-generation-bailout'\nimport type { PagesRenderContext, PagesSharedContext } from '../server/render'\nimport type { AppSharedContext } from '../server/app-render/app-render'\nimport { MultiFileWriter } from '../lib/multi-file-writer'\nimport { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'\nimport { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'\n;(globalThis as any).__NEXT_DATA__ = {\n nextExport: true,\n}\n\nclass TimeoutError extends Error {\n code = 'NEXT_EXPORT_TIMEOUT_ERROR'\n}\n\nclass ExportPageError extends Error {\n code = 'NEXT_EXPORT_PAGE_ERROR'\n}\n\nasync function exportPageImpl(\n input: ExportPageInput,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const {\n exportPath,\n distDir,\n pagesDataDir,\n buildExport = false,\n subFolders = false,\n optimizeCss,\n disableOptimizedLoading,\n debugOutput = false,\n enableExperimentalReact,\n trailingSlash,\n sriEnabled,\n renderOpts: commonRenderOpts,\n outDir: commonOutDir,\n buildId,\n deploymentId,\n clientAssetToken,\n renderResumeDataCache,\n } = input\n\n if (enableExperimentalReact) {\n process.env.__NEXT_EXPERIMENTAL_REACT = 'true'\n }\n\n const {\n path,\n page,\n\n // The parameters that are currently unknown.\n _fallbackRouteParams = [],\n\n // Check if this is an `app/` page.\n _isAppDir: isAppDir = false,\n\n // Check if this should error when dynamic usage is detected.\n _isDynamicError: isDynamicError = false,\n\n // If this page supports partial prerendering, then we need to pass that to\n // the renderOpts.\n _isRoutePPREnabled: isRoutePPREnabled,\n\n // Configure the rendering of the page to allow that an empty static shell\n // is generated while rendering using PPR and Cache Components.\n _allowEmptyStaticShell: allowEmptyStaticShell = false,\n\n // When true, attempt to run build-time instant validation for this export path.\n _runInstantValidation: runInstantValidation = false,\n\n // When true, a fallback shell for this path could later be upgraded to a\n // concrete version (it has a `generateStaticParams` candidate param).\n _isFallbackUpgradeable: isFallbackUpgradeable = false,\n\n // Pull the original query out.\n query: originalQuery = {},\n } = exportPath\n\n const fallbackRouteParams: OpaqueFallbackRouteParams | null =\n createOpaqueFallbackRouteParams(_fallbackRouteParams)\n\n let query = { ...originalQuery }\n const pathname = normalizeAppPath(page)\n const isDynamic = isDynamicRoute(page)\n const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir\n\n const filePath = normalizePagePath(path)\n\n let updatedPath = exportPath._ssgPath || path\n let locale = exportPath._locale || commonRenderOpts.locale\n\n if (commonRenderOpts.locale) {\n const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales)\n\n if (localePathResult.detectedLocale) {\n updatedPath = localePathResult.pathname\n locale = localePathResult.detectedLocale\n }\n }\n\n // We need to show a warning if they try to provide query values\n // for an auto-exported page since they won't be available\n const hasOrigQueryValues = Object.keys(originalQuery).length > 0\n\n // Check if the page is a specified dynamic route\n const { pathname: nonLocalizedPath } = normalizeLocalePath(\n path,\n commonRenderOpts.locales\n )\n\n let params: Params | undefined\n\n if (isDynamic && page !== nonLocalizedPath) {\n const normalizedPage = isAppDir ? normalizeAppPath(page) : page\n\n params = getParams(normalizedPage, updatedPath)\n }\n\n const { req, res } = createRequestResponseMocks({ url: updatedPath })\n\n // If this is a status code page, then set the response code.\n for (const statusCode of [404, 500]) {\n if (\n [\n `/${statusCode}`,\n `/${statusCode}.html`,\n `/${statusCode}/index.html`,\n ].some((p) => p === updatedPath || `/${locale}${p}` === updatedPath)\n ) {\n res.statusCode = statusCode\n }\n }\n\n // Ensure that the URL has a trailing slash if it's configured.\n if (trailingSlash && !req.url?.endsWith('/')) {\n req.url += '/'\n }\n\n // Set the resolved pathname without trailing slash as request metadata.\n addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath))\n\n if (\n locale &&\n buildExport &&\n commonRenderOpts.domainLocales &&\n commonRenderOpts.domainLocales.some(\n (dl) => dl.defaultLocale === locale || dl.locales?.includes(locale || '')\n )\n ) {\n addRequestMeta(req, 'isLocaleDomain', true)\n }\n\n const getHtmlFilename = (p: string) =>\n subFolders ? `${p}${sep}index.html` : `${p}.html`\n\n let htmlFilename = getHtmlFilename(filePath)\n\n // dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an\n // extension of `.slug]`\n const pageExt = isDynamic || isAppDir ? '' : extname(page)\n const pathExt = isDynamic || isAppDir ? '' : extname(path)\n\n // force output 404.html for backwards compat\n if (path === '/404.html') {\n htmlFilename = path\n }\n // Make sure page isn't a folder with a dot in the name e.g. `v1.2`\n else if (pageExt !== pathExt && pathExt !== '') {\n const isBuiltinPaths = ['/500', '/404'].some(\n (p) => p === path || p === path + '.html'\n )\n // If the ssg path has .html extension, and it's not builtin paths, use it directly\n // Otherwise, use that as the filename instead\n const isHtmlExtPath = !isBuiltinPaths && path.endsWith('.html')\n htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path\n } else if (path === '/') {\n // If the path is the root, just use index.html\n htmlFilename = 'index.html'\n }\n\n const baseDir = join(outDir, dirname(htmlFilename))\n let htmlFilepath = join(outDir, htmlFilename)\n\n await fs.mkdir(baseDir, { recursive: true })\n\n const components = await loadComponents({\n distDir,\n page,\n isAppPath: isAppDir,\n isDev: false,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n // Handle App Routes.\n if (isAppDir && isAppRouteRoute(page)) {\n return exportAppRoute(\n req,\n res,\n params,\n page,\n components.routeModule as AppRouteRouteModule,\n commonRenderOpts.incrementalCache,\n commonRenderOpts.cacheLifeProfiles,\n htmlFilepath,\n fileWriter,\n commonRenderOpts.cacheComponents,\n commonRenderOpts.staticPageGenerationTimeout,\n commonRenderOpts.experimental,\n buildId,\n deploymentId\n )\n }\n\n const renderOpts: WorkerRenderOpts = {\n ...components,\n ...commonRenderOpts,\n params,\n optimizeCss,\n disableOptimizedLoading,\n locale,\n supportsDynamicResponse: false,\n // During the export phase in next build, we always enable the streaming metadata since if there's\n // any dynamic access in metadata we can determine it in the build phase.\n // If it's static, then it won't affect anything.\n // If it's dynamic, then it can be handled when request hits the route.\n serveStreamingMetadata: true,\n allowEmptyStaticShell,\n runInstantValidation,\n isFallbackUpgradeable,\n experimental: {\n ...commonRenderOpts.experimental,\n isRoutePPREnabled,\n },\n renderResumeDataCache,\n }\n\n // Handle App Pages\n if (isAppDir) {\n const sharedContext: AppSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n }\n\n return exportAppPage(\n req,\n res,\n page,\n path,\n pathname,\n query,\n fallbackRouteParams,\n renderOpts as WorkerRenderOpts<AppPageModule>,\n htmlFilepath,\n debugOutput,\n isDynamicError,\n fileWriter,\n sharedContext\n )\n } else {\n const sharedContext: PagesSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n customServer: undefined,\n }\n\n const renderContext: PagesRenderContext = {\n isFallback: exportPath._pagesFallback ?? false,\n isDraftMode: false,\n developmentNotFoundSourcePage: undefined,\n }\n\n return exportPagesPage(\n req,\n res,\n path,\n page,\n query,\n params,\n htmlFilepath,\n htmlFilename,\n pagesDataDir,\n buildExport,\n isDynamic,\n sharedContext,\n renderContext,\n hasOrigQueryValues,\n renderOpts as WorkerRenderOpts<PagesModule>,\n components,\n fileWriter\n )\n }\n}\n\nexport async function exportPages(\n input: ExportPagesInput\n): Promise<ExportPagesResult> {\n // Load native bindings in the worker process so that code frame rendering\n // (which uses the native codeFrameColumns function) works during prerendering.\n await installBindings()\n installCodeFrameSupport()\n\n const {\n exportPaths,\n dir,\n distDir,\n outDir,\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n pagesDataDir,\n renderOpts,\n nextConfig,\n options,\n renderResumeDataCachesByPage = {},\n } = input\n\n installGlobalBehaviors(nextConfig)\n\n if (nextConfig.enablePrerenderSourceMaps) {\n try {\n // Same as `next dev`\n // Limiting the stack trace to a useful amount of frames is handled by ignore-listing.\n // TODO: How high can we go without severely impacting CPU/memory?\n Error.stackTraceLimit = 50\n } catch {}\n }\n\n // If the fetch cache was enabled, we need to create an incremental\n // cache instance for this page.\n const incrementalCache = await createIncrementalCache({\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n distDir,\n dir,\n // skip writing to disk in minimal mode for now, pending some\n // changes to better support it\n flushToDisk: !hasNextSupport,\n cacheHandlers: nextConfig.cacheHandlers,\n })\n\n renderOpts.incrementalCache = incrementalCache\n\n const maxConcurrency =\n nextConfig.experimental.staticGenerationMaxConcurrency ?? 8\n const results: ExportPagesResult = []\n\n const exportPageWithRetry = async (\n exportPath: ExportPathEntry,\n maxAttempts: number\n ) => {\n const { page, path } = exportPath\n const pageKey = page !== path ? `${page}: ${path}` : path\n let attempt = 0\n let result\n\n const hasDebuggerAttached =\n // Also tests for `inspect-brk`\n process.env.NODE_OPTIONS?.includes('--inspect')\n\n const renderResumeDataCache = renderResumeDataCachesByPage[pageKey]\n ? createRenderResumeDataCache(\n renderResumeDataCachesByPage[pageKey],\n renderOpts.experimental.maxPostponedStateSizeBytes\n )\n : undefined\n\n while (attempt < maxAttempts) {\n try {\n result = await Promise.race<ExportPageResult | undefined>([\n exportPage({\n exportPath,\n distDir,\n outDir,\n pagesDataDir,\n renderOpts,\n trailingSlash: nextConfig.trailingSlash,\n subFolders: nextConfig.trailingSlash && !options.buildExport,\n buildExport: options.buildExport,\n optimizeCss: nextConfig.experimental.optimizeCss,\n disableOptimizedLoading:\n nextConfig.experimental.disableOptimizedLoading,\n parentSpanId: input.parentSpanId,\n httpAgentOptions: nextConfig.httpAgentOptions,\n debugOutput: options.debugOutput,\n enableExperimentalReact: needsExperimentalReact(nextConfig),\n sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),\n buildId: input.buildId,\n deploymentId: input.deploymentId,\n clientAssetToken: input.clientAssetToken,\n renderResumeDataCache,\n }),\n hasDebuggerAttached\n ? // With a debugger attached, exporting can take infinitely if we paused script execution.\n new Promise(() => {})\n : // If exporting the page takes longer than the timeout, reject the promise.\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError())\n }, nextConfig.staticPageGenerationTimeout * 1000)\n }),\n ])\n\n // If there was an error in the export, throw it immediately. In the catch block, we might retry the export,\n // or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.\n if (result && 'error' in result) {\n throw new ExportPageError()\n }\n\n // If the export succeeds, break out of the retry loop\n break\n } catch (err) {\n // The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.\n // This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.\n if (!(err instanceof ExportPageError || err instanceof TimeoutError)) {\n throw err\n }\n\n if (err instanceof TimeoutError) {\n // If the export times out, we will restart the worker up to 3 times.\n maxAttempts = 3\n }\n\n // We've reached the maximum number of attempts\n if (attempt >= maxAttempts - 1) {\n // Log a message if we've reached the maximum number of attempts.\n // We only care to do this if maxAttempts was configured.\n if (maxAttempts > 1) {\n console.info(\n `Failed to build ${pageKey} after ${maxAttempts} attempts.`\n )\n }\n // If prerenderEarlyExit is enabled, we'll exit the build immediately.\n if (nextConfig.experimental.prerenderEarlyExit) {\n console.error(\n `Export encountered an error on ${pageKey}, exiting the build.`\n )\n process.exit(1)\n } else {\n // Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.\n }\n } else {\n // Otherwise, we have more attempts to make. Wait before retrying\n if (err instanceof TimeoutError) {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}) because it took more than ${nextConfig.staticPageGenerationTimeout} seconds. Retrying again shortly.`\n )\n } else {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`\n )\n }\n\n // Exponential backoff with random jitter to avoid thundering herd on retries\n const baseDelay = 500 // 500ms\n const maxDelay = 2000 // 2 seconds\n const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)\n const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter\n await new Promise((r) => setTimeout(r, delay + jitter))\n }\n }\n\n attempt++\n }\n\n return { result, path, page, pageKey }\n }\n\n for (let i = 0; i < exportPaths.length; i += maxConcurrency) {\n const subset = exportPaths.slice(i, i + maxConcurrency)\n\n const subsetResults = await Promise.all(\n subset.map((exportPath) =>\n exportPageWithRetry(\n exportPath,\n nextConfig.experimental.staticGenerationRetryCount ?? 1\n )\n )\n )\n\n results.push(...subsetResults)\n }\n\n return results\n}\n\nasync function exportPage(\n input: ExportPageInput\n): Promise<ExportPageResult | undefined> {\n trace('export-page', input.parentSpanId).setAttribute(\n 'path',\n input.exportPath.path\n )\n\n // Configure the http agent.\n setHttpClientAndAgentOptions({\n httpAgentOptions: input.httpAgentOptions,\n })\n\n const fileWriter = new MultiFileWriter({\n writeFile: (filePath, data) => fs.writeFile(filePath, data),\n mkdir: (dir) => fs.mkdir(dir, { recursive: true }),\n })\n\n const exportPageSpan = trace('export-page-worker', input.parentSpanId)\n\n const start = Date.now()\n\n const turborepoAccessTraceResult = new TurborepoAccessTraceResult()\n\n // Export the page.\n let result: ExportRouteResult | undefined\n try {\n result = await exportPageSpan.traceAsyncFn(() =>\n turborepoTraceAccess(\n () => exportPageImpl(input, fileWriter),\n turborepoAccessTraceResult\n )\n )\n\n // Wait for all the files to flush to disk.\n await fileWriter.wait()\n\n // If there was no result, then we can exit early.\n if (!result) return\n\n // If there was an error, then we can exit early.\n if ('error' in result) {\n return { error: result.error, duration: Date.now() - start }\n }\n } catch (err) {\n console.error(\n `Error occurred prerendering page \"${input.exportPath.path}\". Read more: https://nextjs.org/docs/messages/prerender-error`\n )\n\n // bailoutToCSRError errors should not leak to the user as they are not actionable; they're\n // a framework signal\n if (!isBailoutToCSRError(err)) {\n // A static generation bailout error is a framework signal to fail static generation but\n // and will encode a reason in the error message. If there is a message, we'll print it.\n // Otherwise there's nothing to show as we don't want to leak an error internal error stack to the user.\n // TODO: Always log the full error. ignore-listing will take care of hiding internal stacks.\n if (isStaticGenBailoutError(err)) {\n if (err.message) {\n console.error(`Error: ${err.message}`)\n }\n } else {\n console.error(err)\n }\n }\n\n return { error: true, duration: Date.now() - start }\n }\n\n // Notify the parent process that we processed a page (used by the progress activity indicator)\n process.send?.([3, { type: 'activity' }])\n\n // Otherwise we can return the result.\n return {\n ...result,\n duration: Date.now() - start,\n turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),\n }\n}\n\nprocess.on('unhandledRejection', (err: unknown) => {\n // if it's a postpone error, it'll be handled later\n // when the postponed promise is actually awaited.\n if (isPostpone(err)) {\n return\n }\n\n // we don't want to log these errors\n if (isDynamicUsageError(err)) {\n return\n }\n\n console.error(err)\n})\n\nprocess.on('rejectionHandled', () => {\n // It is ok to await a Promise late in Next.js as it allows for better\n // prefetching patterns to avoid waterfalls. We ignore logging these.\n // We should've already errored in anyway unhandledRejection.\n})\n\nconst FATAL_UNHANDLED_NEXT_API_EXIT_CODE = 78\n\nprocess.on('uncaughtException', (err) => {\n if (isDynamicUsageError(err)) {\n console.error(\n 'A Next.js API that uses exceptions to signal framework behavior was uncaught. This suggests improper usage of a Next.js API. The original error is printed below and the build will now exit.'\n )\n console.error(err)\n process.exit(FATAL_UNHANDLED_NEXT_API_EXIT_CODE)\n } else {\n console.error(err)\n }\n})\n"],"names":["installBindings","installCodeFrameSupport","process","env","NEXT_IS_EXPORT_WORKER","extname","join","dirname","sep","fs","loadComponents","isDynamicRoute","normalizePagePath","normalizeLocalePath","trace","setHttpClientAndAgentOptions","addRequestMeta","normalizeAppPath","removeTrailingSlash","createRequestResponseMocks","isAppRouteRoute","hasNextSupport","exportAppRoute","exportAppPage","exportPagesPage","getParams","createIncrementalCache","isPostpone","isDynamicUsageError","isBailoutToCSRError","turborepoTraceAccess","TurborepoAccessTraceResult","createOpaqueFallbackRouteParams","needsExperimentalReact","isStaticGenBailoutError","MultiFileWriter","createRenderResumeDataCache","installGlobalBehaviors","globalThis","__NEXT_DATA__","nextExport","TimeoutError","Error","code","ExportPageError","exportPageImpl","input","fileWriter","req","exportPath","distDir","pagesDataDir","buildExport","subFolders","optimizeCss","disableOptimizedLoading","debugOutput","enableExperimentalReact","trailingSlash","sriEnabled","renderOpts","commonRenderOpts","outDir","commonOutDir","buildId","deploymentId","clientAssetToken","renderResumeDataCache","__NEXT_EXPERIMENTAL_REACT","path","page","_fallbackRouteParams","_isAppDir","isAppDir","_isDynamicError","isDynamicError","_isRoutePPREnabled","isRoutePPREnabled","_allowEmptyStaticShell","allowEmptyStaticShell","_runInstantValidation","runInstantValidation","_isFallbackUpgradeable","isFallbackUpgradeable","query","originalQuery","fallbackRouteParams","pathname","isDynamic","filePath","updatedPath","_ssgPath","locale","_locale","localePathResult","locales","detectedLocale","hasOrigQueryValues","Object","keys","length","nonLocalizedPath","params","normalizedPage","res","url","statusCode","some","p","endsWith","domainLocales","dl","defaultLocale","includes","getHtmlFilename","htmlFilename","pageExt","pathExt","isBuiltinPaths","isHtmlExtPath","baseDir","htmlFilepath","mkdir","recursive","components","isAppPath","isDev","needsManifestsForLegacyReasons","routeModule","incrementalCache","cacheLifeProfiles","cacheComponents","staticPageGenerationTimeout","experimental","supportsDynamicResponse","serveStreamingMetadata","sharedContext","customServer","undefined","renderContext","isFallback","_pagesFallback","isDraftMode","developmentNotFoundSourcePage","exportPages","exportPaths","dir","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","nextConfig","options","renderResumeDataCachesByPage","enablePrerenderSourceMaps","stackTraceLimit","flushToDisk","cacheHandlers","maxConcurrency","staticGenerationMaxConcurrency","results","exportPageWithRetry","maxAttempts","pageKey","attempt","result","hasDebuggerAttached","NODE_OPTIONS","maxPostponedStateSizeBytes","Promise","race","exportPage","parentSpanId","httpAgentOptions","Boolean","sri","algorithm","_","reject","setTimeout","err","console","info","prerenderEarlyExit","error","exit","baseDelay","maxDelay","delay","Math","min","pow","jitter","random","r","i","subset","slice","subsetResults","all","map","staticGenerationRetryCount","push","setAttribute","writeFile","data","exportPageSpan","start","Date","now","turborepoAccessTraceResult","traceAsyncFn","wait","duration","message","send","type","serialize","on","FATAL_UNHANDLED_NEXT_API_EXIT_CODE"],"mappings":"AAYA,OAA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AAK,CAACJ;YAChB;QACF;QAEA,OAAO;YAAEI,OAAO;YAAM6B,UAAUL,KAAKC,GAAG,KAAKF;QAAM;IACrD;IAEA,+FAA+F;IAC/F5M,QAAQoN,IAAI,oBAAZpN,QAAQoN,IAAI,MAAZpN,SAAe;QAAC;QAAG;YAAEqN,MAAM;QAAW;KAAE;IAExC,sCAAsC;IACtC,OAAO;QACL,GAAGnD,MAAM;QACTgD,UAAUL,KAAKC,GAAG,KAAKF;QACvBG,4BAA4BA,2BAA2BO,SAAS;IAClE;AACF;AAEAtN,QAAQuN,EAAE,CAAC,sBAAsB,CAACtC;IAChC,mDAAmD;IACnD,kDAAkD;IAClD,IAAIxJ,WAAWwJ,MAAM;QACnB;IACF;IAEA,oCAAoC;IACpC,IAAIvJ,oBAAoBuJ,MAAM;QAC5B;IACF;IAEAC,QAAQG,KAAK,CAACJ;AAChB;AAEAjL,QAAQuN,EAAE,CAAC,oBAAoB;AAC7B,sEAAsE;AACtE,qEAAqE;AACrE,6DAA6D;AAC/D;AAEA,MAAMC,qCAAqC;AAE3CxN,QAAQuN,EAAE,CAAC,qBAAqB,CAACtC;IAC/B,IAAIvJ,oBAAoBuJ,MAAM;QAC5BC,QAAQG,KAAK,CACX;QAEFH,QAAQG,KAAK,CAACJ;QACdjL,QAAQsL,IAAI,CAACkC;IACf,OAAO;QACLtC,QAAQG,KAAK,CAACJ;IAChB;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/export/worker.ts"],"sourcesContent":["import type {\n ExportPagesInput,\n ExportPageInput,\n ExportPageResult,\n ExportRouteResult,\n WorkerRenderOpts,\n ExportPagesResult,\n ExportPathEntry,\n} from './types'\nimport type { AppPageModule } from '../server/route-modules/app-page/module'\nimport type { PagesModule } from '../server/route-modules/pages/module.compiled'\n\nimport '../server/node-environment'\nimport { installBindings } from '../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../server/lib/install-code-frame'\n\nprocess.env.NEXT_IS_EXPORT_WORKER = 'true'\n\nimport { extname, join, dirname, sep } from 'path'\nimport fs from 'fs/promises'\nimport { loadComponents } from '../server/load-components'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { trace } from '../trace'\nimport { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'\nimport { addRequestMeta } from '../server/request-meta'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\n\nimport { createRequestResponseMocks } from '../server/lib/mock-request'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { hasNextSupport } from '../server/ci-info'\nimport { exportAppRoute } from './routes/app-route'\nimport { exportAppPage } from './routes/app-page'\nimport { exportPagesPage } from './routes/pages'\nimport { getParams } from './helpers/get-params'\nimport { createIncrementalCache } from './helpers/create-incremental-cache'\nimport { isDynamicUsageError } from './helpers/is-dynamic-usage-error'\nimport { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'\nimport {\n turborepoTraceAccess,\n TurborepoAccessTraceResult,\n} from '../build/turborepo-access-trace'\nimport type { Params } from '../server/request/params'\nimport {\n createOpaqueFallbackRouteParams,\n type OpaqueFallbackRouteParams,\n} from '../server/request/fallback-params'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'\nimport { isStaticGenBailoutError } from '../client/components/static-generation-bailout'\nimport type { PagesRenderContext, PagesSharedContext } from '../server/render'\nimport type { AppSharedContext } from '../server/app-render/app-render'\nimport { MultiFileWriter } from '../lib/multi-file-writer'\nimport { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'\nimport { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'\n;(globalThis as any).__NEXT_DATA__ = {\n nextExport: true,\n}\n\nclass TimeoutError extends Error {\n code = 'NEXT_EXPORT_TIMEOUT_ERROR'\n}\n\nclass ExportPageError extends Error {\n code = 'NEXT_EXPORT_PAGE_ERROR'\n}\n\nasync function exportPageImpl(\n input: ExportPageInput,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const {\n exportPath,\n distDir,\n pagesDataDir,\n buildExport = false,\n subFolders = false,\n optimizeCss,\n disableOptimizedLoading,\n debugOutput = false,\n enableExperimentalReact,\n trailingSlash,\n sriEnabled,\n renderOpts: commonRenderOpts,\n outDir: commonOutDir,\n buildId,\n deploymentId,\n clientAssetToken,\n renderResumeDataCache,\n } = input\n\n if (enableExperimentalReact) {\n process.env.__NEXT_EXPERIMENTAL_REACT = 'true'\n }\n\n const {\n path,\n page,\n\n // The parameters that are currently unknown.\n _fallbackRouteParams = [],\n\n // Check if this is an `app/` page.\n _isAppDir: isAppDir = false,\n\n // Check if this should error when dynamic usage is detected.\n _isDynamicError: isDynamicError = false,\n\n // If this page supports partial prerendering, then we need to pass that to\n // the renderOpts.\n _isRoutePPREnabled: isRoutePPREnabled,\n\n // Configure the rendering of the page to allow that an empty static shell\n // is generated while rendering using PPR and Cache Components.\n _allowEmptyStaticShell: allowEmptyStaticShell = false,\n\n // When true, attempt to run build-time instant validation for this export path.\n _runInstantValidation: runInstantValidation = false,\n\n // When true, a fallback shell for this path could later be upgraded to a\n // concrete version (it has a `generateStaticParams` candidate param).\n _isFallbackUpgradeable: isFallbackUpgradeable = false,\n\n // Pull the original query out.\n query: originalQuery = {},\n } = exportPath\n\n const fallbackRouteParams: OpaqueFallbackRouteParams | null =\n createOpaqueFallbackRouteParams(_fallbackRouteParams)\n\n let query = { ...originalQuery }\n const pathname = normalizeAppPath(page)\n const isDynamic = isDynamicRoute(page)\n const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir\n\n const filePath = normalizePagePath(path)\n\n let updatedPath = exportPath._ssgPath || path\n let locale = exportPath._locale || commonRenderOpts.locale\n\n if (commonRenderOpts.locale) {\n const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales)\n\n if (localePathResult.detectedLocale) {\n updatedPath = localePathResult.pathname\n locale = localePathResult.detectedLocale\n }\n }\n\n // We need to show a warning if they try to provide query values\n // for an auto-exported page since they won't be available\n const hasOrigQueryValues = Object.keys(originalQuery).length > 0\n\n // Check if the page is a specified dynamic route\n const { pathname: nonLocalizedPath } = normalizeLocalePath(\n path,\n commonRenderOpts.locales\n )\n\n let params: Params | undefined\n\n if (isDynamic && page !== nonLocalizedPath) {\n const normalizedPage = isAppDir ? normalizeAppPath(page) : page\n\n params = getParams(normalizedPage, updatedPath)\n }\n\n const { req, res } = createRequestResponseMocks({ url: updatedPath })\n\n // If this is a status code page, then set the response code.\n for (const statusCode of [404, 500]) {\n if (\n [\n `/${statusCode}`,\n `/${statusCode}.html`,\n `/${statusCode}/index.html`,\n ].some((p) => p === updatedPath || `/${locale}${p}` === updatedPath)\n ) {\n res.statusCode = statusCode\n }\n }\n\n // Ensure that the URL has a trailing slash if it's configured.\n if (trailingSlash && !req.url?.endsWith('/')) {\n req.url += '/'\n }\n\n // Set the resolved pathname without trailing slash as request metadata.\n addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath))\n\n if (\n locale &&\n buildExport &&\n commonRenderOpts.domainLocales &&\n commonRenderOpts.domainLocales.some(\n (dl) => dl.defaultLocale === locale || dl.locales?.includes(locale || '')\n )\n ) {\n addRequestMeta(req, 'isLocaleDomain', true)\n }\n\n const getHtmlFilename = (p: string) =>\n subFolders ? `${p}${sep}index.html` : `${p}.html`\n\n let htmlFilename = getHtmlFilename(filePath)\n\n // dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an\n // extension of `.slug]`\n const pageExt = isDynamic || isAppDir ? '' : extname(page)\n const pathExt = isDynamic || isAppDir ? '' : extname(path)\n\n // force output 404.html for backwards compat\n if (path === '/404.html') {\n htmlFilename = path\n }\n // Make sure page isn't a folder with a dot in the name e.g. `v1.2`\n else if (pageExt !== pathExt && pathExt !== '') {\n const isBuiltinPaths = ['/500', '/404'].some(\n (p) => p === path || p === path + '.html'\n )\n // If the ssg path has .html extension, and it's not builtin paths, use it directly\n // Otherwise, use that as the filename instead\n const isHtmlExtPath = !isBuiltinPaths && path.endsWith('.html')\n htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path\n } else if (path === '/') {\n // If the path is the root, just use index.html\n htmlFilename = 'index.html'\n }\n\n const baseDir = join(outDir, dirname(htmlFilename))\n let htmlFilepath = join(outDir, htmlFilename)\n\n await fs.mkdir(baseDir, { recursive: true })\n\n const components = await loadComponents({\n distDir,\n page,\n isAppPath: isAppDir,\n isDev: false,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n // Handle App Routes.\n if (isAppDir && isAppRouteRoute(page)) {\n return exportAppRoute(\n req,\n res,\n params,\n page,\n components.routeModule as AppRouteRouteModule,\n commonRenderOpts.incrementalCache,\n commonRenderOpts.cacheLifeProfiles,\n htmlFilepath,\n fileWriter,\n commonRenderOpts.cacheComponents,\n commonRenderOpts.staticPageGenerationTimeout,\n commonRenderOpts.experimental,\n buildId,\n deploymentId\n )\n }\n\n const renderOpts: WorkerRenderOpts = {\n ...components,\n ...commonRenderOpts,\n params,\n optimizeCss,\n disableOptimizedLoading,\n locale,\n supportsDynamicResponse: false,\n // During the export phase in next build, we always enable the streaming metadata since if there's\n // any dynamic access in metadata we can determine it in the build phase.\n // If it's static, then it won't affect anything.\n // If it's dynamic, then it can be handled when request hits the route.\n serveStreamingMetadata: true,\n allowEmptyStaticShell,\n runInstantValidation,\n isFallbackUpgradeable,\n experimental: {\n ...commonRenderOpts.experimental,\n isRoutePPREnabled,\n },\n renderResumeDataCache,\n }\n\n // Handle App Pages\n if (isAppDir) {\n const sharedContext: AppSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n }\n\n return exportAppPage(\n req,\n res,\n page,\n path,\n pathname,\n query,\n fallbackRouteParams,\n renderOpts as WorkerRenderOpts<AppPageModule>,\n htmlFilepath,\n debugOutput,\n isDynamicError,\n fileWriter,\n sharedContext\n )\n } else {\n const sharedContext: PagesSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n customServer: undefined,\n }\n\n const renderContext: PagesRenderContext = {\n isFallback: exportPath._pagesFallback ?? false,\n isDraftMode: false,\n developmentNotFoundSourcePage: undefined,\n }\n\n return exportPagesPage(\n req,\n res,\n path,\n page,\n query,\n params,\n htmlFilepath,\n htmlFilename,\n pagesDataDir,\n buildExport,\n isDynamic,\n sharedContext,\n renderContext,\n hasOrigQueryValues,\n renderOpts as WorkerRenderOpts<PagesModule>,\n components,\n fileWriter\n )\n }\n}\n\nexport async function exportPages(\n input: ExportPagesInput\n): Promise<ExportPagesResult> {\n // Load native bindings in the worker process so that code frame rendering\n // (which uses the native codeFrameColumns function) works during prerendering.\n await installBindings()\n installCodeFrameSupport()\n\n const {\n exportPaths,\n dir,\n distDir,\n outDir,\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n pagesDataDir,\n renderOpts,\n nextConfig,\n options,\n renderResumeDataCachesByPage = {},\n } = input\n\n installGlobalBehaviors(nextConfig)\n\n if (nextConfig.enablePrerenderSourceMaps) {\n try {\n // Same as `next dev`\n // Limiting the stack trace to a useful amount of frames is handled by ignore-listing.\n // TODO: How high can we go without severely impacting CPU/memory?\n Error.stackTraceLimit = 50\n } catch {}\n }\n\n // If the fetch cache was enabled, we need to create an incremental\n // cache instance for this page.\n const incrementalCache = await createIncrementalCache({\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n distDir,\n dir,\n // skip writing to disk in minimal mode for now, pending some\n // changes to better support it\n flushToDisk: !hasNextSupport,\n cacheHandlers: nextConfig.cacheHandlers,\n })\n\n renderOpts.incrementalCache = incrementalCache\n\n const maxConcurrency =\n nextConfig.experimental.staticGenerationMaxConcurrency ?? 8\n const results: ExportPagesResult = []\n\n const exportPageWithRetry = async (\n exportPath: ExportPathEntry,\n maxAttempts: number\n ) => {\n const { page, path } = exportPath\n const pageKey = page !== path ? `${page}: ${path}` : path\n let attempt = 0\n let result\n\n const hasDebuggerAttached =\n // Also tests for `inspect-brk`\n process.env.NODE_OPTIONS?.includes('--inspect')\n\n const renderResumeDataCache = renderResumeDataCachesByPage[pageKey]\n ? createRenderResumeDataCache(\n renderResumeDataCachesByPage[pageKey],\n renderOpts.experimental.maxPostponedStateSizeBytes\n )\n : undefined\n\n while (attempt < maxAttempts) {\n try {\n result = await Promise.race<ExportPageResult | undefined>([\n exportPage({\n exportPath,\n distDir,\n outDir,\n pagesDataDir,\n renderOpts,\n trailingSlash: nextConfig.trailingSlash,\n subFolders: nextConfig.trailingSlash && !options.buildExport,\n buildExport: options.buildExport,\n optimizeCss: nextConfig.experimental.optimizeCss,\n disableOptimizedLoading:\n nextConfig.experimental.disableOptimizedLoading,\n parentSpanId: input.parentSpanId,\n httpAgentOptions: nextConfig.httpAgentOptions,\n debugOutput: options.debugOutput,\n enableExperimentalReact: needsExperimentalReact(nextConfig),\n sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),\n buildId: input.buildId,\n deploymentId: input.deploymentId,\n clientAssetToken: input.clientAssetToken,\n renderResumeDataCache,\n }),\n hasDebuggerAttached\n ? // With a debugger attached, exporting can take infinitely if we paused script execution.\n new Promise(() => {})\n : // If exporting the page takes longer than the timeout, reject the promise.\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError())\n }, nextConfig.staticPageGenerationTimeout * 1000)\n }),\n ])\n\n // If there was an error in the export, throw it immediately. In the catch block, we might retry the export,\n // or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.\n if (result && 'error' in result) {\n throw new ExportPageError()\n }\n\n // If the export succeeds, break out of the retry loop\n break\n } catch (err) {\n // The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.\n // This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.\n if (!(err instanceof ExportPageError || err instanceof TimeoutError)) {\n throw err\n }\n\n if (err instanceof TimeoutError) {\n // If the export times out, we will restart the worker up to 3 times.\n maxAttempts = 3\n }\n\n // We've reached the maximum number of attempts\n if (attempt >= maxAttempts - 1) {\n // Log a message if we've reached the maximum number of attempts.\n // We only care to do this if maxAttempts was configured.\n if (maxAttempts > 1) {\n console.info(\n `Failed to build ${pageKey} after ${maxAttempts} attempts.`\n )\n }\n // If prerenderEarlyExit is enabled, we'll exit the build immediately.\n if (nextConfig.experimental.prerenderEarlyExit) {\n console.error(\n `Export encountered an error on ${pageKey}, exiting the build.`\n )\n process.exit(1)\n } else {\n // Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.\n }\n } else {\n // Otherwise, we have more attempts to make. Wait before retrying\n if (err instanceof TimeoutError) {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}) because it took more than ${nextConfig.staticPageGenerationTimeout} seconds. Retrying again shortly.`\n )\n } else {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`\n )\n }\n\n // Exponential backoff with random jitter to avoid thundering herd on retries\n const baseDelay = 500 // 500ms\n const maxDelay = 2000 // 2 seconds\n const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)\n const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter\n await new Promise((r) => setTimeout(r, delay + jitter))\n }\n }\n\n attempt++\n }\n\n return { result, path, page, pageKey }\n }\n\n for (let i = 0; i < exportPaths.length; i += maxConcurrency) {\n const subset = exportPaths.slice(i, i + maxConcurrency)\n\n const subsetResults = await Promise.all(\n subset.map((exportPath) =>\n exportPageWithRetry(\n exportPath,\n nextConfig.experimental.staticGenerationRetryCount ?? 1\n )\n )\n )\n\n results.push(...subsetResults)\n }\n\n return results\n}\n\nasync function exportPage(\n input: ExportPageInput\n): Promise<ExportPageResult | undefined> {\n trace('export-page', input.parentSpanId).setAttribute(\n 'path',\n input.exportPath.path\n )\n\n // Configure the http agent.\n setHttpClientAndAgentOptions({\n httpAgentOptions: input.httpAgentOptions,\n })\n\n const fileWriter = new MultiFileWriter({\n writeFile: (filePath, data) => fs.writeFile(filePath, data),\n mkdir: (dir) => fs.mkdir(dir, { recursive: true }),\n })\n\n const exportPageSpan = trace('export-page-worker', input.parentSpanId)\n\n const start = Date.now()\n\n const turborepoAccessTraceResult = new TurborepoAccessTraceResult()\n\n // Export the page.\n let result: ExportRouteResult | undefined\n try {\n result = await exportPageSpan.traceAsyncFn(() =>\n turborepoTraceAccess(\n () => exportPageImpl(input, fileWriter),\n turborepoAccessTraceResult\n )\n )\n\n // Wait for all the files to flush to disk.\n await fileWriter.wait()\n\n // If there was no result, then we can exit early.\n if (!result) return\n\n // If there was an error, then we can exit early.\n if ('error' in result) {\n return { error: result.error, duration: Date.now() - start }\n }\n } catch (err) {\n console.error(\n `Error occurred prerendering page \"${input.exportPath.path}\". Read more: https://nextjs.org/docs/messages/prerender-error`\n )\n\n // bailoutToCSRError errors should not leak to the user as they are not actionable; they're\n // a framework signal\n if (!isBailoutToCSRError(err)) {\n // A static generation bailout error is a framework signal to fail static generation but\n // and will encode a reason in the error message. If there is a message, we'll print it.\n // Otherwise there's nothing to show as we don't want to leak an error internal error stack to the user.\n // TODO: Always log the full error. ignore-listing will take care of hiding internal stacks.\n if (isStaticGenBailoutError(err)) {\n if (err.message) {\n console.error(`Error: ${err.message}`)\n }\n } else {\n console.error(err)\n }\n }\n\n return { error: true, duration: Date.now() - start }\n }\n\n // Notify the parent process that we processed a page (used by the progress activity indicator)\n process.send?.([3, { type: 'activity' }])\n\n // Otherwise we can return the result.\n return {\n ...result,\n duration: Date.now() - start,\n turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),\n }\n}\n\nprocess.on('unhandledRejection', (err: unknown) => {\n // we don't want to log these errors\n if (isDynamicUsageError(err)) {\n return\n }\n\n console.error(err)\n})\n\nprocess.on('rejectionHandled', () => {\n // It is ok to await a Promise late in Next.js as it allows for better\n // prefetching patterns to avoid waterfalls. We ignore logging these.\n // We should've already errored in anyway unhandledRejection.\n})\n\nconst FATAL_UNHANDLED_NEXT_API_EXIT_CODE = 78\n\nprocess.on('uncaughtException', (err) => {\n if (isDynamicUsageError(err)) {\n console.error(\n 'A Next.js API that uses exceptions to signal framework behavior was uncaught. This suggests improper usage of a Next.js API. The original error is printed below and the build will now exit.'\n )\n console.error(err)\n process.exit(FATAL_UNHANDLED_NEXT_API_EXIT_CODE)\n } else {\n console.error(err)\n }\n})\n"],"names":["installBindings","installCodeFrameSupport","process","env","NEXT_IS_EXPORT_WORKER","extname","join","dirname","sep","fs","loadComponents","isDynamicRoute","normalizePagePath","normalizeLocalePath","trace","setHttpClientAndAgentOptions","addRequestMeta","normalizeAppPath","removeTrailingSlash","createRequestResponseMocks","isAppRouteRoute","hasNextSupport","exportAppRoute","exportAppPage","exportPagesPage","getParams","createIncrementalCache","isDynamicUsageError","isBailoutToCSRError","turborepoTraceAccess","TurborepoAccessTraceResult","createOpaqueFallbackRouteParams","needsExperimentalReact","isStaticGenBailoutError","MultiFileWriter","createRenderResumeDataCache","installGlobalBehaviors","globalThis","__NEXT_DATA__","nextExport","TimeoutError","Error","code","ExportPageError","exportPageImpl","input","fileWriter","req","exportPath","distDir","pagesDataDir","buildExport","subFolders","optimizeCss","disableOptimizedLoading","debugOutput","enableExperimentalReact","trailingSlash","sriEnabled","renderOpts","commonRenderOpts","outDir","commonOutDir","buildId","deploymentId","clientAssetToken","renderResumeDataCache","__NEXT_EXPERIMENTAL_REACT","path","page","_fallbackRouteParams","_isAppDir","isAppDir","_isDynamicError","isDynamicError","_isRoutePPREnabled","isRoutePPREnabled","_allowEmptyStaticShell","allowEmptyStaticShell","_runInstantValidation","runInstantValidation","_isFallbackUpgradeable","isFallbackUpgradeable","query","originalQuery","fallbackRouteParams","pathname","isDynamic","filePath","updatedPath","_ssgPath","locale","_locale","localePathResult","locales","detectedLocale","hasOrigQueryValues","Object","keys","length","nonLocalizedPath","params","normalizedPage","res","url","statusCode","some","p","endsWith","domainLocales","dl","defaultLocale","includes","getHtmlFilename","htmlFilename","pageExt","pathExt","isBuiltinPaths","isHtmlExtPath","baseDir","htmlFilepath","mkdir","recursive","components","isAppPath","isDev","needsManifestsForLegacyReasons","routeModule","incrementalCache","cacheLifeProfiles","cacheComponents","staticPageGenerationTimeout","experimental","supportsDynamicResponse","serveStreamingMetadata","sharedContext","customServer","undefined","renderContext","isFallback","_pagesFallback","isDraftMode","developmentNotFoundSourcePage","exportPages","exportPaths","dir","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","nextConfig","options","renderResumeDataCachesByPage","enablePrerenderSourceMaps","stackTraceLimit","flushToDisk","cacheHandlers","maxConcurrency","staticGenerationMaxConcurrency","results","exportPageWithRetry","maxAttempts","pageKey","attempt","result","hasDebuggerAttached","NODE_OPTIONS","maxPostponedStateSizeBytes","Promise","race","exportPage","parentSpanId","httpAgentOptions","Boolean","sri","algorithm","_","reject","setTimeout","err","console","info","prerenderEarlyExit","error","exit","baseDelay","maxDelay","delay","Math","min","pow","jitter","random","r","i","subset","slice","subsetResults","all","map","staticGenerationRetryCount","push","setAttribute","writeFile","data","exportPageSpan","start","Date","now","turborepoAccessTraceResult","traceAsyncFn","wait","duration","message","send","type","serialize","on","FATAL_UNHANDLED_NEXT_API_EXIT_CODE"],"mappings":"AAYA,OAAO,6BAA4B;AACnC,SAASA,eAAe,QAAQ,gCAA+B;AAC/D,SAASC,uBAAuB,QAAQ,mCAAkC;AAE1EC,QAAQC,GAAG,CAACC,qBAAqB,GAAG;AAEpC,SAASC,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAEC,GAAG,QAAQ,OAAM;AAClD,OAAOC,QAAQ,cAAa;AAC5B,SAASC,cAAc,QAAQ,4BAA2B;AAC1D,SAASC,cAAc,QAAQ,wCAAuC;AACtE,SAASC,iBAAiB,QAAQ,8CAA6C;AAC/E,SAASC,mBAAmB,QAAQ,2CAA0C;AAC9E,SAASC,KAAK,QAAQ,WAAU;AAChC,SAASC,4BAA4B,QAAQ,iC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K,CAACJ;AAChB;AAEAhL,QAAQsN,EAAE,CAAC,oBAAoB;AAC7B,sEAAsE;AACtE,qEAAqE;AACrE,6DAA6D;AAC/D;AAEA,MAAMC,qCAAqC;AAE3CvN,QAAQsN,EAAE,CAAC,qBAAqB,CAACtC;IAC/B,IAAIvJ,oBAAoBuJ,MAAM;QAC5BC,QAAQG,KAAK,CACX;QAEFH,QAAQG,KAAK,CAACJ;QACdhL,QAAQqL,IAAI,CAACkC;IACf,OAAO;QACLtC,QAAQG,KAAK,CAACJ;IAChB;AACF","ignoreList":[0]}

@@ -20,3 +20,3 @@ import { readFileSync, writeFileSync } from 'fs';

const data = await res.json();
const versionData = data.versions["16.3.1-canary.11"];
const versionData = data.versions["16.3.1-canary.12"];
return {

@@ -54,3 +54,3 @@ os: versionData.os,

lockfileParsed.dependencies[pkg] = {
version: "16.3.1-canary.11",
version: "16.3.1-canary.12",
resolved: pkgData.tarball,

@@ -63,3 +63,3 @@ integrity: pkgData.integrity,

lockfileParsed.packages[pkg] = {
version: "16.3.1-canary.11",
version: "16.3.1-canary.12",
resolved: pkgData.tarball,

@@ -66,0 +66,0 @@ integrity: pkgData.integrity,

@@ -58,4 +58,4 @@ import { propagateSubtreeBits } from '../../shared/lib/app-router-types';

async function createComponentTreeInternal({ loaderTree: tree, parentParams, parentOptionalCatchAllParamName, rootLayoutIncluded, injectedCSS, injectedJS, injectedFontPreloadTags, ctx, missingSlots, preloadCallbacks, authInterrupts, MetadataOutlet, isPrerendering, hintTree }, isRoot, workUnitStore) {
const { renderOpts: { nextConfigOutput, experimental, cacheComponents }, workStore, componentMod: { createElement, Fragment, SegmentViewNode, HTTPAccessFallbackBoundary, LayoutRouter, RenderFromTemplateContext, ClientPageRoot, ClientSegmentRoot, createServerSearchParamsForServerPage, createPrerenderSearchParamsForClientPage, createServerParamsForServerSegment, createPrerenderParamsForClientSegment, serverHooks: { DynamicServerError }, Postpone }, pagePath, getDynamicParamFromSegment, isPrefetch, renderCapabilities, query } = ctx;
const { canPostpone, isPossiblyPartialResponse } = renderCapabilities;
const { renderOpts: { nextConfigOutput, experimental, cacheComponents }, workStore, componentMod: { createElement, Fragment, SegmentViewNode, HTTPAccessFallbackBoundary, LayoutRouter, RenderFromTemplateContext, ClientPageRoot, ClientSegmentRoot, createServerSearchParamsForServerPage, createPrerenderSearchParamsForClientPage, createServerParamsForServerSegment, createPrerenderParamsForClientSegment, serverHooks: { DynamicServerError } }, pagePath, getDynamicParamFromSegment, isPrefetch, renderCapabilities, query } = ctx;
const { isPossiblyPartialResponse } = renderCapabilities;
const { page, conventionPath, segment, modules, parallelRoutes } = parseLoaderTree(tree);

@@ -156,6 +156,3 @@ const prefetchInliningEnabled = Boolean(experimental.prefetchInlining);

workStore.forceDynamic = true;
// TODO: (PPR) remove this bailout once PPR is the default
if (isPrerendering && !canPostpone) {
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
if (isPrerendering) {
const err = Object.defineProperty(new DynamicServerError(`Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`), "__NEXT_ERROR_CODE", {

@@ -187,3 +184,2 @@ value: "E585",

case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.revalidate > defaultRevalidate) {

@@ -206,5 +202,3 @@ workUnitStore.revalidate = defaultRevalidate;

}
if (!workStore.forceStatic && isPrerendering && defaultRevalidate === 0 && // If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
!canPostpone) {
if (!workStore.forceStatic && isPrerendering && defaultRevalidate === 0) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}`;

@@ -228,3 +222,2 @@ workStore.dynamicUsageDescription = dynamicUsageDescription;

case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.stale > pageStaleTime) {

@@ -491,23 +484,2 @@ workUnitStore.stale = pageStaleTime;

const Component = MaybeComponent;
// If force-dynamic is used and the current render supports postponing, we
// replace it with a node that will postpone the render. This ensures that the
// postpone is invoked during the react render phase and not during the next
// render phase.
// @TODO this does not actually do what it seems like it would or should do. The idea is that
// if we are rendering in a force-dynamic mode and we can postpone we should only make the segments
// that ask for force-dynamic to be dynamic, allowing other segments to still prerender. However
// because this comes after the children traversal and the static generation store is mutated every segment
// along the parent path of a force-dynamic segment will hit this condition effectively making the entire
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if (canPostpone && workStore.forceDynamic) {
return createTransportNode(ctx, transportSegment, prefetchHints, createElement(Fragment, {
key: cacheNodeKey
}, createElement(Postpone, {
reason: 'dynamic = "force-dynamic" was used',
route: workStore.route
}), layerAssets), parallelRouteNodes, loadingData, true, // force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
emptyVaryParamsAccumulator);
}
const isClientComponent = isClientReference(layoutOrPageMod);

@@ -514,0 +486,0 @@ const varyParamsAccumulator = isClientComponent && cacheComponents ? // from the server, so they have an empty vary params set.

@@ -36,3 +36,2 @@ /**

import { createUnrenderedSegmentError } from '../../shared/lib/instant-messages';
const hasPostpone = typeof React.unstable_postpone === 'function';
export function createDynamicTrackingState(isDebugDynamicAccesses) {

@@ -83,3 +82,2 @@ return {

case 'prerender-legacy':
case 'prerender-ppr':
case 'request':

@@ -105,4 +103,2 @@ case 'generate-static-params':

switch(workUnitStore.type){
case 'prerender-ppr':
return postponeWithTracking(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -170,3 +166,2 @@ workUnitStore.revalidate = 0;

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':

@@ -249,38 +244,2 @@ case 'validation-client':

}
export function Postpone({ reason, route }) {
const prerenderStore = workUnitAsyncStorage.getStore();
const dynamicTracking = prerenderStore && prerenderStore.type === 'prerender-ppr' ? prerenderStore.dynamicTracking : null;
postponeWithTracking(route, reason, dynamicTracking);
}
export function postponeWithTracking(route, expression, dynamicTracking) {
assertPostpone();
if (dynamicTracking) {
dynamicTracking.dynamicAccesses.push({
// When we aren't debugging, we don't need to create another error for the
// stack trace.
stack: dynamicTracking.isDebugDynamicAccesses ? new Error().stack : undefined,
expression
});
}
React.unstable_postpone(createPostponeReason(route, expression));
}
function createPostponeReason(route, expression) {
return `Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` + `React throws this special object to indicate where. It should not be caught by ` + `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;
}
export function isDynamicPostpone(err) {
if (typeof err === 'object' && err !== null && typeof err.message === 'string') {
return isDynamicPostponeReason(err.message);
}
return false;
}
function isDynamicPostponeReason(reason) {
return reason.includes('needs to bail out of prerendering at this point because it used') && reason.includes('Learn more: https://nextjs.org/docs/messages/ppr-caught-error');
}
if (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {
throw Object.defineProperty(new Error('Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'), "__NEXT_ERROR_CODE", {
value: "E296",
enumerable: false,
configurable: true
});
}
const NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED';

@@ -332,15 +291,3 @@ function createPrerenderInterruptedError(message) {

}
function assertPostpone() {
if (!hasPostpone) {
throw Object.defineProperty(new Error(`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`), "__NEXT_ERROR_CODE", {
value: "E224",
enumerable: false,
configurable: true
});
}
}
/**
* This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's
* abort semantics slightly.
*/ export function createRenderInBrowserAbortSignal() {
export function createRenderInBrowserAbortSignal() {
const controller = new AbortController();

@@ -387,3 +334,2 @@ controller.abort(Object.defineProperty(new BailoutToCSRError('Render in Browser'), "__NEXT_ERROR_CODE", {

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -432,10 +378,2 @@ case 'request':

});
case 'prerender-ppr':
{
const fallbackParams = workUnitStore.fallbackRouteParams;
if (fallbackParams && fallbackParams.size > 0) {
return postponeWithTracking(workStore.route, expression, workUnitStore.dynamicTracking);
}
break;
}
case 'validation-client':

@@ -494,3 +432,2 @@ {

case 'prerender-legacy':
case 'prerender-ppr':
{

@@ -497,0 +434,0 @@ if (workStore.forceStatic) {

@@ -206,3 +206,2 @@ /* eslint-disable import/no-extraneous-dependencies */ import 'server-only';

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -209,0 +208,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/app-render/encryption.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport 'server-only'\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport { renderToReadableStream } from 'react-server-dom-webpack/server'\n/* eslint-disable import/no-extraneous-dependencies */\nimport { createFromReadableStream } from 'react-server-dom-webpack/client'\n\nimport { streamToString } from '../stream-utils/node-web-streams-helper'\nimport {\n arrayBufferToString,\n decrypt,\n encrypt,\n getActionEncryptionKey,\n stringToUint8Array,\n} from './encryption-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from './manifests-singleton'\nimport {\n getCacheSignal,\n getResumeDataCache,\n workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from './dynamic-rendering'\nimport React from 'react'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Decrypt the serialized string with the action id as the salt.\n */\nasync function decodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (typeof key === 'undefined') {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get the iv (16 bytes) and the payload from the arg.\n const originalPayload = atob(arg)\n const ivValue = originalPayload.slice(0, 16)\n const payload = originalPayload.slice(16)\n\n const decrypted = textDecoder.decode(\n await decrypt(key, stringToUint8Array(ivValue), stringToUint8Array(payload))\n )\n\n if (!decrypted.startsWith(actionId)) {\n throw new Error('Invalid Server Action payload: failed to decrypt.')\n }\n\n return decrypted.slice(actionId.length)\n}\n\n/**\n * Encrypt the serialized string with the action id as the salt. Add a prefix to\n * later ensure that the payload is correctly decrypted, similar to a checksum.\n */\nasync function encodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (key === undefined) {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get 16 random bytes as iv.\n const randomBytes = new Uint8Array(16)\n workUnitAsyncStorage.exit(() => crypto.getRandomValues(randomBytes))\n const ivValue = arrayBufferToString(randomBytes.buffer)\n\n const encrypted = await encrypt(\n key,\n randomBytes,\n textEncoder.encode(actionId + arg)\n )\n\n return btoa(ivValue + arrayBufferToString(encrypted))\n}\n\nenum ReadStatus {\n Ready,\n Pending,\n Complete,\n}\n\n// Encrypts the action's bound args into a string. For the same combination of\n// actionId and args the same cached promise is returned. This ensures reference\n// equality for returned objects from \"use cache\" functions when they're invoked\n// multiple times within one render pass using the same bound args.\nexport const encryptActionBoundArgs = React.cache(\n async function encryptActionBoundArgs(actionId: string, ...args: any[]) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const cacheSignal = workUnitStore\n ? getCacheSignal(workUnitStore)\n : undefined\n\n const { clientModules } = getClientReferenceManifest()\n\n // Create an error before any asynchronous calls, to capture the original\n // call stack in case we need it when the serialization errors.\n const error = new Error()\n Error.captureStackTrace(error, encryptActionBoundArgs)\n\n let didCatchError = false\n\n const hangingInputAbortSignal = workUnitStore\n ? createHangingInputAbortSignal(workUnitStore)\n : undefined\n\n let readStatus = ReadStatus.Ready\n function startReadOnce() {\n if (readStatus === ReadStatus.Ready) {\n readStatus = ReadStatus.Pending\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readStatus === ReadStatus.Pending) {\n cacheSignal?.endRead()\n }\n readStatus = ReadStatus.Complete\n }\n\n // streamToString might take longer than a microtask to resolve and then other things\n // waiting on the cache signal might not realize there is another cache to fill so if\n // we are no longer waiting on the bound args serialization via the hangingInputAbortSignal\n // we should eagerly start the cache read to prevent other readers of the cache signal from\n // missing this cache fill. We use a idempotent function to only start reading once because\n // it's also possible that streamToString finishes before the hangingInputAbortSignal aborts.\n if (hangingInputAbortSignal && cacheSignal) {\n hangingInputAbortSignal.addEventListener('abort', startReadOnce, {\n once: true,\n })\n }\n\n const resumeDataCache = workUnitStore\n ? getResumeDataCache(workUnitStore)\n : null\n\n // Using Flight to serialize the args into a string.\n const serialized = await streamToString(\n renderToReadableStream(args, clientModules, {\n filterStackFrame,\n signal: hangingInputAbortSignal,\n debugChannel:\n // In Cache Components, we want to cache the encrypted result,\n // and we use the unencrypted bound args as a cache key.\n // In order to do that we need to strip debug info, because it\n // contains timing information and thus changes each time we serialize the args.\n // We can do this by piping debug info into a debug channel that throws it away.\n //\n // Note that this can result in dangling debug info references when we decode the bound args,\n // but React ignores those as long as no debug channel is passed on the decode side, so it's fine:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n process.env.NODE_ENV === 'development' && resumeDataCache\n ? {\n writable: new WritableStream(),\n }\n : undefined,\n onError(err) {\n if (hangingInputAbortSignal?.aborted) {\n return\n }\n\n // We're only reporting one error at a time, starting with the first.\n if (didCatchError) {\n return\n }\n\n didCatchError = true\n\n // Use the original error message together with the previously created\n // stack, because err.stack is a useless Flight Server call stack.\n error.message = err instanceof Error ? err.message : String(err)\n },\n }),\n // We pass the abort signal to `streamToString` so that no chunks are\n // included that are emitted after the signal was already aborted. This\n // ensures that we can encode hanging promises.\n hangingInputAbortSignal\n )\n\n if (didCatchError) {\n if (process.env.NODE_ENV === 'development') {\n // Logging the error is needed for server functions that are passed to the\n // client where the decryption is not done during rendering. Console\n // replaying allows us to still show the error dev overlay in this case.\n console.error(error)\n }\n\n endReadIfStarted()\n throw error\n }\n\n if (!workUnitStore) {\n // We don't need to call cacheSignal.endRead here because we can't have a cacheSignal\n // if we do not have a workUnitStore.\n return encodeActionBoundArg(actionId, serialized)\n }\n\n startReadOnce()\n\n const cacheKey = actionId + serialized\n\n const cachedEncrypted = resumeDataCache?.encryptedBoundArgs.get(cacheKey)\n\n if (cachedEncrypted) {\n return cachedEncrypted\n }\n\n const encrypted = await encodeActionBoundArg(actionId, serialized)\n\n endReadIfStarted()\n if (resumeDataCache?.mutable) {\n resumeDataCache.encryptedBoundArgs.set(cacheKey, encrypted)\n }\n\n return encrypted\n }\n)\n\n// Decrypts the action's bound args from the encrypted string.\nexport async function decryptActionBoundArgs(\n actionId: string,\n encryptedPromise: Promise<string>\n) {\n const encrypted = await encryptedPromise\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n let decrypted: string | undefined\n\n if (workUnitStore) {\n const cacheSignal = getCacheSignal(workUnitStore)\n const resumeDataCache = getResumeDataCache(workUnitStore)\n\n decrypted = resumeDataCache?.decryptedBoundArgs.get(encrypted)\n\n if (!decrypted) {\n cacheSignal?.beginRead()\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n cacheSignal?.endRead()\n if (resumeDataCache?.mutable) {\n resumeDataCache.decryptedBoundArgs.set(encrypted, decrypted)\n }\n }\n } else {\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n }\n\n const { edgeRscModuleMapping, rscModuleMapping } =\n getClientReferenceManifest()\n\n // Using Flight to deserialize the args from the string.\n const deserialized = await createFromReadableStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue(textEncoder.encode(decrypted))\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // Explicitly don't close the stream here (until prerendering is\n // complete) so that hanging promises are not rejected.\n if (workUnitStore.renderSignal.aborted) {\n controller.close()\n } else {\n workUnitStore.renderSignal.addEventListener(\n 'abort',\n () => controller.close(),\n { once: true }\n )\n }\n break\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return controller.close()\n default:\n workUnitStore satisfies never\n }\n },\n }),\n {\n findSourceMapURL,\n // NOTE: When we serialized the bound args, we may have used a dummy debug channel to strip debug info.\n // In that case, it's important that we also *don't* pass a debug channel here, because that will make\n // the Flight Client ignore the dangling references:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n debugChannel: undefined,\n serverConsumerManifest: {\n // moduleLoading must be null because we don't want to trigger preloads of ClientReferences\n // to be added to the current execution. Instead, we'll wait for any ClientReference\n // to be emitted which themselves will handle the preloading.\n moduleLoading: null,\n moduleMap: isEdgeRuntime ? edgeRscModuleMapping : rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n }\n )\n\n return deserialized\n}\n"],"names":["renderToReadableStream","createFromReadableStream","streamToString","arrayBufferToString","decrypt","encrypt","getActionEncryptionKey","stringToUint8Array","getClientReferenceManifest","getServerModuleMap","getCacheSignal","getResumeDataCache","workUnitAsyncStorage","createHangingInputAbortSignal","React","isEdgeRuntime","process","env","NEXT_RUNTIME","textEncoder","TextEncoder","textDecoder","TextDecoder","filterStackFrame","NODE_ENV","require","filterStackFrameDEV","undefined","findSourceMapURL","findSourceMapURLDEV","decodeActionBoundArg","actionId","arg","key","Error","originalPayload","atob","ivValue","slice","payload","decrypted","decode","startsWith","length","encodeActionBoundArg","randomBytes","Uint8Array","exit","crypto","getRandomValues","buffer","encrypted","encode","btoa","ReadStatus","encryptActionBoundArgs","cache","args","workUnitStore","getStore","cacheSignal","clientModules","error","captureStackTrace","didCatchError","hangingInputAbortSignal","readStatus","startReadOnce","beginRead","endReadIfStarted","endRead","addEventListener","once","resumeDataCache","serialized","signal","debugChannel","writable","WritableStream","onError","err","aborted","message","String","console","cacheKey","cachedEncrypted","encryptedBoundArgs","get","mutable","set","decryptActionBoundArgs","encryptedPromise","decryptedBoundArgs","edgeRscModuleMapping","rscModuleMapping","deserialized","ReadableStream","start","controller","enqueue","type","renderSignal","close","serverConsumerManifest","moduleLoading","moduleMap","serverModuleMap"],"mappings":"AAAA,oDAAoD,GACpD,OAAO,cAAa;AAEpB,oDAAoD,GACpD,SAASA,sBAAsB,QAAQ,kCAAiC;AACxE,oDAAoD,GACpD,SAASC,wBAAwB,QAAQ,kCAAiC;AAE1E,SAASC,cAAc,QAAQ,0CAAyC;AACxE,SACEC,mBAAmB,EACnBC,OAAO,EACPC,OAAO,EACPC,sBAAsB,EACtBC,kBAAkB,QACb,qBAAoB;AAC3B,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,wBAAuB;AAC9B,SACEC,cAAc,EACdC,kBAAkB,EAClBC,oBAAoB,QACf,qCAAoC;AAC3C,SAASC,6BAA6B,QAAQ,sBAAqB;AACnE,OAAOC,WAAW,QAAO;AAEzB,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD,MAAMC,cAAc,IAAIC;AACxB,MAAMC,cAAc,IAAIC;AAExB,MAAMC,mBACJP,QAAQC,GAAG,CAACO,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AACN,MAAMC,mBACJZ,QAAQC,GAAG,CAACO,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNI,mBAAmB,GACtBF;AAEN;;CAEC,GACD,eAAeG,qBAAqBC,QAAgB,EAAEC,GAAW;IAC/D,MAAMC,MAAM,MAAM3B;IACl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5BhB,gBAAgBoB,kBAAkB,CAACH,GAAG,CAACvC,WAAWX;YACpD;QACF;IACF,OAAO;QACLA,YAAY,MAAMV,qBAAqBC,UAAUoB;IACnD;IAEA,MAAM,EAAE2C,oBAAoB,EAAEC,gBAAgB,EAAE,GAC9CvF;IAEF,wDAAwD;IACxD,MAAMwF,eAAe,MAAM/F,yBACzB,IAAIgG,eAAe;QACjBC,OAAMC,UAAU;YACdA,WAAWC,OAAO,CAACjF,YAAYiC,MAAM,CAACZ;YAEtC,OAAQkB,iCAAAA,cAAe2C,IAAI;gBACzB,KAAK;gBACL,KAAK;oBACH,gEAAgE;oBAChE,uDAAuD;oBACvD,IAAI3C,cAAc4C,YAAY,CAACrB,OAAO,EAAE;wBACtCkB,WAAWI,KAAK;oBAClB,OAAO;wBACL7C,cAAc4C,YAAY,CAAC/B,gBAAgB,CACzC,SACA,IAAM4B,WAAWI,KAAK,IACtB;4BAAE/B,MAAM;wBAAK;oBAEjB;oBACA;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK7C;oBACH,OAAOwE,WAAWI,KAAK;gBACzB;oBACE7C;YACJ;QACF;IACF,IACA;QACE9B;QACA,uGAAuG;QACvG,sGAAsG;QACtG,oDAAoD;QACpD,6IAA6I;QAC7I,6IAA6I;QAC7IgD,cAAcjD;QACd6E,wBAAwB;YACtB,2FAA2F;YAC3F,oFAAoF;YACpF,6DAA6D;YAC7DC,eAAe;YACfC,WAAW3F,gBAAgB+E,uBAAuBC;YAClDY,iBAAiBlG;QACnB;IACF;IAGF,OAAOuF;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/app-render/encryption.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport 'server-only'\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport { renderToReadableStream } from 'react-server-dom-webpack/server'\n/* eslint-disable import/no-extraneous-dependencies */\nimport { createFromReadableStream } from 'react-server-dom-webpack/client'\n\nimport { streamToString } from '../stream-utils/node-web-streams-helper'\nimport {\n arrayBufferToString,\n decrypt,\n encrypt,\n getActionEncryptionKey,\n stringToUint8Array,\n} from './encryption-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from './manifests-singleton'\nimport {\n getCacheSignal,\n getResumeDataCache,\n workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from './dynamic-rendering'\nimport React from 'react'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Decrypt the serialized string with the action id as the salt.\n */\nasync function decodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (typeof key === 'undefined') {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get the iv (16 bytes) and the payload from the arg.\n const originalPayload = atob(arg)\n const ivValue = originalPayload.slice(0, 16)\n const payload = originalPayload.slice(16)\n\n const decrypted = textDecoder.decode(\n await decrypt(key, stringToUint8Array(ivValue), stringToUint8Array(payload))\n )\n\n if (!decrypted.startsWith(actionId)) {\n throw new Error('Invalid Server Action payload: failed to decrypt.')\n }\n\n return decrypted.slice(actionId.length)\n}\n\n/**\n * Encrypt the serialized string with the action id as the salt. Add a prefix to\n * later ensure that the payload is correctly decrypted, similar to a checksum.\n */\nasync function encodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (key === undefined) {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get 16 random bytes as iv.\n const randomBytes = new Uint8Array(16)\n workUnitAsyncStorage.exit(() => crypto.getRandomValues(randomBytes))\n const ivValue = arrayBufferToString(randomBytes.buffer)\n\n const encrypted = await encrypt(\n key,\n randomBytes,\n textEncoder.encode(actionId + arg)\n )\n\n return btoa(ivValue + arrayBufferToString(encrypted))\n}\n\nenum ReadStatus {\n Ready,\n Pending,\n Complete,\n}\n\n// Encrypts the action's bound args into a string. For the same combination of\n// actionId and args the same cached promise is returned. This ensures reference\n// equality for returned objects from \"use cache\" functions when they're invoked\n// multiple times within one render pass using the same bound args.\nexport const encryptActionBoundArgs = React.cache(\n async function encryptActionBoundArgs(actionId: string, ...args: any[]) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const cacheSignal = workUnitStore\n ? getCacheSignal(workUnitStore)\n : undefined\n\n const { clientModules } = getClientReferenceManifest()\n\n // Create an error before any asynchronous calls, to capture the original\n // call stack in case we need it when the serialization errors.\n const error = new Error()\n Error.captureStackTrace(error, encryptActionBoundArgs)\n\n let didCatchError = false\n\n const hangingInputAbortSignal = workUnitStore\n ? createHangingInputAbortSignal(workUnitStore)\n : undefined\n\n let readStatus = ReadStatus.Ready\n function startReadOnce() {\n if (readStatus === ReadStatus.Ready) {\n readStatus = ReadStatus.Pending\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readStatus === ReadStatus.Pending) {\n cacheSignal?.endRead()\n }\n readStatus = ReadStatus.Complete\n }\n\n // streamToString might take longer than a microtask to resolve and then other things\n // waiting on the cache signal might not realize there is another cache to fill so if\n // we are no longer waiting on the bound args serialization via the hangingInputAbortSignal\n // we should eagerly start the cache read to prevent other readers of the cache signal from\n // missing this cache fill. We use a idempotent function to only start reading once because\n // it's also possible that streamToString finishes before the hangingInputAbortSignal aborts.\n if (hangingInputAbortSignal && cacheSignal) {\n hangingInputAbortSignal.addEventListener('abort', startReadOnce, {\n once: true,\n })\n }\n\n const resumeDataCache = workUnitStore\n ? getResumeDataCache(workUnitStore)\n : null\n\n // Using Flight to serialize the args into a string.\n const serialized = await streamToString(\n renderToReadableStream(args, clientModules, {\n filterStackFrame,\n signal: hangingInputAbortSignal,\n debugChannel:\n // In Cache Components, we want to cache the encrypted result,\n // and we use the unencrypted bound args as a cache key.\n // In order to do that we need to strip debug info, because it\n // contains timing information and thus changes each time we serialize the args.\n // We can do this by piping debug info into a debug channel that throws it away.\n //\n // Note that this can result in dangling debug info references when we decode the bound args,\n // but React ignores those as long as no debug channel is passed on the decode side, so it's fine:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n process.env.NODE_ENV === 'development' && resumeDataCache\n ? {\n writable: new WritableStream(),\n }\n : undefined,\n onError(err) {\n if (hangingInputAbortSignal?.aborted) {\n return\n }\n\n // We're only reporting one error at a time, starting with the first.\n if (didCatchError) {\n return\n }\n\n didCatchError = true\n\n // Use the original error message together with the previously created\n // stack, because err.stack is a useless Flight Server call stack.\n error.message = err instanceof Error ? err.message : String(err)\n },\n }),\n // We pass the abort signal to `streamToString` so that no chunks are\n // included that are emitted after the signal was already aborted. This\n // ensures that we can encode hanging promises.\n hangingInputAbortSignal\n )\n\n if (didCatchError) {\n if (process.env.NODE_ENV === 'development') {\n // Logging the error is needed for server functions that are passed to the\n // client where the decryption is not done during rendering. Console\n // replaying allows us to still show the error dev overlay in this case.\n console.error(error)\n }\n\n endReadIfStarted()\n throw error\n }\n\n if (!workUnitStore) {\n // We don't need to call cacheSignal.endRead here because we can't have a cacheSignal\n // if we do not have a workUnitStore.\n return encodeActionBoundArg(actionId, serialized)\n }\n\n startReadOnce()\n\n const cacheKey = actionId + serialized\n\n const cachedEncrypted = resumeDataCache?.encryptedBoundArgs.get(cacheKey)\n\n if (cachedEncrypted) {\n return cachedEncrypted\n }\n\n const encrypted = await encodeActionBoundArg(actionId, serialized)\n\n endReadIfStarted()\n if (resumeDataCache?.mutable) {\n resumeDataCache.encryptedBoundArgs.set(cacheKey, encrypted)\n }\n\n return encrypted\n }\n)\n\n// Decrypts the action's bound args from the encrypted string.\nexport async function decryptActionBoundArgs(\n actionId: string,\n encryptedPromise: Promise<string>\n) {\n const encrypted = await encryptedPromise\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n let decrypted: string | undefined\n\n if (workUnitStore) {\n const cacheSignal = getCacheSignal(workUnitStore)\n const resumeDataCache = getResumeDataCache(workUnitStore)\n\n decrypted = resumeDataCache?.decryptedBoundArgs.get(encrypted)\n\n if (!decrypted) {\n cacheSignal?.beginRead()\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n cacheSignal?.endRead()\n if (resumeDataCache?.mutable) {\n resumeDataCache.decryptedBoundArgs.set(encrypted, decrypted)\n }\n }\n } else {\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n }\n\n const { edgeRscModuleMapping, rscModuleMapping } =\n getClientReferenceManifest()\n\n // Using Flight to deserialize the args from the string.\n const deserialized = await createFromReadableStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue(textEncoder.encode(decrypted))\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // Explicitly don't close the stream here (until prerendering is\n // complete) so that hanging promises are not rejected.\n if (workUnitStore.renderSignal.aborted) {\n controller.close()\n } else {\n workUnitStore.renderSignal.addEventListener(\n 'abort',\n () => controller.close(),\n { once: true }\n )\n }\n break\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return controller.close()\n default:\n workUnitStore satisfies never\n }\n },\n }),\n {\n findSourceMapURL,\n // NOTE: When we serialized the bound args, we may have used a dummy debug channel to strip debug info.\n // In that case, it's important that we also *don't* pass a debug channel here, because that will make\n // the Flight Client ignore the dangling references:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n debugChannel: undefined,\n serverConsumerManifest: {\n // moduleLoading must be null because we don't want to trigger preloads of ClientReferences\n // to be added to the current execution. Instead, we'll wait for any ClientReference\n // to be emitted which themselves will handle the preloading.\n moduleLoading: null,\n moduleMap: isEdgeRuntime ? edgeRscModuleMapping : rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n }\n )\n\n return deserialized\n}\n"],"names":["renderToReadableStream","createFromReadableStream","streamToString","arrayBufferToString","decrypt","encrypt","getActionEncryptionKey","stringToUint8Array","getClientReferenceManifest","getServerModuleMap","getCacheSignal","getResumeDataCache","workUnitAsyncStorage","createHangingInputAbortSignal","React","isEdgeRuntime","process","env","NEXT_RUNTIME","textEncoder","TextEncoder","textDecoder","TextDecoder","filterStackFrame","NODE_ENV","require","filterStackFrameDEV","undefined","findSourceMapURL","findSourceMapURLDEV","decodeActionBoundArg","actionId","arg","key","Error","originalPayload","atob","ivValue","slice","payload","decrypted","decode","startsWith","length","encodeActionBoundArg","randomBytes","Uint8Array","exit","crypto","getRandomValues","buffer","encrypted","encode","btoa","ReadStatus","encryptActionBoundArgs","cache","args","workUnitStore","getStore","cacheSignal","clientModules","error","captureStackTrace","didCatchError","hangingInputAbortSignal","readStatus","startReadOnce","beginRead","endReadIfStarted","endRead","addEventListener","once","resumeDataCache","serialized","signal","debugChannel","writable","WritableStream","onError","err","aborted","message","String","console","cacheKey","cachedEncrypted","encryptedBoundArgs","get","mutable","set","decryptActionBoundArgs","encryptedPromise","decryptedBoundArgs","edgeRscModuleMapping","rscModuleMapping","deserialized","ReadableStream","start","controller","enqueue","type","renderSignal","close","serverConsumerManifest","moduleLoading","moduleMap","serverModuleMap"],"mappings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ACvD,IAAI3C,cAAc4C,YAAY,CAACrB,OAAO,EAAE;wBACtCkB,WAAWI,KAAK;oBAClB,OAAO;wBACL7C,cAAc4C,YAAY,CAAC/B,gBAAgB,CACzC,SACA,IAAM4B,WAAWI,KAAK,IACtB;4BAAE/B,MAAM;wBAAK;oBAEjB;oBACA;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK7C;oBACH,OAAOwE,WAAWI,KAAK;gBACzB;oBACE7C;YACJ;QACF;IACF,IACA;QACE9B;QACA,uGAAuG;QACvG,sGAAsG;QACtG,oDAAoD;QACpD,6IAA6I;QAC7I,6IAA6I;QAC7IgD,cAAcjD;QACd6E,wBAAwB;YACtB,2FAA2F;YAC3F,oFAAoF;YACpF,6DAA6D;YAC7DC,eAAe;YACfC,WAAW3F,gBAAgB+E,uBAAuBC;YAClDY,iBAAiBlG;QACnB;IACF;IAGF,OAAOuF;AACT","ignoreList":[0]}

@@ -28,3 +28,2 @@ // eslint-disable-next-line import/no-extraneous-dependencies

export { isEmptyHTMLPrelude } from './postponed-state';
export { Postpone } from './rsc/postpone';
export { taintObjectReference } from './rsc/taint';

@@ -57,4 +56,2 @@ export { collectSegmentData, collectPrefetchHints } from './collect-segment-data';

}
// patchFetch makes use of APIs such as `React.unstable_postpone` which are only available
// in the experimental channel of React, so export it from here so that it comes from the bundled runtime
export function patchFetch() {

@@ -61,0 +58,0 @@ return _patchFetch({

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/app-render/entry-base.ts"],"sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nexport {\n createTemporaryReferenceSet,\n renderToReadableStream,\n decodeReply,\n decodeAction,\n decodeFormState,\n} from 'react-server-dom-webpack/server'\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nexport { prerender } from 'react-server-dom-webpack/static'\n\n// Node.js-specific Flight APIs, needed by stream-ops.node.ts via ComponentMod.\n// These must be exported from entry-base (react-server layer) because direct\n// imports from react-server-dom-webpack/* fail outside this layer.\ntype FlightRenderToPipeableStream = (...args: any[]) => {\n pipe<Writable extends NodeJS.WritableStream>(destination: Writable): Writable\n abort: (reason?: unknown) => void\n}\n\ntype FlightPrerenderToNodeStream = (...args: any[]) => Promise<{\n prelude: import('node:stream').Readable\n}>\n\n/* eslint-disable import/no-extraneous-dependencies */\nexport let renderToPipeableStream: FlightRenderToPipeableStream | undefined\nexport let prerenderToNodeStream: FlightPrerenderToNodeStream | undefined\nif (process.env.__NEXT_USE_NODE_STREAMS) {\n renderToPipeableStream = (\n require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')\n ).renderToPipeableStream\n prerenderToNodeStream = (\n require('react-server-dom-webpack/static') as typeof import('react-server-dom-webpack/static')\n ).prerenderToNodeStream\n} else {\n renderToPipeableStream = undefined\n prerenderToNodeStream = undefined\n}\n/* eslint-enable import/no-extraneous-dependencies */\n\n// TODO: Just re-export `* as ReactServer`\nexport { captureOwnerStack, createElement, Fragment } from 'react'\n\nexport {\n default as LayoutRouter,\n LoadingBoundaryProvider,\n} from '../../client/components/layout-router'\nexport { default as RenderFromTemplateContext } from '../../client/components/render-from-template-context'\nexport { ClientPageRoot } from '../../client/components/client-page'\nexport { ClientSegmentRoot } from '../../client/components/client-segment'\nexport {\n createServerSearchParamsForServerPage,\n createPrerenderSearchParamsForClientPage,\n} from '../request/search-params'\nexport {\n createServerParamsForServerSegment,\n createPrerenderParamsForClientSegment,\n} from '../request/params'\nexport * as serverHooks from '../../client/components/hooks-server-context'\nexport { HTTPAccessFallbackBoundary } from '../../client/components/http-access-fallback/error-boundary'\nexport { createMetadataComponents } from '../../lib/metadata/metadata'\nexport { RootLayoutBoundary } from '../../lib/framework/boundary-components'\n\nexport { preloadStyle, preloadFont, preconnect } from './rsc/preloads'\nexport { isEmptyHTMLPrelude } from './postponed-state'\nexport { Postpone } from './rsc/postpone'\nexport { taintObjectReference } from './rsc/taint'\nexport {\n collectSegmentData,\n collectPrefetchHints,\n} from './collect-segment-data'\n\nexport const InstantValidation = () => {\n if (\n process.env.NEXT_RUNTIME !== 'edge' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n return require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation')\n } else {\n return undefined\n }\n}\n\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { patchFetch as _patchFetch } from '../lib/patch-fetch'\n\nlet SegmentViewNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewNode =\n () => null\nlet SegmentViewStateNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewStateNode =\n () => null\nif (process.env.NODE_ENV === 'development') {\n const mod =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n SegmentViewNode = mod.SegmentViewNode\n SegmentViewStateNode = mod.SegmentViewStateNode\n}\n\n// For hot-reloader\ndeclare global {\n var __next__clear_chunk_cache__: (() => void) | null | undefined\n var __turbopack_clear_chunk_cache__: () => void | null | undefined\n var __turbopack_server_hmr_apply__:\n | ((update: NodeJsPartialHmrUpdate) => void)\n | undefined\n}\n\n// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`\n// into globalThis from this file which is bundled.\nif (process.env.TURBOPACK) {\n globalThis.__next__clear_chunk_cache__ = __turbopack_clear_chunk_cache__\n} else {\n // Webpack does not have chunks on the server\n globalThis.__next__clear_chunk_cache__ = null\n}\n\n// patchFetch makes use of APIs such as `React.unstable_postpone` which are only available\n// in the experimental channel of React, so export it from here so that it comes from the bundled runtime\nexport function patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\n// Development only\nexport { SegmentViewNode, SegmentViewStateNode }\n"],"names":["createTemporaryReferenceSet","renderToReadableStream","decodeReply","decodeAction","decodeFormState","prerender","renderToPipeableStream","prerenderToNodeStream","process","env","__NEXT_USE_NODE_STREAMS","require","undefined","captureOwnerStack","createElement","Fragment","default","LayoutRouter","LoadingBoundaryProvider","RenderFromTemplateContext","ClientPageRoot","ClientSegmentRoot","createServerSearchParamsForServerPage","createPrerenderSearchParamsForClientPage","createServerParamsForServerSegment","createPrerenderParamsForClientSegment","serverHooks","HTTPAccessFallbackBoundary","createMetadataComponents","RootLayoutBoundary","preloadStyle","preloadFont","preconnect","isEmptyHTMLPrelude","Postpone","taintObjectReference","collectSegmentData","collectPrefetchHints","InstantValidation","NEXT_RUNTIME","__NEXT_CACHE_COMPONENTS","workAsyncStorage","workUnitAsyncStorage","patchFetch","_patchFetch","SegmentViewNode","SegmentViewStateNode","NODE_ENV","mod","TURBOPACK","globalThis","__next__clear_chunk_cache__","__turbopack_clear_chunk_cache__"],"mappings":"AAAA,6DAA6D;AAC7D,SACEA,2BAA2B,EAC3BC,sBAAsB,EACtBC,WAAW,EACXC,YAAY,EACZC,eAAe,QACV,kCAAiC;AAExC,6DAA6D;AAC7D,SAASC,SAAS,QAAQ,kCAAiC;AAc3D,oDAAoD,GACpD,OAAO,IAAIC,uBAAgE;AAC3E,OAAO,IAAIC,sBAA8D;AACzE,IAAIC,QAAQC,GAAG,CAACC,uBAAuB,EAAE;IACvCJ,yBAAyB,AACvBK,QAAQ,wCACRL,sBAAsB;IACxBC,wBAAwB,AACtBI,QAAQ,mCACRJ,qBAAqB;AACzB,OAAO;IACLD,yBAAyBM;IACzBL,wBAAwBK;AAC1B;AACA,mDAAmD,GAEnD,0CAA0C;AAC1C,SAASC,iBAAiB,EAAEC,aAAa,EAAEC,QAAQ,QAAQ,QAAO;AAElE,SACEC,WAAWC,YAAY,EACvBC,uBAAuB,QAClB,wCAAuC;AAC9C,SAASF,WAAWG,yBAAyB,QAAQ,uDAAsD;AAC3G,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SAASC,iBAAiB,QAA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;AACF;AAEA,mBAAmB;AACnB,SAASG,eAAe,EAAEC,oBAAoB,GAAE","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/app-render/entry-base.ts"],"sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nexport {\n createTemporaryReferenceSet,\n renderToReadableStream,\n decodeReply,\n decodeAction,\n decodeFormState,\n} from 'react-server-dom-webpack/server'\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nexport { prerender } from 'react-server-dom-webpack/static'\n\n// Node.js-specific Flight APIs, needed by stream-ops.node.ts via ComponentMod.\n// These must be exported from entry-base (react-server layer) because direct\n// imports from react-server-dom-webpack/* fail outside this layer.\ntype FlightRenderToPipeableStream = (...args: any[]) => {\n pipe<Writable extends NodeJS.WritableStream>(destination: Writable): Writable\n abort: (reason?: unknown) => void\n}\n\ntype FlightPrerenderToNodeStream = (...args: any[]) => Promise<{\n prelude: import('node:stream').Readable\n}>\n\n/* eslint-disable import/no-extraneous-dependencies */\nexport let renderToPipeableStream: FlightRenderToPipeableStream | undefined\nexport let prerenderToNodeStream: FlightPrerenderToNodeStream | undefined\nif (process.env.__NEXT_USE_NODE_STREAMS) {\n renderToPipeableStream = (\n require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')\n ).renderToPipeableStream\n prerenderToNodeStream = (\n require('react-server-dom-webpack/static') as typeof import('react-server-dom-webpack/static')\n ).prerenderToNodeStream\n} else {\n renderToPipeableStream = undefined\n prerenderToNodeStream = undefined\n}\n/* eslint-enable import/no-extraneous-dependencies */\n\n// TODO: Just re-export `* as ReactServer`\nexport { captureOwnerStack, createElement, Fragment } from 'react'\n\nexport {\n default as LayoutRouter,\n LoadingBoundaryProvider,\n} from '../../client/components/layout-router'\nexport { default as RenderFromTemplateContext } from '../../client/components/render-from-template-context'\nexport { ClientPageRoot } from '../../client/components/client-page'\nexport { ClientSegmentRoot } from '../../client/components/client-segment'\nexport {\n createServerSearchParamsForServerPage,\n createPrerenderSearchParamsForClientPage,\n} from '../request/search-params'\nexport {\n createServerParamsForServerSegment,\n createPrerenderParamsForClientSegment,\n} from '../request/params'\nexport * as serverHooks from '../../client/components/hooks-server-context'\nexport { HTTPAccessFallbackBoundary } from '../../client/components/http-access-fallback/error-boundary'\nexport { createMetadataComponents } from '../../lib/metadata/metadata'\nexport { RootLayoutBoundary } from '../../lib/framework/boundary-components'\n\nexport { preloadStyle, preloadFont, preconnect } from './rsc/preloads'\nexport { isEmptyHTMLPrelude } from './postponed-state'\nexport { taintObjectReference } from './rsc/taint'\nexport {\n collectSegmentData,\n collectPrefetchHints,\n} from './collect-segment-data'\n\nexport const InstantValidation = () => {\n if (\n process.env.NEXT_RUNTIME !== 'edge' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n return require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation')\n } else {\n return undefined\n }\n}\n\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { patchFetch as _patchFetch } from '../lib/patch-fetch'\n\nlet SegmentViewNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewNode =\n () => null\nlet SegmentViewStateNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewStateNode =\n () => null\nif (process.env.NODE_ENV === 'development') {\n const mod =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n SegmentViewNode = mod.SegmentViewNode\n SegmentViewStateNode = mod.SegmentViewStateNode\n}\n\n// For hot-reloader\ndeclare global {\n var __next__clear_chunk_cache__: (() => void) | null | undefined\n var __turbopack_clear_chunk_cache__: () => void | null | undefined\n var __turbopack_server_hmr_apply__:\n | ((update: NodeJsPartialHmrUpdate) => void)\n | undefined\n}\n\n// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`\n// into globalThis from this file which is bundled.\nif (process.env.TURBOPACK) {\n globalThis.__next__clear_chunk_cache__ = __turbopack_clear_chunk_cache__\n} else {\n // Webpack does not have chunks on the server\n globalThis.__next__clear_chunk_cache__ = null\n}\n\nexport function patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\n// Development only\nexport { SegmentViewNode, SegmentViewStateNode }\n"],"names":["createTemporaryReferenceSet","renderToReadableStream","decodeReply","decodeAction","decodeFormState","prerender","renderToPipeableStream","prerenderToNodeStream","process","env","__NEXT_USE_NODE_STREAMS","require","undefined","captureOwnerStack","createElement","Fragment","default","LayoutRouter","LoadingBoundaryProvider","RenderFromTemplateContext","ClientPageRoot","ClientSegmentRoot","createServerSearchParamsForServerPage","createPrerenderSearchParamsForClientPage","createServerParamsForServerSegment","createPrerenderParamsForClientSegment","serverHooks","HTTPAccessFallbackBoundary","createMetadataComponents","RootLayoutBoundary","preloadStyle","preloadFont","preconnect","isEmptyHTMLPrelude","taintObjectReference","collectSegmentData","collectPrefetchHints","InstantValidation","NEXT_RUNTIME","__NEXT_CACHE_COMPONENTS","workAsyncStorage","workUnitAsyncStorage","patchFetch","_patchFetch","SegmentViewNode","SegmentViewStateNode","NODE_ENV","mod","TURBOPACK","globalThis","__next__clear_chunk_cache__","__turbopack_clear_chunk_cache__"],"mappings":"AAAA,6DAA6D;AAC7D,SACEA,2BAA2B,EAC3BC,sBAAsB,EACtBC,WAAW,EACXC,YAAY,EACZC,eAAe,QACV,kCAAiC;AAExC,6DAA6D;AAC7D,SAASC,SAAS,QAAQ,kCAAiC;AAc3D,oDAAoD,GACpD,OAAO,IAAIC,uBAAgE;AAC3E,OAAO,IAAIC,sBAA8D;AACzE,IAAIC,QAAQC,GAAG,CAACC,uBAAuB,EAAE;IACvCJ,yBAAyB,AACvBK,QAAQ,wCACRL,sBAAsB;IACxBC,wBAAwB,AACtBI,QAAQ,mCACRJ,qBAAqB;AACzB,OAAO;IACLD,yBAAyBM;IACzBL,wBAAwBK;AAC1B;AACA,mDAAm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QC,GAAG,CAACuC,SAAS,EAAE;IACzBC,WAAWC,2BAA2B,GAAGC;AAC3C,OAAO;IACL,6CAA6C;IAC7CF,WAAWC,2BAA2B,GAAG;AAC3C;AAEA,OAAO,SAASR;IACd,OAAOC,YAAY;QACjBH;QACAC;IACF;AACF;AAEA,mBAAmB;AACnB,SAASG,eAAe,EAAEC,oBAAoB,GAAE","ignoreList":[0]}

@@ -24,3 +24,2 @@ /* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */ // Do not put a "use client" directive here. Import this module via the shim in

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -27,0 +26,0 @@ case 'prerender-runtime':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/server/app-render/instant-validation/boundary-impl.tsx"],"sourcesContent":["/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */\n\n// Do not put a \"use client\" directive here. Import this module via the shim in\n// `packages/next/src/client/components/instant-validation/boundary.tsx` instead.\n// 'use client'\n\nimport { createContext, type ReactNode } from 'react'\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type { ValidationBoundaryTracking } from './boundary-tracking'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\n\nif (typeof window !== 'undefined') {\n throw new InvariantError(\n 'Instant validation boundaries should never appear in browser bundles.'\n )\n}\n\nfunction getValidationBoundaryTracking(): ValidationBoundaryTracking | null {\n const store = workUnitAsyncStorage.getStore()\n if (!store) return null\n switch (store.type) {\n case 'validation-client':\n return store.boundaryState\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n store satisfies never\n }\n return null\n}\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [INSTANT_VALIDATION_BOUNDARY_NAME]: function ({\n id,\n children,\n }: {\n id: string\n children: ReactNode\n }) {\n // Track which boundaries we actually managed to render.\n const state = getValidationBoundaryTracking()\n if (state === null) {\n throw new InvariantError('Missing boundary tracking state')\n }\n state.renderedIds.add(id)\n\n return children\n },\n}\n\ntype BoundaryPlacement =\n | null // do not place here\n | string // boundaryId -- place here\n\nexport const InstantValidationBoundaryContext =\n createContext<BoundaryPlacement>(null)\n\nexport function PlaceValidationBoundaryBelowThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n return (\n // OuterLayoutRouter will see this and render a `RenderValidationBoundaryAtThisLevel`.\n <InstantValidationBoundaryContext value={id}>\n {children}\n </InstantValidationBoundaryContext>\n )\n}\n\nexport function RenderValidationBoundaryAtThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n // We got a boundaryId from the context. Clear the context so that the children don't render another boundary.\n return (\n <InstantValidationBoundary id={id}>\n <InstantValidationBoundaryContext value={null}>\n {children}\n </InstantValidationBoundaryContext>\n </InstantValidationBoundary>\n )\n}\n\nconst InstantValidationBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n INSTANT_VALIDATION_BOUNDARY_NAME.slice(\n 0\n ) as typeof INSTANT_VALIDATION_BOUNDARY_NAME\n ]\n\n// Slot marker component for attributing validation errors to the\n// correct config when a boundary spans multiple parallel slots.\n// Renders a dynamically-named inner component so the slot index\n// appears in the SSR component stack (__next_instant_slot_N__).\nconst slotMarkerCache = new Map<\n string,\n (props: { children: ReactNode }) => ReactNode\n>()\n\nexport function SlotMarker({\n name,\n children,\n}: {\n name: string\n children: ReactNode\n}) {\n let Marker = slotMarkerCache.get(name)\n if (!Marker) {\n const ns = {\n [name]: function ({ children: c }: { children: ReactNode }) {\n return c\n },\n }\n Marker = ns[name]\n slotMarkerCache.set(name, Marker)\n }\n return <Marker>{children}</Marker>\n}\n"],"names":["createContext","INSTANT_VALIDATION_BOUNDARY_NAME","InvariantError","workUnitAsyncStorage","window","getValidationBoundaryTracking","store","getStore","type","boundaryState","NameSpace","id","children","state","renderedIds","add","InstantValidationBoundaryContext","PlaceValidationBoundaryBelowThisLevel","value","RenderValidationBoundaryAtThisLevel","InstantValidationBoundary","slice","slotMarkerCache","Map","SlotMarker","name","Marker","get","ns","c","set"],"mappings":"AAAA,kEAAkE,GAElE,+EAA+E;AAC/E,iFAAiF;AACjF,eAAe;;AAEf,SAASA,aAAa,QAAwB,QAAO;AACrD,SAASC,gCAAgC,QAAQ,uBAAsB;AACvE,SAASC,cAAc,QAAQ,sCAAqC;AAEpE,SAASC,oBAAoB,QAAQ,sCAAqC;AAE1E,IAAI,OAAOC,WAAW,aAAa;IACjC,MAAM,qBAEL,CAFK,IAAIF,eACR,0EADI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,SAASG;IACP,MAAMC,QAAQH,qBAAqBI,QAAQ;IAC3C,IAAI,CAACD,OAAO,OAAO;IACnB,OAAQA,MAAME,IAAI;QAChB,KAAK;YACH,OAAOF,MAAMG,aAAa;QAC5B,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEH;IACJ;IACA,OAAO;AACT;AAEA,4EAA4E;AAC5E,iEAAiE;AACjE,MAAMI,YAAY;IAChB,CAACT,iCAAiC,EAAE,SAAU,EAC5CU,EAAE,EACFC,QAAQ,EAIT;QACC,wDAAwD;QACxD,MAAMC,QAAQR;QACd,IAAIQ,UAAU,MAAM;YAClB,MAAM,qBAAqD,CAArD,IAAIX,eAAe,oCAAnB,qBAAA;uBAAA;4BAAA;8BAAA;YAAoD;QAC5D;QACAW,MAAMC,WAAW,CAACC,GAAG,CAACJ;QAEtB,OAAOC;IACT;AACF;AAMA,OAAO,MAAMI,iDACXhB,cAAiC,MAAK;AAExC,OAAO,SAASiB,sCAAsC,EACpDN,EAAE,EACFC,QAAQ,EAIT;IACC,OACE,sFAAsF;kBACtF,KAACI;QAAiCE,OAAOP;kBACtCC;;AAGP;AAEA,OAAO,SAASO,oCAAoC,EAClDR,EAAE,EACFC,QAAQ,EAIT;IACC,8GAA8G;IAC9G,qBACE,KAACQ;QAA0BT,IAAIA;kBAC7B,cAAA,KAACK;YAAiCE,OAAO;sBACtCN;;;AAIT;AAEA,MAAMQ,4BACJ,gFAAgF;AAChF,4DAA4D;AAC5DV,SAAS,CACPT,iCAAiCoB,KAAK,CACpC,GAEH;AAEH,iEAAiE;AACjE,gEAAgE;AAChE,gEAAgE;AAChE,gEAAgE;AAChE,MAAMC,kBAAkB,IAAIC;AAK5B,OAAO,SAASC,WAAW,EACzBC,IAAI,EACJb,QAAQ,EAIT;IACC,IAAIc,SAASJ,gBAAgBK,GAAG,CAACF;IACjC,IAAI,CAACC,QAAQ;QACX,MAAME,KAAK;YACT,CAACH,KAAK,EAAE,SAAU,EAAEb,UAAUiB,CAAC,EAA2B;gBACxD,OAAOA;YACT;QACF;QACAH,SAASE,EAAE,CAACH,KAAK;QACjBH,gBAAgBQ,GAAG,CAACL,MAAMC;IAC5B;IACA,qBAAO,KAACA;kBAAQd;;AAClB","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/server/app-render/instant-validation/boundary-impl.tsx"],"sourcesContent":["/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */\n\n// Do not put a \"use client\" directive here. Import this module via the shim in\n// `packages/next/src/client/components/instant-validation/boundary.tsx` instead.\n// 'use client'\n\nimport { createContext, type ReactNode } from 'react'\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type { ValidationBoundaryTracking } from './boundary-tracking'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\n\nif (typeof window !== 'undefined') {\n throw new InvariantError(\n 'Instant validation boundaries should never appear in browser bundles.'\n )\n}\n\nfunction getValidationBoundaryTracking(): ValidationBoundaryTracking | null {\n const store = workUnitAsyncStorage.getStore()\n if (!store) return null\n switch (store.type) {\n case 'validation-client':\n return store.boundaryState\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n store satisfies never\n }\n return null\n}\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [INSTANT_VALIDATION_BOUNDARY_NAME]: function ({\n id,\n children,\n }: {\n id: string\n children: ReactNode\n }) {\n // Track which boundaries we actually managed to render.\n const state = getValidationBoundaryTracking()\n if (state === null) {\n throw new InvariantError('Missing boundary tracking state')\n }\n state.renderedIds.add(id)\n\n return children\n },\n}\n\ntype BoundaryPlacement =\n | null // do not place here\n | string // boundaryId -- place here\n\nexport const InstantValidationBoundaryContext =\n createContext<BoundaryPlacement>(null)\n\nexport function PlaceValidationBoundaryBelowThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n return (\n // OuterLayoutRouter will see this and render a `RenderValidationBoundaryAtThisLevel`.\n <InstantValidationBoundaryContext value={id}>\n {children}\n </InstantValidationBoundaryContext>\n )\n}\n\nexport function RenderValidationBoundaryAtThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n // We got a boundaryId from the context. Clear the context so that the children don't render another boundary.\n return (\n <InstantValidationBoundary id={id}>\n <InstantValidationBoundaryContext value={null}>\n {children}\n </InstantValidationBoundaryContext>\n </InstantValidationBoundary>\n )\n}\n\nconst InstantValidationBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n INSTANT_VALIDATION_BOUNDARY_NAME.slice(\n 0\n ) as typeof INSTANT_VALIDATION_BOUNDARY_NAME\n ]\n\n// Slot marker component for attributing validation errors to the\n// correct config when a boundary spans multiple parallel slots.\n// Renders a dynamically-named inner component so the slot index\n// appears in the SSR component stack (__next_instant_slot_N__).\nconst slotMarkerCache = new Map<\n string,\n (props: { children: ReactNode }) => ReactNode\n>()\n\nexport function SlotMarker({\n name,\n children,\n}: {\n name: string\n children: ReactNode\n}) {\n let Marker = slotMarkerCache.get(name)\n if (!Marker) {\n const ns = {\n [name]: function ({ children: c }: { children: ReactNode }) {\n return c\n },\n }\n Marker = ns[name]\n slotMarkerCache.set(name, Marker)\n }\n return <Marker>{children}</Marker>\n}\n"],"names":["createContext","INSTANT_VALIDATION_BOUNDARY_NAME","InvariantError","workUnitAsyncStorage","window","getValidationBoundaryTracking","store","getStore","type","boundaryState","NameSpace","id","children","state","renderedIds","add","InstantValidationBoundaryContext","PlaceValidationBoundaryBelowThisLevel","value","RenderValidationBoundaryAtThisLevel","InstantValidationBoundary","slice","slotMarkerCache","Map","SlotMarker","name","Marker","get","ns","c","set"],"mappings":"AAAA,kEAAkE,GAElE,+EAA+E;AAC/E,iFAAiF;AACjF,eAAe;;AAEf,SAASA,aAAa,QAAwB,QAAO;AACrD,SAASC,gCAAgC,QAAQ,uBAAsB;AACvE,SAASC,cAAc,QAAQ,sCAAqC;AAEpE,SAASC,oBAAoB,QAAQ,sCAAqC;AAE1E,IAAI,OAAOC,WAAW,aAAa;IACjC,MAAM,qBAEL,CAFK,IAAIF,eACR,0EADI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,SAASG;IACP,MAAMC,QAAQH,qBAAqBI,QAAQ;IAC3C,IAAI,CAACD,OAAO,OAAO;IACnB,OAAQA,MAAME,IAAI;QAChB,KAAK;YACH,OAAOF,MAAMG,aAAa;QAC5B,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEH;IACJ;IACA,OAAO;AACT;AAEA,4EAA4E;AAC5E,iEAAiE;AACjE,MAAMI,YAAY;IAChB,CAACT,iCAAiC,EAAE,SAAU,EAC5CU,EAAE,EACFC,QAAQ,EAIT;QACC,wDAAwD;QACxD,MAAMC,QAAQR;QACd,IAAIQ,UAAU,MAAM;YAClB,MAAM,qBAAqD,CAArD,IAAIX,eAAe,oCAAnB,qBAAA;uBAAA;4BAAA;8BAAA;YAAoD;QAC5D;QACAW,MAAMC,WAAW,CAACC,GAAG,CAACJ;QAEtB,OAAOC;IACT;AACF;AAMA,OAAO,MAAMI,iDACXhB,cAAiC,MAAK;AAExC,OAAO,SAASiB,sCAAsC,EACpDN,EAAE,EACFC,QAAQ,EAIT;IACC,OACE,sFAAsF;kBACtF,KAACI;QAAiCE,OAAOP;kBACtCC;;AAGP;AAEA,OAAO,SAASO,oCAAoC,EAClDR,EAAE,EACFC,QAAQ,EAIT;IACC,8GAA8G;IAC9G,qBACE,KAACQ;QAA0BT,IAAIA;kBAC7B,cAAA,KAACK;YAAiCE,OAAO;sBACtCN;;;AAIT;AAEA,MAAMQ,4BACJ,gFAAgF;AAChF,4DAA4D;AAC5DV,SAAS,CACPT,iCAAiCoB,KAAK,CACpC,GAEH;AAEH,iEAAiE;AACjE,gEAAgE;AAChE,gEAAgE;AAChE,gEAAgE;AAChE,MAAMC,kBAAkB,IAAIC;AAK5B,OAAO,SAASC,WAAW,EACzBC,IAAI,EACJb,QAAQ,EAIT;IACC,IAAIc,SAASJ,gBAAgBK,GAAG,CAACF;IACjC,IAAI,CAACC,QAAQ;QACX,MAAME,KAAK;YACT,CAACH,KAAK,EAAE,SAAU,EAAEb,UAAUiB,CAAC,EAA2B;gBACxD,OAAOA;YACT;QACF;QACAH,SAASE,EAAE,CAACH,KAAK;QACjBH,gBAAgBQ,GAAG,CAACL,MAAMC;IAC5B;IACA,qBAAO,KAACA;kBAAQd;;AAClB","ignoreList":[0]}

@@ -29,3 +29,2 @@ import { RequestCookies } from '../../web/spec-extension/cookies';

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':

@@ -32,0 +31,0 @@ case 'prerender':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/server/app-render/instant-validation/instant-samples.ts"],"sourcesContent":["import type { InstantSample } from '../../../build/segment-config/app/app-segment-config'\nimport type { ReadonlyRequestCookies } from '../../web/spec-extension/adapters/request-cookies'\nimport type { ReadonlyHeaders } from '../../web/spec-extension/adapters/headers'\nimport type { DraftModeProvider } from '../../async-storage/draft-mode-provider'\nimport type { Params } from '../../request/params'\n\nimport { RequestCookies } from '../../web/spec-extension/cookies'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport type { SearchParams } from '../../request/search-params'\nimport { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param'\nimport { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { InstantValidationError } from './instant-validation-error'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\nimport { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils'\nimport type { WorkStore } from '../work-async-storage.external'\n\nexport type InstantValidationSampleTracking = {\n // TODO(instant-validation-build): track which samples config we used and attribute errors\n missingSampleErrors: InstantValidationError[]\n}\n\nexport function createValidationSampleTracking(): InstantValidationSampleTracking {\n return {\n missingSampleErrors: [],\n }\n}\n\nfunction getExpectedSampleTracking(): InstantValidationSampleTracking {\n let validationSampleTracking: InstantValidationSampleTracking | null = null\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'request':\n case 'validation-client':\n // TODO(instant-validation-build): do we need any special handling for caches?\n validationSampleTracking =\n workUnitStore.validationSampleTracking ?? null\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender-client':\n case 'prerender':\n case 'prerender-runtime':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n if (!validationSampleTracking) {\n throw new InvariantError(\n 'Expected to have a workUnitStore that provides validationSampleTracking'\n )\n }\n return validationSampleTracking\n}\n\nexport function trackMissingSampleError(error: InstantValidationError): void {\n const validationSampleTracking = getExpectedSampleTracking()\n validationSampleTracking.missingSampleErrors.push(error)\n}\n\nexport function trackMissingSampleErrorAndThrow(\n error: InstantValidationError\n): never {\n // TODO(instant-validation-build): this should abort the render\n trackMissingSampleError(error)\n throw error\n}\n\n/**\n * Creates ReadonlyRequestCookies from sample cookie data.\n * Accessing a cookie not declared in the sample will throw an error.\n * Cookies with `value: null` are declared (allowed to access) but return no value.\n */\nexport function createCookiesFromSample(\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyRequestCookies {\n const declaredNames = new Set<string>()\n\n const cookies = new RequestCookies(new Headers())\n if (sampleCookies) {\n for (const cookie of sampleCookies) {\n declaredNames.add(cookie.name)\n if (cookie.value !== null) {\n cookies.set(cookie.name, cookie.value)\n }\n }\n }\n\n const sealed = RequestCookiesAdapter.seal(cookies)\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (name) {\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n if (prop === 'get') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (nameOrCookie) {\n let name: string\n if (typeof nameOrCookie === 'string') {\n name = nameOrCookie\n } else if (\n nameOrCookie &&\n typeof nameOrCookie === 'object' &&\n typeof nameOrCookie.name === 'string'\n ) {\n name = nameOrCookie.name\n } else {\n // This is an invalid input. Pass it through to the original method so it can error.\n return originalMethod.call(target, nameOrCookie)\n }\n\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n\n // TODO(instant-validation-build): what should getAll do?\n // Maybe we should only allow it if there's an array (possibly empty?)\n\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\nfunction createMissingCookieSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`cookies\\` array, ` +\n `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`\n )\n}\n\n/**\n * Creates ReadonlyHeaders from sample header data.\n * Accessing a header not declared in the sample will throw an error.\n * Headers with `value: null` are declared (allowed to access) but return null.\n */\nexport function createHeadersFromSample(\n rawSampleHeaders: InstantSample['headers'],\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyHeaders {\n // If we have cookie samples, add a `cookie` header to match.\n // Accessing it will be implicitly allowed by the proxy --\n // if the user defined some cookies, accessing the \"cookie\" header is also fine.\n const sampleHeaders = rawSampleHeaders ? [...rawSampleHeaders] : []\n if (sampleHeaders.find(([name]) => name.toLowerCase() === 'cookie')) {\n throw new InstantValidationError(\n 'Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'\n )\n }\n if (sampleCookies) {\n const cookieHeaderValue = sampleCookies.toString()\n sampleHeaders.push([\n 'cookie',\n // if the `cookies` samples were empty, or they were all `null`, then we have no cookies,\n // and the header isn't present, but should remains readable, so we set it to null.\n cookieHeaderValue !== '' ? cookieHeaderValue : null,\n ])\n }\n\n const declaredNames = new Set<string>()\n const headersInit: Record<string, string> = {}\n\n for (const [name, value] of sampleHeaders) {\n declaredNames.add(name.toLowerCase())\n if (value !== null) {\n headersInit[name.toLowerCase()] = value\n }\n }\n\n const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit))\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'get' || prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const patchedMethod: typeof originalMethod = function (rawName) {\n const name = rawName.toLowerCase()\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`headers\\` array, ` +\n `or \\`[\"${name}\", null]\\` if it should be absent.`\n )\n )\n }\n // typescript can't reconcile a union of functions with a union of return types,\n // so we have to cast the original return type away\n return (originalMethod as (...args: any[]) => any).call(target, name)\n }\n return patchedMethod\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\n/**\n * Creates a DraftModeProvider that always returns isEnabled: false.\n */\nexport function createDraftModeForValidation(): DraftModeProvider {\n // Create a minimal DraftModeProvider-compatible object\n // that always reports draft mode as disabled.\n //\n // private properties that can't be set from outside the class.\n return {\n get isEnabled() {\n return false\n },\n enable() {\n throw new Error(\n 'Draft mode cannot be enabled during build-time instant validation.'\n )\n },\n disable() {\n throw new Error(\n 'Draft mode cannot be disabled during build-time instant validation.'\n )\n },\n } as Partial<DraftModeProvider> as DraftModeProvider\n}\n\n/**\n * Creates params wrapped with an exhaustive proxy.\n * Accessing a param not declared in the sample will throw an error.\n */\nexport function createExhaustiveParamsProxy<TParams extends Params>(\n underlyingParams: TParams,\n declaredParamNames: Set<string>,\n route: string\n): TParams {\n return new Proxy(underlyingParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n // Only error when accessing a param that is part of the route but wasn't provided.\n // accessing properties that aren't expected to be a valid param value is fine.\n prop in underlyingParams &&\n !declaredParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n // We don't need to override `has` or `ownKeys`.\n // the shape of the params object is determined by the routing structure\n // and independent of the samples. We only need to instrument accessing the values.\n })\n}\n\n/**\n * Creates searchParams wrapped with an exhaustive proxy.\n * Accessing a searchParam not declared in the sample will throw an error.\n * A searchParam with `value: undefined` means \"declared but absent\" (allowed to access, returns undefined).\n */\nexport function createExhaustiveSearchParamsProxy(\n searchParams: SearchParams,\n declaredSearchParamNames: Set<string>,\n route: string\n): SearchParams {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n has(target, prop) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.has(target, prop)\n },\n })\n}\n\n/**\n * Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an\n * exhaustive proxy. Accessing a search param not declared in the sample via\n * get/getAll/has will throw an error.\n */\nexport function createExhaustiveURLSearchParamsProxy<T extends URLSearchParams>(\n searchParams: T,\n declaredSearchParamNames: Set<string>,\n route: string\n): T {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n // Intercept method calls that access specific param names\n if (prop === 'get' || prop === 'getAll' || prop === 'has') {\n const originalMathod = Reflect.get(target, prop, receiver)\n return (name: string) => {\n if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, name)\n )\n }\n return (originalMathod as (...args: any[]) => any).call(target, name)\n }\n }\n const value = Reflect.get(target, prop, receiver)\n // Prevent `TypeError: Value of \"this\" must be of type URLSearchParams` for methods\n if (typeof value === 'function' && !Object.hasOwn(target, prop)) {\n return value.bind(target)\n }\n return value\n },\n })\n}\n\nfunction createMissingSearchParamSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`searchParams\\` object, ` +\n `or \\`{ \"${name}\": null }\\` if it should be absent.`\n )\n}\n\nexport function createRelativeURLFromSamples(\n route: string,\n sampleParams: InstantSample['params'],\n sampleSearchParams: InstantSample['searchParams']\n) {\n // Build searchParams query object and URL search string from sample\n const pathname = createPathnameFromRouteAndSampleParams(\n route,\n sampleParams ?? {}\n )\n\n let search = ''\n if (sampleSearchParams) {\n const qs = createURLSearchParamsFromSample(sampleSearchParams).toString()\n if (qs) {\n search = '?' + qs\n }\n }\n\n return parseRelativeUrl(pathname + search, undefined, true)\n}\n\nfunction createURLSearchParamsFromSample(\n sampleSearchParams: InstantSample['searchParams']\n) {\n const result = new URLSearchParams()\n if (sampleSearchParams) {\n for (const [key, value] of Object.entries(sampleSearchParams)) {\n if (value === null || value === undefined) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n result.append(key, v)\n }\n } else {\n result.set(key, value)\n }\n }\n }\n return result\n}\n\n/**\n * Substitute sample params into `workStore.route` to create a plausible pathname.\n * TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,\n * but it should be good enough for some initial testing.\n */\nfunction createPathnameFromRouteAndSampleParams(route: string, params: Params) {\n let interpolatedSegments: string[] = []\n const rawSegments = route.split('/')\n for (const rawSegment of rawSegments) {\n const param = getSegmentParam(rawSegment)\n if (param) {\n switch (param.paramType) {\n case 'catchall':\n case 'optional-catchall': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = [rawSegment]\n } else if (!Array.isArray(paramValue)) {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(\n ...paramValue.map((v) => encodeURIComponent(v))\n )\n break\n }\n case 'dynamic': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = rawSegment\n } else if (typeof paramValue !== 'string') {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(encodeURIComponent(paramValue))\n break\n }\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)': {\n // TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here\n throw new InvariantError(\n 'Not implemented: Validation of interception routes'\n )\n }\n default: {\n param.paramType satisfies never\n }\n }\n } else {\n interpolatedSegments.push(rawSegment)\n }\n }\n return interpolatedSegments.join('/')\n}\n\nexport function assertRootParamInSamples(\n workStore: WorkStore,\n sampleParams: Params | undefined,\n paramName: string\n) {\n if (sampleParams && paramName in sampleParams) {\n // The param is defined in the samples.\n } else {\n const route = workStore.route\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n}\n"],"names":["RequestCookies","RequestCookiesAdapter","HeadersAdapter","getSegmentParam","parseRelativeUrl","InvariantError","InstantValidationError","workUnitAsyncStorage","wellKnownProperties","createValidationSampleTracking","missingSampleErrors","getExpectedSampleTracking","validationSampleTracking","workUnitStore","getStore","type","trackMissingSampleError","error","push","trackMissingSampleErrorAndThrow","createCookiesFromSample","sampleCookies","route","declaredNames","Set","cookies","Headers","cookie","add","name","value","set","sealed","seal","Proxy","get","target","prop","receiver","originalMethod","Reflect","wrappedMethod","has","createMissingCookieSampleError","call","nameOrCookie","createHeadersFromSample","rawSampleHeaders","sampleHeaders","find","toLowerCase","cookieHeaderValue","toString","headersInit","from","patchedMethod","rawName","createDraftModeForValidation","isEnabled","enable","Error","disable","createExhaustiveParamsProxy","underlyingParams","declaredParamNames","createExhaustiveSearchParamsProxy","searchParams","declaredSearchParamNames","createMissingSearchParamSampleError","createExhaustiveURLSearchParamsProxy","originalMathod","Object","hasOwn","bind","createRelativeURLFromSamples","sampleParams","sampleSearchParams","pathname","createPathnameFromRouteAndSampleParams","search","qs","createURLSearchParamsFromSample","undefined","result","URLSearchParams","key","entries","Array","isArray","v","append","params","interpolatedSegments","rawSegments","split","rawSegment","param","paramType","paramValue","paramName","map","encodeURIComponent","join","assertRootParamInSamples","workStore"],"mappings":"AAMA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,cAAc,QAAQ,4CAA2C;AAE1E,SAASC,eAAe,QAAQ,qDAAoD;AACpF,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SAASC,sBAAsB,QAAQ,6BAA4B;AACnE,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,mBAAmB,QAAQ,0CAAyC;AAQ7E,OAAO,SAASC;IACd,OAAO;QACLC,qBAAqB,EAAE;IACzB;AACF;AAEA,SAASC;IACP,IAAIC,2BAAmE;IACvE,MAAMC,gBAAgBN,qBAAqBO,QAAQ;IACnD,IAAID,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;gBACH,8EAA8E;gBAC9EH,2BACEC,cAAcD,wBAAwB,IAAI;gBAC5C;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,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ACF;gBACA,KAAK;oBAAW;wBACd,IAAIS,aAAaP,MAAM,CAACK,MAAMG,SAAS,CAAC;wBACxC,IAAID,eAAehB,WAAW;4BAC5B,qFAAqF;4BACrF,0FAA0F;4BAC1F,6CAA6C;4BAC7CgB,aAAaH;wBACf,OAAO,IAAI,OAAOG,eAAe,UAAU;4BACzC,2FAA2F;4BAC3F,MAAM,qBAEL,CAFK,IAAI5F,uBACR,CAAC,yCAAyC,EAAEyF,WAAW,sBAAsB,EAAE,OAAOG,YAAY,GAD9F,qBAAA;uCAAA;4CAAA;8CAAA;4BAEN;wBACF;wBACAN,qBAAqB1E,IAAI,CAACmF,mBAAmBH;wBAC7C;oBACF;gBACA,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBAA6B;wBAChC,+GAA+G;wBAC/G,MAAM,qBAEL,CAFK,IAAI7F,eACR,uDADI,qBAAA;mCAAA;wCAAA;0CAAA;wBAEN;oBACF;gBACA;oBAAS;wBACP2F,MAAMC,SAAS;oBACjB;YACF;QACF,OAAO;YACLL,qBAAqB1E,IAAI,CAAC6E;QAC5B;IACF;IACA,OAAOH,qBAAqBU,IAAI,CAAC;AACnC;AAEA,OAAO,SAASC,yBACdC,SAAoB,EACpB7B,YAAgC,EAChCwB,SAAiB;IAEjB,IAAIxB,gBAAgBwB,aAAaxB,cAAc;IAC7C,uCAAuC;IACzC,OAAO;QACL,MAAMrD,QAAQkF,UAAUlF,KAAK;QAC7BH,gCACE,qBAGC,CAHD,IAAIb,uBACF,CAAC,OAAO,EAAEgB,MAAM,uBAAuB,EAAE6E,UAAU,mDAAmD,CAAC,GACrG,CAAC,yDAAyD,CAAC,GAF/D,qBAAA;mBAAA;wBAAA;0BAAA;QAGA;IAEJ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/server/app-render/instant-validation/instant-samples.ts"],"sourcesContent":["import type { InstantSample } from '../../../build/segment-config/app/app-segment-config'\nimport type { ReadonlyRequestCookies } from '../../web/spec-extension/adapters/request-cookies'\nimport type { ReadonlyHeaders } from '../../web/spec-extension/adapters/headers'\nimport type { DraftModeProvider } from '../../async-storage/draft-mode-provider'\nimport type { Params } from '../../request/params'\n\nimport { RequestCookies } from '../../web/spec-extension/cookies'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport type { SearchParams } from '../../request/search-params'\nimport { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param'\nimport { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { InstantValidationError } from './instant-validation-error'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\nimport { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils'\nimport type { WorkStore } from '../work-async-storage.external'\n\nexport type InstantValidationSampleTracking = {\n // TODO(instant-validation-build): track which samples config we used and attribute errors\n missingSampleErrors: InstantValidationError[]\n}\n\nexport function createValidationSampleTracking(): InstantValidationSampleTracking {\n return {\n missingSampleErrors: [],\n }\n}\n\nfunction getExpectedSampleTracking(): InstantValidationSampleTracking {\n let validationSampleTracking: InstantValidationSampleTracking | null = null\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'request':\n case 'validation-client':\n // TODO(instant-validation-build): do we need any special handling for caches?\n validationSampleTracking =\n workUnitStore.validationSampleTracking ?? null\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'prerender-client':\n case 'prerender':\n case 'prerender-runtime':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n if (!validationSampleTracking) {\n throw new InvariantError(\n 'Expected to have a workUnitStore that provides validationSampleTracking'\n )\n }\n return validationSampleTracking\n}\n\nexport function trackMissingSampleError(error: InstantValidationError): void {\n const validationSampleTracking = getExpectedSampleTracking()\n validationSampleTracking.missingSampleErrors.push(error)\n}\n\nexport function trackMissingSampleErrorAndThrow(\n error: InstantValidationError\n): never {\n // TODO(instant-validation-build): this should abort the render\n trackMissingSampleError(error)\n throw error\n}\n\n/**\n * Creates ReadonlyRequestCookies from sample cookie data.\n * Accessing a cookie not declared in the sample will throw an error.\n * Cookies with `value: null` are declared (allowed to access) but return no value.\n */\nexport function createCookiesFromSample(\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyRequestCookies {\n const declaredNames = new Set<string>()\n\n const cookies = new RequestCookies(new Headers())\n if (sampleCookies) {\n for (const cookie of sampleCookies) {\n declaredNames.add(cookie.name)\n if (cookie.value !== null) {\n cookies.set(cookie.name, cookie.value)\n }\n }\n }\n\n const sealed = RequestCookiesAdapter.seal(cookies)\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (name) {\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n if (prop === 'get') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (nameOrCookie) {\n let name: string\n if (typeof nameOrCookie === 'string') {\n name = nameOrCookie\n } else if (\n nameOrCookie &&\n typeof nameOrCookie === 'object' &&\n typeof nameOrCookie.name === 'string'\n ) {\n name = nameOrCookie.name\n } else {\n // This is an invalid input. Pass it through to the original method so it can error.\n return originalMethod.call(target, nameOrCookie)\n }\n\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n\n // TODO(instant-validation-build): what should getAll do?\n // Maybe we should only allow it if there's an array (possibly empty?)\n\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\nfunction createMissingCookieSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`cookies\\` array, ` +\n `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`\n )\n}\n\n/**\n * Creates ReadonlyHeaders from sample header data.\n * Accessing a header not declared in the sample will throw an error.\n * Headers with `value: null` are declared (allowed to access) but return null.\n */\nexport function createHeadersFromSample(\n rawSampleHeaders: InstantSample['headers'],\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyHeaders {\n // If we have cookie samples, add a `cookie` header to match.\n // Accessing it will be implicitly allowed by the proxy --\n // if the user defined some cookies, accessing the \"cookie\" header is also fine.\n const sampleHeaders = rawSampleHeaders ? [...rawSampleHeaders] : []\n if (sampleHeaders.find(([name]) => name.toLowerCase() === 'cookie')) {\n throw new InstantValidationError(\n 'Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'\n )\n }\n if (sampleCookies) {\n const cookieHeaderValue = sampleCookies.toString()\n sampleHeaders.push([\n 'cookie',\n // if the `cookies` samples were empty, or they were all `null`, then we have no cookies,\n // and the header isn't present, but should remains readable, so we set it to null.\n cookieHeaderValue !== '' ? cookieHeaderValue : null,\n ])\n }\n\n const declaredNames = new Set<string>()\n const headersInit: Record<string, string> = {}\n\n for (const [name, value] of sampleHeaders) {\n declaredNames.add(name.toLowerCase())\n if (value !== null) {\n headersInit[name.toLowerCase()] = value\n }\n }\n\n const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit))\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'get' || prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const patchedMethod: typeof originalMethod = function (rawName) {\n const name = rawName.toLowerCase()\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`headers\\` array, ` +\n `or \\`[\"${name}\", null]\\` if it should be absent.`\n )\n )\n }\n // typescript can't reconcile a union of functions with a union of return types,\n // so we have to cast the original return type away\n return (originalMethod as (...args: any[]) => any).call(target, name)\n }\n return patchedMethod\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\n/**\n * Creates a DraftModeProvider that always returns isEnabled: false.\n */\nexport function createDraftModeForValidation(): DraftModeProvider {\n // Create a minimal DraftModeProvider-compatible object\n // that always reports draft mode as disabled.\n //\n // private properties that can't be set from outside the class.\n return {\n get isEnabled() {\n return false\n },\n enable() {\n throw new Error(\n 'Draft mode cannot be enabled during build-time instant validation.'\n )\n },\n disable() {\n throw new Error(\n 'Draft mode cannot be disabled during build-time instant validation.'\n )\n },\n } as Partial<DraftModeProvider> as DraftModeProvider\n}\n\n/**\n * Creates params wrapped with an exhaustive proxy.\n * Accessing a param not declared in the sample will throw an error.\n */\nexport function createExhaustiveParamsProxy<TParams extends Params>(\n underlyingParams: TParams,\n declaredParamNames: Set<string>,\n route: string\n): TParams {\n return new Proxy(underlyingParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n // Only error when accessing a param that is part of the route but wasn't provided.\n // accessing properties that aren't expected to be a valid param value is fine.\n prop in underlyingParams &&\n !declaredParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n // We don't need to override `has` or `ownKeys`.\n // the shape of the params object is determined by the routing structure\n // and independent of the samples. We only need to instrument accessing the values.\n })\n}\n\n/**\n * Creates searchParams wrapped with an exhaustive proxy.\n * Accessing a searchParam not declared in the sample will throw an error.\n * A searchParam with `value: undefined` means \"declared but absent\" (allowed to access, returns undefined).\n */\nexport function createExhaustiveSearchParamsProxy(\n searchParams: SearchParams,\n declaredSearchParamNames: Set<string>,\n route: string\n): SearchParams {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n has(target, prop) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.has(target, prop)\n },\n })\n}\n\n/**\n * Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an\n * exhaustive proxy. Accessing a search param not declared in the sample via\n * get/getAll/has will throw an error.\n */\nexport function createExhaustiveURLSearchParamsProxy<T extends URLSearchParams>(\n searchParams: T,\n declaredSearchParamNames: Set<string>,\n route: string\n): T {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n // Intercept method calls that access specific param names\n if (prop === 'get' || prop === 'getAll' || prop === 'has') {\n const originalMathod = Reflect.get(target, prop, receiver)\n return (name: string) => {\n if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, name)\n )\n }\n return (originalMathod as (...args: any[]) => any).call(target, name)\n }\n }\n const value = Reflect.get(target, prop, receiver)\n // Prevent `TypeError: Value of \"this\" must be of type URLSearchParams` for methods\n if (typeof value === 'function' && !Object.hasOwn(target, prop)) {\n return value.bind(target)\n }\n return value\n },\n })\n}\n\nfunction createMissingSearchParamSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`searchParams\\` object, ` +\n `or \\`{ \"${name}\": null }\\` if it should be absent.`\n )\n}\n\nexport function createRelativeURLFromSamples(\n route: string,\n sampleParams: InstantSample['params'],\n sampleSearchParams: InstantSample['searchParams']\n) {\n // Build searchParams query object and URL search string from sample\n const pathname = createPathnameFromRouteAndSampleParams(\n route,\n sampleParams ?? {}\n )\n\n let search = ''\n if (sampleSearchParams) {\n const qs = createURLSearchParamsFromSample(sampleSearchParams).toString()\n if (qs) {\n search = '?' + qs\n }\n }\n\n return parseRelativeUrl(pathname + search, undefined, true)\n}\n\nfunction createURLSearchParamsFromSample(\n sampleSearchParams: InstantSample['searchParams']\n) {\n const result = new URLSearchParams()\n if (sampleSearchParams) {\n for (const [key, value] of Object.entries(sampleSearchParams)) {\n if (value === null || value === undefined) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n result.append(key, v)\n }\n } else {\n result.set(key, value)\n }\n }\n }\n return result\n}\n\n/**\n * Substitute sample params into `workStore.route` to create a plausible pathname.\n * TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,\n * but it should be good enough for some initial testing.\n */\nfunction createPathnameFromRouteAndSampleParams(route: string, params: Params) {\n let interpolatedSegments: string[] = []\n const rawSegments = route.split('/')\n for (const rawSegment of rawSegments) {\n const param = getSegmentParam(rawSegment)\n if (param) {\n switch (param.paramType) {\n case 'catchall':\n case 'optional-catchall': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = [rawSegment]\n } else if (!Array.isArray(paramValue)) {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(\n ...paramValue.map((v) => encodeURIComponent(v))\n )\n break\n }\n case 'dynamic': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = rawSegment\n } else if (typeof paramValue !== 'string') {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(encodeURIComponent(paramValue))\n break\n }\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)': {\n // TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here\n throw new InvariantError(\n 'Not implemented: Validation of interception routes'\n )\n }\n default: {\n param.paramType satisfies never\n }\n }\n } else {\n interpolatedSegments.push(rawSegment)\n }\n }\n return interpolatedSegments.join('/')\n}\n\nexport function assertRootParamInSamples(\n workStore: WorkStore,\n sampleParams: Params | undefined,\n paramName: string\n) {\n if (sampleParams && paramName in sampleParams) {\n // The param is defined in the samples.\n } else {\n const route = workStore.route\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n}\n"],"names":["RequestCookies","RequestCookiesAdapter","HeadersAdapter","getSegmentParam","parseRelativeUrl","InvariantError","InstantValidationError","workUnitAsyncStorage","wellKnownProperties","createValidationSampleTracking","missingSampleErrors","getExpectedSampleTracking","validationSampleTracking","workUnitStore","getStore","type","trackMissingSampleError","error","push","trackMissingSampleErrorAndThrow","createCookiesFromSample","sampleCookies","route","declaredNames","Set","cookies","Headers","cookie","add","name","value","set","sealed","seal","Proxy","get","target","prop","receiver","originalMethod","Reflect","wrappedMethod","has","createMissingCookieSampleError","call","nameOrCookie","createHeadersFromSample","rawSampleHeaders","sampleHeaders","find","toLowerCase","cookieHeaderValue","toString","headersInit","from","patchedMethod","rawName","createDraftModeForValidation","isEnabled","enable","Error","disable","createExhaustiveParamsProxy","underlyingParams","declaredParamNames","createExhaustiveSearchParamsProxy","searchParams","declaredSearchParamNames","createMissingSearchParamSampleError","createExhaustiveURLSearchParamsProxy","originalMathod","Object","hasOwn","bind","createRelativeURLFromSamples","sampleParams","sampleSearchParams","pathname","createPathnameFromRouteAndSampleParams","search","qs","createURLSearchParamsFromSample","undefined","result","URLSearchParams","key","entries","Array","isArray","v","append","params","interpolatedSegments","rawSegments","split","rawSegment","param","paramType","paramValue","paramName","map","encodeURIComponent","join","assertRootParamInSamples","workStore"],"mappings":"AAMA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,cAAc,QAAQ,4CAA2C;AAE1E,SAASC,eAAe,QAAQ,qDAAoD;AACpF,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SAASC,sBAAsB,QAAQ,6BAA4B;AACnE,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,mBAAmB,QAAQ,0CAAyC;AAQ7E,OAAO,SAASC;IACd,OAAO;QACLC,qBAAqB,EAAE;IACzB;AACF;AAEA,SAASC;IACP,IAAIC,2BAAmE;IACvE,MAAMC,gBAAgBN,qBAAqBO,QAAQ;IACnD,IAAID,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;gBACH,8EAA8E;gBAC9EH,2BACEC,cAAcD,wBAAwB,IAAI;gBAC5C;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEC;QACJ;IACF;IACA,IAAI,CAACD,0BAA0B;QAC7B,MAAM,qBAEL,C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AC5B,qFAAqF;4BACrF,0FAA0F;4BAC1F,6CAA6C;4BAC7CgB,aAAaH;wBACf,OAAO,IAAI,OAAOG,eAAe,UAAU;4BACzC,2FAA2F;4BAC3F,MAAM,qBAEL,CAFK,IAAI5F,uBACR,CAAC,yCAAyC,EAAEyF,WAAW,sBAAsB,EAAE,OAAOG,YAAY,GAD9F,qBAAA;uCAAA;4CAAA;8CAAA;4BAEN;wBACF;wBACAN,qBAAqB1E,IAAI,CAACmF,mBAAmBH;wBAC7C;oBACF;gBACA,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBAA6B;wBAChC,+GAA+G;wBAC/G,MAAM,qBAEL,CAFK,IAAI7F,eACR,uDADI,qBAAA;mCAAA;wCAAA;0CAAA;wBAEN;oBACF;gBACA;oBAAS;wBACP2F,MAAMC,SAAS;oBACjB;YACF;QACF,OAAO;YACLL,qBAAqB1E,IAAI,CAAC6E;QAC5B;IACF;IACA,OAAOH,qBAAqBU,IAAI,CAAC;AACnC;AAEA,OAAO,SAASC,yBACdC,SAAoB,EACpB7B,YAAgC,EAChCwB,SAAiB;IAEjB,IAAIxB,gBAAgBwB,aAAaxB,cAAc;IAC7C,uCAAuC;IACzC,OAAO;QACL,MAAMrD,QAAQkF,UAAUlF,KAAK;QAC7BH,gCACE,qBAGC,CAHD,IAAIb,uBACF,CAAC,OAAO,EAAEgB,MAAM,uBAAuB,EAAE6E,UAAU,mDAAmD,CAAC,GACrG,CAAC,yDAAyD,CAAC,GAF/D,qBAAA;mBAAA;wBAAA;0BAAA;QAGA;IAEJ;AACF","ignoreList":[0]}

@@ -106,3 +106,2 @@ import { htmlEscapeAttributeString, htmlEscapeJsonString } from '../../shared/lib/htmlescape';

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -109,0 +108,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/app-render/use-flight-response.tsx"],"sourcesContent":["import type { BinaryStreamOf } from './app-render'\nimport type { Readable } from 'node:stream'\n\nimport {\n htmlEscapeAttributeString,\n htmlEscapeJsonString,\n} from '../../shared/lib/htmlescape'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { getClientReferenceManifest } from './manifests-singleton'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0\nconst INLINE_FLIGHT_PAYLOAD_DATA = 1\nconst INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2\nconst INLINE_FLIGHT_PAYLOAD_BINARY = 3\n\nconst flightResponses = new WeakMap<\n Readable | BinaryStreamOf<any>,\n Promise<any>\n>()\nconst encoder = new TextEncoder()\n\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Render Flight stream.\n * This is only used for renderToHTML, the Flight response does not need additional wrappers.\n */\nexport function getFlightStream<T>(\n flightStream: Readable | BinaryStreamOf<T>,\n debugStream: Readable | ReadableStream<Uint8Array> | undefined,\n debugEndTime: number | undefined,\n nonce: string | undefined\n): Promise<T> {\n const response = flightResponses.get(flightStream)\n\n if (response) {\n return response\n }\n\n const { moduleLoading, edgeSSRModuleMapping, ssrModuleMapping } =\n getClientReferenceManifest()\n\n let newResponse: Promise<T>\n if (flightStream instanceof ReadableStream) {\n // The types of flightStream and debugStream should match.\n if (debugStream && !(debugStream instanceof ReadableStream)) {\n throw new InvariantError('Expected debug stream to be a ReadableStream')\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromReadableStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromReadableStream<T>(flightStream, {\n findSourceMapURL,\n serverConsumerManifest: {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n nonce,\n debugChannel: debugStream ? { readable: debugStream } : undefined,\n endTime: debugEndTime,\n })\n } else {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'getFlightStream should always receive a ReadableStream when using the edge runtime'\n )\n } else {\n const { Readable } =\n require('node:stream') as typeof import('node:stream')\n\n // Convert debug stream to Readable if it's a ReadableStream.\n // When __NEXT_USE_NODE_STREAMS is enabled, the debug channel produces\n // Node Readables natively. Otherwise, it produces web ReadableStreams.\n let nodeDebugStream: Readable | undefined\n if (debugStream) {\n if (debugStream instanceof Readable) {\n nodeDebugStream = debugStream\n } else {\n type WebReadableStream = import('stream/web').ReadableStream\n nodeDebugStream = Readable.fromWeb(debugStream as WebReadableStream)\n }\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromNodeStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromNodeStream<T>(\n flightStream,\n {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n {\n findSourceMapURL,\n nonce,\n debugChannel: nodeDebugStream,\n endTime: debugEndTime,\n }\n )\n }\n }\n\n // Edge pages are never prerendered so they necessarily cannot have a workUnitStore type\n // that requires the nextTick behavior. This is why it is safe to access a node only API here\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workUnitStore) {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n }\n\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'validation-client':\n const responseOnNextTick = new Promise<T>((resolve) => {\n process.nextTick(() => {\n resolve(newResponse)\n })\n })\n flightResponses.set(flightStream, responseOnNextTick)\n return responseOnNextTick\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n flightResponses.set(flightStream, newResponse)\n\n return newResponse\n}\n\n/**\n * Creates a ReadableStream provides inline script tag chunks for writing hydration\n * data to the client outside the React render itself.\n *\n * @param flightStream The RSC render stream\n * @param nonce optionally a nonce used during this particular render\n * @param formState optionally the formState used with this particular render\n * @returns a ReadableStream without the complete property. This signifies a lazy ReadableStream\n */\nexport function createInlinedDataReadableStream(\n flightStream: ReadableStream<Uint8Array>,\n nonce: string | undefined,\n formState: unknown | null\n): ReadableStream<Uint8Array> {\n const startScriptTag = nonce\n ? `<script nonce=\"${htmlEscapeAttributeString(nonce)}\">`\n : '<script>'\n\n const flightReader = flightStream.getReader()\n const decoder = new TextDecoder('utf-8', { fatal: true })\n\n const readable = new ReadableStream({\n type: 'bytes',\n start(controller) {\n try {\n writeInitialInstructions(controller, startScriptTag, formState)\n } catch (error) {\n // during encoding or enqueueing forward the error downstream\n controller.error(error)\n }\n },\n async pull(controller) {\n try {\n const { done, value } = await flightReader.read()\n\n if (value) {\n try {\n const decodedString = decoder.decode(value, { stream: !done })\n\n // The chunk cannot be decoded as valid UTF-8 string as it might\n // have arbitrary binary data.\n writeFlightDataInstruction(\n controller,\n startScriptTag,\n decodedString\n )\n } catch {\n // The chunk cannot be decoded as valid UTF-8 string.\n writeFlightDataInstruction(controller, startScriptTag, value)\n }\n }\n\n if (done) {\n controller.close()\n }\n } catch (error) {\n // There was a problem in the upstream reader or during decoding or enqueuing\n // forward the error downstream\n controller.error(error)\n }\n },\n })\n\n return readable\n}\n\nfunction writeInitialInstructions(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n formState: unknown | null\n) {\n let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])\n )})`\n\n if (formState != null) {\n scriptContents += `;self.__next_f.push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])\n )})`\n }\n\n controller.enqueue(encoder.encode(`${scriptStart}${scriptContents}</script>`))\n}\n\nfunction writeFlightDataInstruction(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n chunk: string | Uint8Array\n) {\n let htmlInlinedData: string\n\n if (typeof chunk === 'string') {\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, chunk])\n )\n } else {\n // The chunk cannot be embedded as a UTF-8 string in the script tag.\n // Instead let's inline it in base64.\n // Credits to Devon Govett (devongovett) for the technique.\n // https://github.com/devongovett/rsc-html-stream\n const base64 =\n typeof Buffer !== 'undefined'\n ? Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n ).toString('base64')\n : btoa(String.fromCodePoint(...chunk))\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64])\n )\n }\n\n controller.enqueue(\n encoder.encode(\n `${scriptStart}self.__next_f.push(${htmlInlinedData})</script>`\n )\n )\n}\n"],"names":["htmlEscapeAttributeString","htmlEscapeJsonString","workUnitAsyncStorage","InvariantError","getClientReferenceManifest","isEdgeRuntime","process","env","NEXT_RUNTIME","INLINE_FLIGHT_PAYLOAD_BOOTSTRAP","INLINE_FLIGHT_PAYLOAD_DATA","INLINE_FLIGHT_PAYLOAD_FORM_STATE","INLINE_FLIGHT_PAYLOAD_BINARY","flightResponses","WeakMap","encoder","TextEncoder","findSourceMapURL","NODE_ENV","require","findSourceMapURLDEV","undefined","getFlightStream","flightStream","debugStream","debugEndTime","nonce","response","get","moduleLoading","edgeSSRModuleMapping","ssrModuleMapping","newResponse","ReadableStream","createFromReadableStream","serverConsumerManifest","moduleMap","serverModuleMap","debugChannel","readable","endTime","Readable","nodeDebugStream","fromWeb","createFromNodeStream","workUnitStore","getStore","type","responseOnNextTick","Promise","resolve","nextTick","set","createInlinedDataReadableStream","formState","startScriptTag","flightReader","getReader","decoder","TextDecoder","fatal","start","controller","writeInitialInstructions","error","pull","done","value","read","decodedString","decode","stream","writeFlightDataInstruction","close","scriptStart","scriptContents","JSON","stringify","enqueue","encode","chunk","htmlInlinedData","base64","Buffer","from","buffer","byteOffset","byteLength","toString","btoa","String","fromCodePoint"],"mappings":"AAGA,SACEA,yBAAyB,EACzBC,oBAAoB,QACf,8BAA6B;AACpC,SAASC,oBAAoB,QAAQ,qCAAoC;AACzE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,0BAA0B,QAAQ,wBAAuB;AAElE,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD,MAAMC,kCAAkC;AACxC,MAAMC,6BAA6B;AACnC,MAAMC,mCAAmC;AACzC,MAAMC,+BAA+B;AAErC,MAAMC,kBAAkB,IAAIC;AAI5B,MAAMC,UAAU,IAAIC;AAEpB,MAAMC,mBACJX,QAAQC,GAAG,CAACW,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AAEN;;;CAGC,GACD,OAAO,SAASC,gBACdC,YAA0C,EAC1CC,WAA8D,EAC9DC,YAAgC,EAChCC,KAAyB;IAEzB,MAAMC,WAAWd,gBAAgBe,GAAG,CAACL;IAErC,IAAII,UAAU;QACZ,OAAOA;IACT;IAEA,MAAM,EAAEE,aAAa,EAAEC,oBAAoB,EAAEC,gBAAgB,EAAE,GAC7D3B;IAEF,IAAI4B;IACJ,IAAIT,wBAAwBU,gBAAgB;QAC1C,0DAA0D;QAC1D,IAAIT,eAAe,CAAEA,CAAAA,uBAAuBS,cAAa,GAAI;YAC3D,MAAM,qBAAkE,CAAlE,IAAI9B,eAAe,iDAAnB,qBAAA;uBAAA;4BAAA;8BAAA;YAAiE;QACzE;QAEA,wGAAwG;QACxG,MAAM,EAAE+B,wBAAwB,EA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A,OAAOzB;AACT;AAEA,SAASwB,yBACPD,UAA2C,EAC3CY,WAAmB,EACnBpB,SAAyB;IAEzB,IAAIqB,iBAAiB,CAAC,uCAAuC,EAAE1E,qBAC7D2E,KAAKC,SAAS,CAAC;QAACpE;KAAgC,GAChD,CAAC,CAAC;IAEJ,IAAI6C,aAAa,MAAM;QACrBqB,kBAAkB,CAAC,oBAAoB,EAAE1E,qBACvC2E,KAAKC,SAAS,CAAC;YAAClE;YAAkC2C;SAAU,GAC5D,CAAC,CAAC;IACN;IAEAQ,WAAWgB,OAAO,CAAC/D,QAAQgE,MAAM,CAAC,GAAGL,cAAcC,eAAe,SAAS,CAAC;AAC9E;AAEA,SAASH,2BACPV,UAA2C,EAC3CY,WAAmB,EACnBM,KAA0B;IAE1B,IAAIC;IAEJ,IAAI,OAAOD,UAAU,UAAU;QAC7BC,kBAAkBhF,qBAChB2E,KAAKC,SAAS,CAAC;YAACnE;YAA4BsE;SAAM;IAEtD,OAAO;QACL,oEAAoE;QACpE,qCAAqC;QACrC,2DAA2D;QAC3D,iDAAiD;QACjD,MAAME,SACJ,OAAOC,WAAW,cACdA,OAAOC,IAAI,CACTJ,MAAMK,MAAM,EACZL,MAAMM,UAAU,EAChBN,MAAMO,UAAU,EAChBC,QAAQ,CAAC,YACXC,KAAKC,OAAOC,aAAa,IAAIX;QACnCC,kBAAkBhF,qBAChB2E,KAAKC,SAAS,CAAC;YAACjE;YAA8BsE;SAAO;IAEzD;IAEApB,WAAWgB,OAAO,CAChB/D,QAAQgE,MAAM,CACZ,GAAGL,YAAY,mBAAmB,EAAEO,gBAAgB,UAAU,CAAC;AAGrE","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/app-render/use-flight-response.tsx"],"sourcesContent":["import type { BinaryStreamOf } from './app-render'\nimport type { Readable } from 'node:stream'\n\nimport {\n htmlEscapeAttributeString,\n htmlEscapeJsonString,\n} from '../../shared/lib/htmlescape'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { getClientReferenceManifest } from './manifests-singleton'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0\nconst INLINE_FLIGHT_PAYLOAD_DATA = 1\nconst INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2\nconst INLINE_FLIGHT_PAYLOAD_BINARY = 3\n\nconst flightResponses = new WeakMap<\n Readable | BinaryStreamOf<any>,\n Promise<any>\n>()\nconst encoder = new TextEncoder()\n\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Render Flight stream.\n * This is only used for renderToHTML, the Flight response does not need additional wrappers.\n */\nexport function getFlightStream<T>(\n flightStream: Readable | BinaryStreamOf<T>,\n debugStream: Readable | ReadableStream<Uint8Array> | undefined,\n debugEndTime: number | undefined,\n nonce: string | undefined\n): Promise<T> {\n const response = flightResponses.get(flightStream)\n\n if (response) {\n return response\n }\n\n const { moduleLoading, edgeSSRModuleMapping, ssrModuleMapping } =\n getClientReferenceManifest()\n\n let newResponse: Promise<T>\n if (flightStream instanceof ReadableStream) {\n // The types of flightStream and debugStream should match.\n if (debugStream && !(debugStream instanceof ReadableStream)) {\n throw new InvariantError('Expected debug stream to be a ReadableStream')\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromReadableStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromReadableStream<T>(flightStream, {\n findSourceMapURL,\n serverConsumerManifest: {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n nonce,\n debugChannel: debugStream ? { readable: debugStream } : undefined,\n endTime: debugEndTime,\n })\n } else {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'getFlightStream should always receive a ReadableStream when using the edge runtime'\n )\n } else {\n const { Readable } =\n require('node:stream') as typeof import('node:stream')\n\n // Convert debug stream to Readable if it's a ReadableStream.\n // When __NEXT_USE_NODE_STREAMS is enabled, the debug channel produces\n // Node Readables natively. Otherwise, it produces web ReadableStreams.\n let nodeDebugStream: Readable | undefined\n if (debugStream) {\n if (debugStream instanceof Readable) {\n nodeDebugStream = debugStream\n } else {\n type WebReadableStream = import('stream/web').ReadableStream\n nodeDebugStream = Readable.fromWeb(debugStream as WebReadableStream)\n }\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromNodeStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromNodeStream<T>(\n flightStream,\n {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n {\n findSourceMapURL,\n nonce,\n debugChannel: nodeDebugStream,\n endTime: debugEndTime,\n }\n )\n }\n }\n\n // Edge pages are never prerendered so they necessarily cannot have a workUnitStore type\n // that requires the nextTick behavior. This is why it is safe to access a node only API here\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workUnitStore) {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n }\n\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'validation-client':\n const responseOnNextTick = new Promise<T>((resolve) => {\n process.nextTick(() => {\n resolve(newResponse)\n })\n })\n flightResponses.set(flightStream, responseOnNextTick)\n return responseOnNextTick\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n flightResponses.set(flightStream, newResponse)\n\n return newResponse\n}\n\n/**\n * Creates a ReadableStream provides inline script tag chunks for writing hydration\n * data to the client outside the React render itself.\n *\n * @param flightStream The RSC render stream\n * @param nonce optionally a nonce used during this particular render\n * @param formState optionally the formState used with this particular render\n * @returns a ReadableStream without the complete property. This signifies a lazy ReadableStream\n */\nexport function createInlinedDataReadableStream(\n flightStream: ReadableStream<Uint8Array>,\n nonce: string | undefined,\n formState: unknown | null\n): ReadableStream<Uint8Array> {\n const startScriptTag = nonce\n ? `<script nonce=\"${htmlEscapeAttributeString(nonce)}\">`\n : '<script>'\n\n const flightReader = flightStream.getReader()\n const decoder = new TextDecoder('utf-8', { fatal: true })\n\n const readable = new ReadableStream({\n type: 'bytes',\n start(controller) {\n try {\n writeInitialInstructions(controller, startScriptTag, formState)\n } catch (error) {\n // during encoding or enqueueing forward the error downstream\n controller.error(error)\n }\n },\n async pull(controller) {\n try {\n const { done, value } = await flightReader.read()\n\n if (value) {\n try {\n const decodedString = decoder.decode(value, { stream: !done })\n\n // The chunk cannot be decoded as valid UTF-8 string as it might\n // have arbitrary binary data.\n writeFlightDataInstruction(\n controller,\n startScriptTag,\n decodedString\n )\n } catch {\n // The chunk cannot be decoded as valid UTF-8 string.\n writeFlightDataInstruction(controller, startScriptTag, value)\n }\n }\n\n if (done) {\n controller.close()\n }\n } catch (error) {\n // There was a problem in the upstream reader or during decoding or enqueuing\n // forward the error downstream\n controller.error(error)\n }\n },\n })\n\n return readable\n}\n\nfunction writeInitialInstructions(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n formState: unknown | null\n) {\n let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])\n )})`\n\n if (formState != null) {\n scriptContents += `;self.__next_f.push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])\n )})`\n }\n\n controller.enqueue(encoder.encode(`${scriptStart}${scriptContents}</script>`))\n}\n\nfunction writeFlightDataInstruction(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n chunk: string | Uint8Array\n) {\n let htmlInlinedData: string\n\n if (typeof chunk === 'string') {\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, chunk])\n )\n } else {\n // The chunk cannot be embedded as a UTF-8 string in the script tag.\n // Instead let's inline it in base64.\n // Credits to Devon Govett (devongovett) for the technique.\n // https://github.com/devongovett/rsc-html-stream\n const base64 =\n typeof Buffer !== 'undefined'\n ? Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n ).toString('base64')\n : btoa(String.fromCodePoint(...chunk))\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64])\n )\n }\n\n controller.enqueue(\n encoder.encode(\n `${scriptStart}self.__next_f.push(${htmlInlinedData})</script>`\n )\n )\n}\n"],"names":["htmlEscapeAttributeString","htmlEscapeJsonString","workUnitAsyncStorage","InvariantError","getClientReferenceManifest","isEdgeRuntime","process","env","NEXT_RUNTIME","INLINE_FLIGHT_PAYLOAD_BOOTSTRAP","INLINE_FLIGHT_PAYLOAD_DATA","INLINE_FLIGHT_PAYLOAD_FORM_STATE","INLINE_FLIGHT_PAYLOAD_BINARY","flightResponses","WeakMap","encoder","TextEncoder","findSourceMapURL","NODE_ENV","require","findSourceMapURLDEV","undefined","getFlightStream","flightStream","debugStream","debugEndTime","nonce","response","get","moduleLoading","edgeSSRModuleMapping","ssrModuleMapping","newResponse","ReadableStream","createFromReadableStream","serverConsumerManifest","moduleMap","serverModuleMap","debugChannel","readable","endTime","Readable","nodeDebugStream","fromWeb","createFromNodeStream","workUnitStore","getStore","type","responseOnNextTick","Promise","resolve","nextTick","set","createInlinedDataReadableStream","formState","startScriptTag","flightReader","getReader","decoder","TextDecoder","fatal","start","controller","writeInitialInstructions","error","pull","done","value","read","decodedString","decode","stream","writeFlightDataInstruction","close","scriptStart","scriptContents","JSON","stringify","enqueue","encode","chunk","htmlInlinedData","base64","Buffer","from","buffer","byteOffset","byteLength","toString","btoa","String","fromCodePoint"],"mappings":"AAGA,SACEA,yBAAyB,EACzBC,oBAAoB,QACf,8BAA6B;AACpC,SAASC,oBAAoB,QAAQ,qCAAoC;AACzE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,0BAA0B,QAAQ,wBAAuB;AAElE,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD,MAAMC,kCAAkC;AACxC,MAAMC,6BAA6B;AACnC,MAAMC,mCAAmC;AACzC,MAAMC,+BAA+B;AAErC,MAAMC,kBAAkB,IAAIC;AAI5B,MAAMC,UAAU,IAAIC;AAEpB,MAAMC,mBACJX,QAAQC,GAAG,CAACW,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AAEN;;;CAGC,GACD,OAAO,SAASC,gBACdC,YAA0C,EAC1CC,WAA8D,EAC9DC,YAAgC,EAChCC,KAAyB;IAEzB,MAAMC,WAAWd,gBAAgBe,GAAG,CAACL;IAErC,IAAII,UAAU;QACZ,OAAOA;IACT;IAEA,MAAM,EAAEE,aAAa,EAAEC,oBAAoB,EAAEC,gBAAgB,EAAE,GAC7D3B;IAEF,IAAI4B;IACJ,IAAIT,wBAAwBU,gBAAgB;QAC1C,0DAA0D;QAC1D,IAAIT,eAAe,CAAEA,CAAAA,uBAAuBS,cAAa,GAAI;YAC3D,MAAM,qBAAkE,CAAlE,IAAI9B,eAAe,iDAAnB,qBAAA;uBAAA;4BAAA;8BAAA;YAAiE;QACzE;QAEA,wGAAwG;QACxG,MAAM,EAAE+B,wBAAwB,EAAE,GAChC,6DAA6D;QAC7Df,QAAQ;QAEVa,cAAcE,yBAA4BX,cAAc;YACtDN;YACAkB,wBAAwB;gBACtBN;gBACAO,WAAW/B,gBAAgByB,uBAAuBC;gBAClDM,iBAAiB;YACnB;YACAX;YACAY,cAAcd,cAAc;gBAAEe,UA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aAAa,MAAM;QACrBqB,kBAAkB,CAAC,oBAAoB,EAAE1E,qBACvC2E,KAAKC,SAAS,CAAC;YAAClE;YAAkC2C;SAAU,GAC5D,CAAC,CAAC;IACN;IAEAQ,WAAWgB,OAAO,CAAC/D,QAAQgE,MAAM,CAAC,GAAGL,cAAcC,eAAe,SAAS,CAAC;AAC9E;AAEA,SAASH,2BACPV,UAA2C,EAC3CY,WAAmB,EACnBM,KAA0B;IAE1B,IAAIC;IAEJ,IAAI,OAAOD,UAAU,UAAU;QAC7BC,kBAAkBhF,qBAChB2E,KAAKC,SAAS,CAAC;YAACnE;YAA4BsE;SAAM;IAEtD,OAAO;QACL,oEAAoE;QACpE,qCAAqC;QACrC,2DAA2D;QAC3D,iDAAiD;QACjD,MAAME,SACJ,OAAOC,WAAW,cACdA,OAAOC,IAAI,CACTJ,MAAMK,MAAM,EACZL,MAAMM,UAAU,EAChBN,MAAMO,UAAU,EAChBC,QAAQ,CAAC,YACXC,KAAKC,OAAOC,aAAa,IAAIX;QACnCC,kBAAkBhF,qBAChB2E,KAAKC,SAAS,CAAC;YAACjE;YAA8BsE;SAAO;IAEzD;IAEApB,WAAWgB,OAAO,CAChB/D,QAAQgE,MAAM,CACZ,GAAGL,YAAY,mBAAmB,EAAEO,gBAAgB,UAAU,CAAC;AAGrE","ignoreList":[0]}

@@ -17,3 +17,2 @@ // Share the instance module in the next-shared layer

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -56,3 +55,2 @@ return true;

case 'validation-client':
case 'prerender-ppr':
return workUnitStore.resumeDataCache;

@@ -80,3 +78,2 @@ case 'cache':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -103,3 +100,2 @@ case 'unstable-cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -126,3 +122,2 @@ case 'unstable-cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -152,3 +147,2 @@ case 'unstable-cache':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -171,3 +165,2 @@ case 'generate-static-params':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -198,3 +191,2 @@ case 'cache':

}
case 'prerender-ppr':
case 'prerender-legacy':

@@ -218,3 +210,2 @@ case 'cache':

}
case 'prerender-ppr':
case 'prerender-legacy':

@@ -221,0 +212,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n\n /**\n * DEV-only.\n * Certain APIs have different behavior in static and runtime prerenders.\n * - if `false`, they will follow static semantics\n * - if `true`, they will follow runtime semantics\n * */\n needsAppShell?: boolean // DEV-only\n /**\n * DEV-only, mutable.\n * Whether any APIs that resolve in different stages in static and\n * runtime prerenders (i.e. whose behavior varies on `needsAppShell`)\n * were used during this render.\n * */\n hasIncompatibleShellContent?: boolean\n\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["workUnitAsyncStorageInstance","InvariantError","willConsumerServerCache","workUnitStore","type","consumerWillServerCache","workUnitAsyncStorage","throwForMissingRequestStore","callingExpression","Error","throwInvariantForMissingStore","getResumeDataCache","resumeDataCache","getHmrRefreshHash","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","isHmrRefresh","getServerComponentsHmrCache","serverComponentsHmrCache","getDraftModeProviderForCacheScope","workStore","isDraftMode","draftMode","getStagedRenderingController","stagedRendering","getCacheSignal","cacheSignal","getVaryParamsAccumulator","varyParamsAccumulator"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,4BAA4B,QAAQ,0CAA0C;IAAE,wBAAwB;AAAc,EAAC;AAShI,SAASC,cAAc,QAAQ,mCAAkC;AA0bjE,OAAO,SAASC,wBACdC,aAAwC;IAExC,IAAI,CAACA,eAAe;QAClB,OAAO;IACT;IAEA,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcE,uBAAuB;QAC9C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOF;IACX;AACF;AAIA,SAASH,gCAAgCM,oBAAoB,GAAE;AAE/D,OAAO,SAASC,4BAA4BC,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,OAAO,SAASE;IACd,MAAM,qBAAoE,CAApE,IAAIT,eAAe,mDAAnB,qBAAA;eAAA;oBAAA;sBAAA;IAAmE;AAC3E;AAEA;;;;CAIC,GACD,OAAO,SAASU,mBACdR,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcS,eAAe;QACtC,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOT;IACX;AACF;AAEA,OAAO,SAASU,kBACdV,aAA4B;IAE5B,IAAIW,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QACjC,OAAQb,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,O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QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOxB;IACX;AACF;AAEA,OAAO,SAASyB,eACdzB,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAc0B,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAI1B,cAAc0B,WAAW,EAAE;oBAC7B,OAAO1B,cAAc0B,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAO1B;IACX;AACF;AAEA,OAAO,SAAS2B,yBACd3B,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAc4B,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE5B;YACA,OAAO;IACX;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n\n /**\n * DEV-only.\n * Certain APIs have different behavior in static and runtime prerenders.\n * - if `false`, they will follow static semantics\n * - if `true`, they will follow runtime semantics\n * */\n needsAppShell?: boolean // DEV-only\n /**\n * DEV-only, mutable.\n * Whether any APIs that resolve in different stages in static and\n * runtime prerenders (i.e. whose behavior varies on `needsAppShell`)\n * were used during this render.\n * */\n hasIncompatibleShellContent?: boolean\n\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["workUnitAsyncStorageInstance","InvariantError","willConsumerServerCache","workUnitStore","type","consumerWillServerCache","workUnitAsyncStorage","throwForMissingRequestStore","callingExpression","Error","throwInvariantForMissingStore","getResumeDataCache","resumeDataCache","getHmrRefreshHash","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","isHmrRefresh","getServerComponentsHmrCache","serverComponentsHmrCache","getDraftModeProviderForCacheScope","workStore","isDraftMode","draftMode","getStagedRenderingController","stagedRendering","getCacheSignal","cacheSignal","getVaryParamsAccumulator","varyParamsAccumulator"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,4BAA4B,QAAQ,0CAA0C;IAAE,wBAAwB;AAAc,EAAC;AAMhI,SAASC,cAAc,QAAQ,mCAAkC;AAoajE,OAAO,SAASC,wBACdC,aAAwC;IAExC,IAAI,CAACA,eAAe;QAClB,OAAO;IACT;IAEA,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcE,uBAAuB;QAC9C,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOF;IACX;AACF;AAIA,SAASH,gCAAgCM,oBAAoB,GAAE;AAE/D,OAAO,SAASC,4BAA4BC,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,OAAO,SAASE;IACd,MAAM,qBAAoE,CAApE,IAAIT,eAAe,mDAAnB,qBAAA;eAAA;oBAAA;sBAAA;IAAmE;AAC3E;AAEA;;;;CAIC,GACD,OAAO,SAASU,mBACdR,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcS,eAAe;QACtC,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOT;IACX;AACF;AAEA,OAAO,SAASU,kBACdV,aAA4B;IAE5B,IAAIW,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QACjC,OAAQb,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOD,cAAcc,cAAc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E,OAAOxB;IACX;AACF;AAEA,OAAO,SAASyB,eACdzB,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAc0B,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAI1B,cAAc0B,WAAW,EAAE;oBAC7B,OAAO1B,cAAc0B,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAO1B;IACX;AACF;AAEA,OAAO,SAAS2B,yBACd3B,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAc4B,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE5B;YACA,OAAO;IACX;AACF","ignoreList":[0]}

@@ -409,2 +409,3 @@ import { VALID_LOADERS } from '../shared/lib/image-config';

turbopackCjsTreeShaking: z.boolean().optional(),
turbopackCjsScopeHoisting: z.boolean().optional(),
turbopackServerFastRefresh: z.boolean().optional(),

@@ -411,0 +412,0 @@ optimizePackageImports: z.array(z.string()).optional(),

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/config-schema.ts"],"sourcesContent":["import type { NextConfig } from './config'\nimport { VALID_LOADERS } from '../shared/lib/image-config'\n\nimport { z } from 'next/dist/compiled/zod'\nimport type zod from 'next/dist/compiled/zod'\n\nimport type { SizeLimit } from '../types'\nimport {\n LIGHTNINGCSS_FEATURE_NAMES,\n type ExportPathMap,\n type TurbopackLoaderItem,\n type TurbopackOptions,\n type TurbopackRuleConfigItem,\n type TurbopackRuleConfigCollection,\n type TurbopackRuleCondition,\n type TurbopackLoaderBuiltinCondition,\n} from './config-shared'\nimport type {\n Header,\n Rewrite,\n RouteHas,\n Redirect,\n} from '../lib/load-custom-routes'\nimport { SUPPORTED_TEST_RUNNERS_LIST } from '../cli/next-test'\n\n// A custom zod schema for the SizeLimit type\nconst zSizeLimit = z.custom<SizeLimit>((val) => {\n if (typeof val === 'number' || typeof val === 'string') {\n return true\n }\n return false\n})\n\nconst zExportMap: zod.ZodType<ExportPathMap> = z.record(\n z.string(),\n z.object({\n page: z.string(),\n query: z.any(), // NextParsedUrlQuery\n\n // private optional properties\n _fallbackRouteParams: z.array(z.any()).optional(),\n _isAppDir: z.boolean().optional(),\n _isDynamicError: z.boolean().optional(),\n _isRoutePPREnabled: z.boolean().optional(),\n _allowEmptyStaticShell: z.boolean().optional(),\n _isFallbackUpgradeable: z.boolean().optional(),\n })\n)\n\nconst zRouteHas: zod.ZodType<RouteHas> = z.union([\n z.object({\n type: z.enum(['header', 'query', 'cookie']),\n key: z.string(),\n value: z.string().optional(),\n }),\n z.object({\n type: z.literal('host'),\n key: z.undefined().optional(),\n value: z.string(),\n }),\n])\n\nconst zRewrite: zod.ZodType<Rewrite> = z.object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n})\n\nconst zRedirect: zod.ZodType<Redirect> = z\n .object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n })\n .and(\n z.union([\n z.object({\n statusCode: z.never().optional(),\n permanent: z.boolean(),\n }),\n z.object({\n statusCode: z.number(),\n permanent: z.never().optional(),\n }),\n ])\n )\n\nconst zHeader: zod.ZodType<Header> = z.object({\n source: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n headers: z.array(z.object({ key: z.string(), value: z.string() })),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n\n internal: z.boolean().optional(),\n})\n\nconst zTurbopackLoaderItem: zod.ZodType<TurbopackLoaderItem> = z.union([\n z.string(),\n z.strictObject({\n loader: z.string(),\n // Any JSON value can be used as turbo loader options, so use z.any() here\n options: z.record(z.string(), z.any()).optional(),\n }),\n])\n\nconst zTurbopackLoaderBuiltinCondition: zod.ZodType<TurbopackLoaderBuiltinCondition> =\n z.union([\n z.literal('browser'),\n z.literal('foreign'),\n z.literal('development'),\n z.literal('production'),\n z.literal('node'),\n z.literal('edge-light'),\n ])\n\nconst zTurbopackCondition: zod.ZodType<TurbopackRuleCondition> = z.union([\n z.strictObject({ all: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ any: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ not: z.lazy(() => zTurbopackCondition) }),\n zTurbopackLoaderBuiltinCondition,\n z.strictObject({\n path: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n content: z.instanceof(RegExp).optional(),\n query: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n contentType: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n }),\n])\n\nconst zTurbopackModuleType = z.enum([\n 'asset',\n 'ecmascript',\n 'typescript',\n 'css',\n 'css-module',\n 'json',\n 'wasm',\n 'raw',\n 'node',\n 'bytes',\n 'text',\n])\n\nconst zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> =\n z.strictObject({\n loaders: z.array(zTurbopackLoaderItem).optional(),\n as: z.string().optional(),\n condition: zTurbopackCondition.optional(),\n type: zTurbopackModuleType.optional(),\n })\n\nconst zTurbopackRuleConfigCollection: zod.ZodType<TurbopackRuleConfigCollection> =\n z.union([\n zTurbopackRuleConfigItem,\n z.array(z.union([zTurbopackLoaderItem, zTurbopackRuleConfigItem])),\n ])\n\nconst zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({\n rules: z.record(z.string(), zTurbopackRuleConfigCollection).optional(),\n resolveAlias: z\n .record(\n z.string(),\n z.union([\n z.string(),\n z.array(z.string()),\n z.record(z.string(), z.union([z.string(), z.array(z.string())])),\n ])\n )\n .optional(),\n resolveExtensions: z.array(z.string()).optional(),\n root: z.string().optional(),\n debugIds: z.boolean().optional(),\n chunkLoadingGlobal: z.string().optional(),\n ignoreIssue: z\n .array(\n z.object({\n path: z.union([z.string(), z.instanceof(RegExp)]),\n title: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n description: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n })\n )\n .optional(),\n})\n\nexport const experimentalSchema = {\n outputHashSalt: z.string().optional(),\n useSkewCookie: z.boolean().optional(),\n after: z.boolean().optional(),\n appNavFailHandling: z.boolean().optional(),\n coldCacheBadge: z.boolean().optional(),\n preloadEntriesOnStart: z.boolean().optional(),\n allowedRevalidateHeaderKeys: z.array(z.string()).optional(),\n staleTimes: z\n .object({\n dynamic: z.number().optional(),\n static: z.number().gte(30).optional(),\n })\n .optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n clientRouterFilter: z.boolean().optional(),\n clientRouterFilterRedirects: z.boolean().optional(),\n clientRouterFilterAllowedRate: z.number().optional(),\n cpus: z.number().optional(),\n memoryBasedWorkersCount: z.boolean().optional(),\n craCompat: z.boolean().optional(),\n caseSensitiveRoutes: z.boolean().optional(),\n clientParamParsingOrigins: z.array(z.string()).optional(),\n cachedNavigations: z.boolean().optional(),\n dynamicOnHover: z.boolean().optional(),\n useOffline: z.boolean().optional(),\n optimisticRouting: z.boolean().optional(),\n instrumentationClientRouterTransitionEvents: z.boolean().optional(),\n varyParams: z.boolean().optional(),\n prefetchInlining: z\n .union([\n z.boolean(),\n z.object({\n maxSize: z.number().optional(),\n maxBundleSize: z.number().optional(),\n }),\n ])\n .optional(),\n devMemoryThresholdRestart: z.boolean().optional(),\n disableOptimizedLoading: z.boolean().optional(),\n disablePostcssPresetEnv: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n inlineCss: z.boolean().optional(),\n esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),\n serverActions: z\n .object({\n bodySizeLimit: zSizeLimit.optional(),\n allowedOrigins: z.array(z.string()).optional(),\n })\n .optional(),\n maxPostponedStateSize: zSizeLimit.optional(),\n // The original type was Record<string, any>\n extensionAlias: z.record(z.string(), z.any()).optional(),\n externalDir: z.boolean().optional(),\n externalMiddlewareRewritesResolve: z.boolean().optional(),\n externalProxyRewritesResolve: z.boolean().optional(),\n exposeTestingApiInProductionBuild: z.boolean().optional(),\n requestInsights: z.boolean().optional(),\n fallbackNodePolyfills: z.literal(false).optional(),\n fetchCacheKeyPrefix: z.string().optional(),\n forceSwcTransforms: z.boolean().optional(),\n fullySpecified: z.boolean().optional(),\n gzipSize: z.boolean().optional(),\n imgOptConcurrency: z.number().int().optional().nullable(),\n imgOptOperationCache: z.boolean().optional().nullable(),\n imgOptTimeoutInSeconds: z.number().int().optional(),\n imgOptMaxInputPixels: z.number().int().optional(),\n imgOptSequentialRead: z.boolean().optional().nullable(),\n isrFlushToDisk: z.boolean().optional(),\n largePageDataBytes: z.number().optional(),\n linkNoTouchStart: z.boolean().optional(),\n manualClientBasePath: z.boolean().optional(),\n middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),\n proxyPrefetch: z.enum(['strict', 'flexible']).optional(),\n middlewareClientMaxBodySize: zSizeLimit.optional(),\n proxyClientMaxBodySize: zSizeLimit.optional(),\n multiZoneDraftMode: z.boolean().optional(),\n cssChunking: z\n .union([\n z.boolean(),\n z.literal('strict'),\n z.literal('loose'),\n z.literal('graph'),\n z.strictObject({ type: z.literal('strict') }),\n z.strictObject({ type: z.literal('loose') }),\n z.strictObject({\n type: z.literal('graph'),\n requestCost: z.number().nonnegative().finite().optional(),\n weightDistribution: z.number().nonnegative().finite().optional(),\n }),\n ])\n .optional(),\n nextScriptWorkers: z.boolean().optional(),\n // The critter option is unknown, use z.any() here\n optimizeCss: z.union([z.boolean(), z.any()]).optional(),\n optimisticClientCache: z.boolean().optional(),\n parallelServerCompiles: z.boolean().optional(),\n parallelServerBuildTraces: z.boolean().optional(),\n ppr: z\n .union([z.boolean(), z.literal('incremental')])\n .readonly()\n .optional(),\n taint: z.boolean().optional(),\n blockingSSR: z.boolean().optional(),\n prerenderEarlyExit: z.boolean().optional(),\n proxyTimeout: z.number().gte(0).optional(),\n rootParams: z.boolean().optional(),\n mcpServer: z.boolean().optional(),\n removeUncaughtErrorAndRejectionListeners: z.boolean().optional(),\n validateRSCRequestHeaders: z.boolean().optional(),\n scrollRestoration: z.boolean().optional(),\n sri: z\n .object({\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).optional(),\n })\n .optional(),\n swcPlugins: z\n // The specific swc plugin's option is unknown, use z.any() here\n .array(z.tuple([z.string(), z.record(z.string(), z.any())]))\n .optional(),\n swcEnvOptions: z\n .object({\n mode: z.enum(['usage', 'entry']).optional(),\n coreJs: z.string().optional(),\n skip: z.array(z.string()).optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n shippedProposals: z.boolean().optional(),\n forceAllTransforms: z.boolean().optional(),\n debug: z.boolean().optional(),\n loose: z.boolean().optional(),\n })\n .optional(),\n swcTraceProfiling: z.boolean().optional(),\n // NonNullable<webpack.Configuration['experiments']>['buildHttp']\n urlImports: z.any().optional(),\n workerThreads: z.boolean().optional(),\n webVitalsAttribution: z\n .array(\n z.union([\n z.literal('CLS'),\n z.literal('FCP'),\n z.literal('FID'),\n z.literal('INP'),\n z.literal('LCP'),\n z.literal('TTFB'),\n ])\n )\n .optional(),\n // This is partial set of mdx-rs transform options we support, aligned\n // with next_core::next_config::MdxRsOptions. Ensure both types are kept in sync.\n mdxRs: z\n .union([\n z.boolean(),\n z.object({\n development: z.boolean().optional(),\n jsxRuntime: z.string().optional(),\n jsxImportSource: z.string().optional(),\n providerImportSource: z.string().optional(),\n mdxType: z.enum(['gfm', 'commonmark']).optional(),\n }),\n ])\n .optional(),\n transitionIndicator: z.boolean().optional(),\n gestureTransition: z.boolean().optional(),\n typedRoutes: z.boolean().optional(),\n webpackBuildWorker: z.boolean().optional(),\n webpackMemoryOptimizations: z.boolean().optional(),\n turbopackMemoryEviction: z\n .union([z.literal(false), z.literal('full'), z.literal('auto')])\n .optional(),\n turbopackPluginRuntimeStrategy: z\n .enum(['workerThreads', 'childProcesses'])\n .optional(),\n turbopackMinify: z\n .union([\n z.boolean(),\n z.strictObject({\n server: z.boolean().optional(),\n client: z.boolean().optional(),\n edge: z.boolean().optional(),\n }),\n ])\n .optional(),\n turbopackFileSystemCacheForDev: z.boolean().optional(),\n turbopackFileSystemCacheForBuild: z.boolean().optional(),\n turbopackSeedCacheFromWorktree: z.boolean().optional(),\n turbopackSourceMaps: z.boolean().optional(),\n turbopackInputSourceMaps: z.boolean().optional(),\n turbopackModuleFragments: z.boolean().optional(),\n turbopackRemoveUnusedImports: z.boolean().optional(),\n turbopackRemoveUnusedExports: z.boolean().optional(),\n turbopackScopeHoisting: z.boolean().optional(),\n turbopackSharedRuntime: z.boolean().optional(),\n turbopackChunking: z\n .object({\n firstPageLoadPriority: z.number().min(0).max(1).optional(),\n priorityRoutes: z.array(z.instanceof(RegExp)).optional(),\n priorityBoost: z.number().min(1).optional(),\n requestCost: z.number().min(0).finite().optional(),\n minChunkSize: z.number().min(0).optional(),\n maxChunkCountPerGroup: z.number().min(0).optional(),\n maxMergeChunkSize: z.number().min(0).optional(),\n minComponentChunkSize: z.number().min(0).optional(),\n generateComponentChunks: z.boolean().optional(),\n })\n .optional(),\n turbopackWorkerAssetPrefix: z.string().optional(),\n turbopackClientSideNestedAsyncChunking: z.boolean().optional(),\n turbopackServerSideNestedAsyncChunking: z.boolean().optional(),\n turbopackImportTypeBytes: z.boolean().optional(),\n turbopackUseBuiltinBabel: z.boolean().optional(),\n turbopackUseBuiltinSass: z.boolean().optional(),\n turbopackLocalPostcssConfig: z.boolean().optional(),\n turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),\n turbopackInferModuleSideEffects: z.boolean().optional(),\n turbopackCjsTreeShaking: z.boolean().optional(),\n turbopackServerFastRefresh: z.boolean().optional(),\n optimizePackageImports: z.array(z.string()).optional(),\n optimizeServerReact: z.boolean().optional(),\n strictRouteTypes: z.boolean().optional(),\n useTypeScriptCli: z.boolean().optional(),\n clientTraceMetadata: z.array(z.string()).optional(),\n serverMinification: z.boolean().optional(),\n serverSourceMaps: z.boolean().optional(),\n useWasmBinary: z.boolean().optional(),\n useLightningcss: z.boolean().optional(),\n lightningCssFeatures: z\n .object({\n include: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n exclude: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n })\n .optional(),\n testProxy: z.boolean().optional(),\n defaultTestRunner: z.enum(SUPPORTED_TEST_RUNNERS_LIST).optional(),\n allowDevelopmentBuild: z.literal(true).optional(),\n\n reactDebugChannel: z.boolean().optional(),\n instantInsights: z\n .object({\n validationLevel: z\n .enum([\n 'warning',\n 'manual-warning',\n 'experimental-error',\n 'experimental-manual-error',\n ])\n .optional(),\n })\n .optional(),\n devValidationWorker: z.boolean().optional(),\n staticGenerationRetryCount: z.number().int().optional(),\n staticGenerationMaxConcurrency: z.number().int().optional(),\n staticGenerationMinPagesPerWorker: z.number().int().optional(),\n typedEnv: z.boolean().optional(),\n serverComponentsHmrCache: z.boolean().optional(),\n serverComponentsHmrCancellation: z.boolean().optional(),\n authInterrupts: z.boolean().optional(),\n useCache: z.boolean().optional(),\n durableUseCacheEntries: z.boolean().optional(),\n useCacheTimeout: z.number().positive().optional(),\n slowModuleDetection: z\n .object({\n buildTimeThresholdMs: z.number().int(),\n })\n .optional(),\n globalNotFound: z.boolean().optional(),\n turbopackRustReactCompiler: z.boolean().optional(),\n browserDebugInfoInTerminal: z\n .union([\n z.boolean(),\n z.enum(['error', 'warn', 'verbose']),\n z.object({\n level: z.enum(['error', 'warn', 'verbose']).optional(),\n depthLimit: z.number().int().positive().optional(),\n edgeLimit: z.number().int().positive().optional(),\n showSourceLocation: z.boolean().optional(),\n }),\n ])\n .optional(),\n lockDistDir: z.boolean().optional(),\n hideLogsAfterAbort: z.boolean().optional(),\n runtimeServerDeploymentId: z.boolean().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n deferredEntries: z.array(z.string()).optional(),\n onBeforeDeferredEntries: z.function().returns(z.promise(z.void())).optional(),\n reportSystemEnvInlining: z.enum(['warn', 'error']).optional(),\n}\n\nexport const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>\n z.strictObject({\n adapterPath: z.string().optional(),\n agentRules: z.boolean().optional(),\n allowedDevOrigins: z.array(z.string()).optional(),\n assetPrefix: z.string().optional(),\n basePath: z.string().optional(),\n bundlePagesRouterDependencies: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n cacheHandler: z.string().min(1).optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheMaxMemorySize: z.number().optional(),\n cleanDistDir: z.boolean().optional(),\n compiler: z\n .strictObject({\n emotion: z\n .union([\n z.boolean(),\n z.object({\n sourceMap: z.boolean().optional(),\n autoLabel: z\n .union([\n z.literal('always'),\n z.literal('dev-only'),\n z.literal('never'),\n ])\n .optional(),\n labelFormat: z.string().min(1).optional(),\n importMap: z\n .record(\n z.string(),\n z.record(\n z.string(),\n z.object({\n canonicalImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n styledBaseImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n })\n )\n )\n .optional(),\n }),\n ])\n .optional(),\n reactRemoveProperties: z\n .union([\n z.boolean().optional(),\n z.object({\n properties: z.array(z.string()).optional(),\n }),\n ])\n .optional(),\n relay: z\n .object({\n src: z.string(),\n artifactDirectory: z.string().optional(),\n language: z.enum(['javascript', 'typescript', 'flow']).optional(),\n eagerEsModules: z.boolean().optional(),\n })\n .optional(),\n removeConsole: z\n .union([\n z.boolean().optional(),\n z.object({\n exclude: z.array(z.string()).min(1).optional(),\n }),\n ])\n .optional(),\n styledComponents: z.union([\n z.boolean().optional(),\n z.object({\n displayName: z.boolean().optional(),\n topLevelImportPaths: z.array(z.string()).optional(),\n ssr: z.boolean().optional(),\n fileName: z.boolean().optional(),\n meaninglessFileNames: z.array(z.string()).optional(),\n minify: z.boolean().optional(),\n transpileTemplateLiterals: z.boolean().optional(),\n namespace: z.string().min(1).optional(),\n pure: z.boolean().optional(),\n cssProp: z.boolean().optional(),\n }),\n ]),\n styledJsx: z.union([\n z.boolean().optional(),\n z.object({\n useLightningcss: z.boolean().optional(),\n }),\n ]),\n define: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n defineServer: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n runAfterProductionCompile: z\n .function()\n .returns(z.promise(z.void()))\n .optional(),\n })\n .optional(),\n compress: z.boolean().optional(),\n configOrigin: z.string().optional(),\n crossOrigin: z\n .union([z.literal('anonymous'), z.literal('use-credentials')])\n .optional(),\n deploymentId: z.string().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n outputHashSalt: z.string().optional(),\n devIndicators: z\n .union([\n z.object({\n position: z\n .union([\n z.literal('bottom-left'),\n z.literal('bottom-right'),\n z.literal('top-left'),\n z.literal('top-right'),\n ])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n distDir: z.string().min(1).optional(),\n env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(),\n enablePrerenderSourceMaps: z.boolean().optional(),\n excludeDefaultMomentLocales: z.boolean().optional(),\n experimental: z.strictObject(experimentalSchema).optional(),\n exportPathMap: z\n .function()\n .args(\n zExportMap,\n z.object({\n dev: z.boolean(),\n dir: z.string(),\n outDir: z.string().nullable(),\n distDir: z.string(),\n buildId: z.string(),\n })\n )\n .returns(z.union([zExportMap, z.promise(zExportMap)]))\n .optional(),\n generateBuildId: z\n .function()\n .args()\n .returns(\n z.union([\n z.string(),\n z.null(),\n z.promise(z.union([z.string(), z.null()])),\n ])\n )\n .optional(),\n generateEtags: z.boolean().optional(),\n headers: z\n .function()\n .args()\n .returns(z.promise(z.array(zHeader)))\n .optional(),\n htmlLimitedBots: z.instanceof(RegExp).optional(),\n httpAgentOptions: z\n .strictObject({ keepAlive: z.boolean().optional() })\n .optional(),\n i18n: z\n .strictObject({\n defaultLocale: z.string().min(1),\n domains: z\n .array(\n z.strictObject({\n defaultLocale: z.string().min(1),\n domain: z.string().min(1),\n http: z.literal(true).optional(),\n locales: z.array(z.string().min(1)).optional(),\n })\n )\n .optional(),\n localeDetection: z.literal(false).optional(),\n locales: z.array(z.string().min(1)),\n })\n .nullable()\n .optional(),\n images: z\n .strictObject({\n localPatterns: z\n .array(\n z.strictObject({\n pathname: z.string().optional(),\n search: z.string().optional(),\n })\n )\n .max(25)\n .optional(),\n remotePatterns: z\n .array(\n z.union([\n z.instanceof(URL),\n z.strictObject({\n hostname: z.string(),\n pathname: z.string().optional(),\n port: z.string().max(5).optional(),\n protocol: z.enum(['http', 'https']).optional(),\n search: z.string().optional(),\n }),\n ])\n )\n .max(50)\n .optional(),\n unoptimized: z.boolean().optional(),\n customCacheHandler: z.boolean().optional(),\n contentSecurityPolicy: z.string().optional(),\n contentDispositionType: z.enum(['inline', 'attachment']).optional(),\n dangerouslyAllowSVG: z.boolean().optional(),\n dangerouslyAllowLocalIP: z.boolean().optional(),\n deviceSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .max(25)\n .optional(),\n disableStaticImages: z.boolean().optional(),\n domains: z.array(z.string()).max(50).optional(),\n formats: z\n .array(z.enum(['image/avif', 'image/webp']))\n .max(4)\n .optional(),\n imageSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .min(0)\n .max(25)\n .optional(),\n loader: z.enum(VALID_LOADERS).optional(),\n loaderFile: z.string().optional(),\n maximumDiskCacheSize: z.number().int().min(0).optional(),\n maximumRedirects: z.number().int().min(0).max(20).optional(),\n maximumResponseBody: z\n .number()\n .int()\n .min(1)\n .max(Number.MAX_SAFE_INTEGER)\n .optional(),\n minimumCacheTTL: z.number().int().gte(0).optional(),\n path: z.string().optional(),\n qualities: z\n .array(z.number().int().gte(1).lte(100))\n .min(1)\n .max(20)\n .optional(),\n })\n .optional(),\n logging: z\n .union([\n z.object({\n fetches: z\n .object({\n fullUrl: z.boolean().optional(),\n hmrRefreshes: z.boolean().optional(),\n })\n .optional(),\n incomingRequests: z\n .union([\n z.boolean(),\n z.object({\n ignore: z.array(z.instanceof(RegExp)),\n }),\n ])\n .optional(),\n serverFunctions: z.boolean().optional(),\n browserToTerminal: z\n .union([z.boolean(), z.enum(['error', 'warn'])])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n modularizeImports: z\n .record(\n z.string(),\n z.object({\n transform: z.union([z.string(), z.record(z.string(), z.string())]),\n preventFullImport: z.boolean().optional(),\n skipDefaultConversion: z.boolean().optional(),\n })\n )\n .optional(),\n onDemandEntries: z\n .strictObject({\n maxInactiveAge: z.number().optional(),\n pagesBufferLength: z.number().optional(),\n })\n .optional(),\n output: z.enum(['standalone', 'export']).optional(),\n outputFileTracingRoot: z.string().optional(),\n outputFileTracingExcludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n outputFileTracingIncludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n pageExtensions: z.array(z.string()).min(1).optional(),\n instrumentationClientInject: z.array(z.string()).optional(),\n partialPrefetching: z\n .union([z.boolean(), z.literal('unstable_eager')])\n .optional(),\n poweredByHeader: z.boolean().optional(),\n productionBrowserSourceMaps: z.boolean().optional(),\n reactCompiler: z.union([\n z.boolean(),\n z\n .object({\n compilationMode: z.enum(['infer', 'annotation', 'all']).optional(),\n panicThreshold: z\n .enum(['none', 'critical_errors', 'all_errors'])\n .optional(),\n })\n .optional(),\n ]),\n reactProductionProfiling: z.boolean().optional(),\n reactStrictMode: z.boolean().nullable().optional(),\n reactMaxHeadersLength: z.number().nonnegative().int().optional(),\n redirects: z\n .function()\n .args()\n .returns(z.promise(z.array(zRedirect)))\n .optional(),\n rewrites: z\n .function()\n .args()\n .returns(\n z.promise(\n z.union([\n z.array(zRewrite),\n z.object({\n beforeFiles: z.array(zRewrite),\n afterFiles: z.array(zRewrite),\n fallback: z.array(zRewrite),\n }),\n ])\n )\n )\n .optional(),\n // sassOptions properties are unknown besides implementation, use z.any() here\n sassOptions: z\n .object({\n implementation: z.string().optional(),\n })\n .catchall(z.any())\n .optional(),\n serverExternalPackages: z.array(z.string()).optional(),\n skipMiddlewareUrlNormalize: z.boolean().optional(),\n skipProxyUrlNormalize: z.boolean().optional(),\n skipTrailingSlashRedirect: z.boolean().optional(),\n staticPageGenerationTimeout: z.number().optional(),\n expireTime: z.number().optional(),\n target: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n transpilePackages: z.array(z.string()).optional(),\n turbopack: zTurbopackConfig.optional(),\n typescript: z\n .strictObject({\n ignoreBuildErrors: z.boolean().optional(),\n tsconfigPath: z.string().min(1).optional(),\n })\n .optional(),\n typedRoutes: z.boolean().optional(),\n useFileSystemPublicRoutes: z.boolean().optional(),\n // The webpack config type is unknown, use z.any() here\n webpack: z.any().nullable().optional(),\n watchOptions: z\n .strictObject({\n pollIntervalMs: z.number().positive().finite().optional(),\n })\n .optional(),\n })\n)\n"],"names":["VALID_LOADERS","z","LIGHTNINGCSS_FEATURE_NAMES","SUPPORTED_TEST_RUNNERS_LIST","zSizeLimit","custom","val","zExportMap","record","string","object","page","query","any","_fallbackRouteParams","array","optional","_isAppDir","boolean","_isDynamicError","_isRoutePPREnabled","_allowEmptyStaticShell","_isFallbackUpgradeable","zRouteHas","union","type","enum","key","value","literal","undefined","zRewrite","source","destination","basePath","locale","has","missing","internal","zRedirect","and","statusCode","never","permanent","number","zHeader","headers","zTurbopackLoaderItem","strictObject","loader","options","zTurbopackLoaderBuiltinCondition","zTurbopackCondition","all","lazy","not","path","instanceof","RegExp","content","contentType","zTurbopackModuleType","zTurbopackRuleConfigItem","loaders","as","condition","zTurbopackRuleConfigCollection","zTurbopackConfig","rules","resolveAlias","resolveExtensions","root","debugIds","chunkLoadingGlobal","ignoreIssue","title","description","experimentalSchema","outputHashSalt","useSkewCookie","after","appNavFailHandling","coldCacheBadge","preloadEntriesOnStart","allowedRevalidateHeaderKeys","staleTimes","dynamic","static","gte","cacheLife","stale","revalidate","expire","cacheHandlers","clientRouterFilter","clientRouterFilterRedirects","clientRouterFilterAllowedRate","cpus","memoryBasedWorkersCount","craCompat","caseSensitiveRoutes","clientParamParsingOrigins","cachedNavigations","dynamicOnHover","useOffline","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","prefetchInlining","maxSize","maxBundleSize","devMemoryThresholdRestart","disableOptimizedLoading","disablePostcssPresetEnv","cacheComponents","inlineCss","esmExternals","serverActions","bodySizeLimit","allowedOrigins","maxPostponedStateSize","extensionAlias","externalDir","externalMiddlewareRewritesResolve","externalProxyRewritesResolve","exposeTestingApiInProductionBuild","requestInsights","fallbackNodePolyfills","fetchCacheKeyPrefix","forceSwcTransforms","fullySpecified","gzipSize","imgOptConcurrency","int","nullable","imgOptOperationCache","imgOptTimeoutInSeconds","imgOptMaxInputPixels","imgOptSequentialRead","isrFlushToDisk","largePageDataBytes","linkNoTouchStart","manualClientBasePath","middlewarePrefetch","proxyPrefetch","middlewareClientMaxBodySize","proxyClientMaxBodySize","multiZoneDraftMode","cssChunking","requestCost","nonnegative","finite","weightDistribution","nextScriptWorkers","optimizeCss","optimisticClientCache","parallelServerCompiles","parallelServerBuildTraces","ppr","readonly","taint","blockingSSR","prerenderEarlyExit","proxyTimeout","rootParams","mcpServer","removeUncaughtErrorAndRejectionListeners","validateRSCRequestHeaders","scrollRestoration","sri","algorithm","swcPlugins","tuple","swcEnvOptions","mode","coreJs","skip","include","exclude","shippedProposals","forceAllTransforms","debug","loose","swcTraceProfiling","urlImports","workerThreads","webVitalsAttribution","mdxRs","development","jsxRuntime","jsxImportSource","providerImportSource","mdxType","transitionIndicator","gestureTransition","typedRoutes","webpackBuildWorker","webpackMemoryOptimizations","turbopackMemoryEviction","turbopackPluginRuntimeStrategy","turbopackMinify","server","client","edge","turbopackFileSystemCacheForDev","turbopackFileSystemCacheForBuild","turbopackSeedCacheFromWorktree","turbopackSourceMaps","turbopackInputSourceMaps","turbopackModuleFragments","turbopackRemoveUnusedImports","turbopackRemoveUnusedExports","turbopackScopeHoisting","turbopackSharedRuntime","turbopackChunking","firstPageLoadPriority","min","max","priorityRoutes","priorityBoost","minChunkSize","maxChunkCountPerGroup","maxMergeChunkSize","minComponentChunkSize","generateComponentChunks","turbopackWorkerAssetPrefix","turbopackClientSideNestedAsyncChunking","turbopackServerSideNestedAsyncChunking","turbopackImportTypeBytes","turbopackUseBuiltinBabel","turbopackUseBuiltinSass","turbopackLocalPostcssConfig","turbopackModuleIds","turbopackInferModuleSideEffects","turbopackCjsTreeShaking","turbopackServerFastRefresh","optimizePackageImports","optimizeServerReact","strictRouteTypes","useTypeScriptCli","clientTraceMetadata","serverMinification","serverSourceMaps","useWasmBinary","useLightningcss","lightningCssFeatures","testProxy","defaultTestRunner","allowDevelopmentBuild","reactDebugChannel","instantInsights","validationLevel","devValidationWorker","staticGenerationRetryCount","staticGenerationMaxConcurrency","staticGenerationMinPagesPerWorker","typedEnv","serverComponentsHmrCache","serverComponentsHmrCancellation","authInterrupts","useCache","durableUseCacheEntries","useCacheTimeout","positive","slowModuleDetection","buildTimeThresholdMs","globalNotFound","turbopackRustReactCompiler","browserDebugInfoInTerminal","level","depthLimit","edgeLimit","showSourceLocation","lockDistDir","hideLogsAfterAbort","runtimeServerDeploymentId","supportsImmutableAssets","deferredEntries","onBeforeDeferredEntries","function","returns","promise","void","reportSystemEnvInlining","configSchema","adapterPath","agentRules","allowedDevOrigins","assetPrefix","bundlePagesRouterDependencies","cacheHandler","cacheMaxMemorySize","cleanDistDir","compiler","emotion","sourceMap","autoLabel","labelFormat","importMap","canonicalImport","styledBaseImport","reactRemoveProperties","properties","relay","src","artifactDirectory","language","eagerEsModules","removeConsole","styledComponents","displayName","topLevelImportPaths","ssr","fileName","meaninglessFileNames","minify","transpileTemplateLiterals","namespace","pure","cssProp","styledJsx","define","defineServer","runAfterProductionCompile","compress","configOrigin","crossOrigin","deploymentId","devIndicators","position","distDir","env","enablePrerenderSourceMaps","excludeDefaultMomentLocales","experimental","exportPathMap","args","dev","dir","outDir","buildId","generateBuildId","null","generateEtags","htmlLimitedBots","httpAgentOptions","keepAlive","i18n","defaultLocale","domains","domain","http","locales","localeDetection","images","localPatterns","pathname","search","remotePatterns","URL","hostname","port","protocol","unoptimized","customCacheHandler","contentSecurityPolicy","contentDispositionType","dangerouslyAllowSVG","dangerouslyAllowLocalIP","deviceSizes","lte","disableStaticImages","formats","imageSizes","loaderFile","maximumDiskCacheSize","maximumRedirects","maximumResponseBody","Number","MAX_SAFE_INTEGER","minimumCacheTTL","qualities","logging","fetches","fullUrl","hmrRefreshes","incomingRequests","ignore","serverFunctions","browserToTerminal","modularizeImports","transform","preventFullImport","skipDefaultConversion","onDemandEntries","maxInactiveAge","pagesBufferLength","output","outputFileTracingRoot","outputFileTracingExcludes","outputFileTracingIncludes","pageExtensions","instrumentationClientInject","partialPrefetching","poweredByHeader","productionBrowserSourceMaps","reactCompiler","compilationMode","panicThreshold","reactProductionProfiling","reactStrictMode","reactMaxHeadersLength","redirects","rewrites","beforeFiles","afterFiles","fallback","sassOptions","implementation","catchall","serverExternalPackages","skipMiddlewareUrlNormalize","skipProxyUrlNormalize","skipTrailingSlashRedirect","staticPageGenerationTimeout","expireTime","target","trailingSlash","transpilePackages","turbopack","typescript","ignoreBuildErrors","tsconfigPath","useFileSystemPublicRoutes","webpack","watchOptions","pollIntervalMs"],"mappings":"AACA,SAASA,aAAa,QAAQ,6BAA4B;AAE1D,SAASC,CAAC,QAAQ,yBAAwB;AAI1C,SACEC,0B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a,EAAEiB,OAAO,GAAGF,QAAQ;QAChDsZ,uBAAuBra,EAAEiB,OAAO,GAAGF,QAAQ;QAC3CuZ,2BAA2Bta,EAAEiB,OAAO,GAAGF,QAAQ;QAC/CwZ,6BAA6Bva,EAAE2C,MAAM,GAAG5B,QAAQ;QAChDyZ,YAAYxa,EAAE2C,MAAM,GAAG5B,QAAQ;QAC/B0Z,QAAQza,EAAEQ,MAAM,GAAGO,QAAQ;QAC3B2Z,eAAe1a,EAAEiB,OAAO,GAAGF,QAAQ;QACnC4Z,mBAAmB3a,EAAEc,KAAK,CAACd,EAAEQ,MAAM,IAAIO,QAAQ;QAC/C6Z,WAAW1W,iBAAiBnD,QAAQ;QACpC8Z,YAAY7a,EACT+C,YAAY,CAAC;YACZ+X,mBAAmB9a,EAAEiB,OAAO,GAAGF,QAAQ;YACvCga,cAAc/a,EAAEQ,MAAM,GAAG+M,GAAG,CAAC,GAAGxM,QAAQ;QAC1C,GACCA,QAAQ;QACXmL,aAAalM,EAAEiB,OAAO,GAAGF,QAAQ;QACjCia,2BAA2Bhb,EAAEiB,OAAO,GAAGF,QAAQ;QAC/C,uDAAuD;QACvDka,SAASjb,EAAEY,GAAG,GAAGyH,QAAQ,GAAGtH,QAAQ;QACpCma,cAAclb,EACX+C,YAAY,CAAC;YACZoY,gBAAgBnb,EAAE2C,MAAM,GAAG2N,QAAQ,GAAGhH,MAAM,GAAGvI,QAAQ;QACzD,GACCA,QAAQ;IACb,IACD","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/config-schema.ts"],"sourcesContent":["import type { NextConfig } from './config'\nimport { VALID_LOADERS } from '../shared/lib/image-config'\n\nimport { z } from 'next/dist/compiled/zod'\nimport type zod from 'next/dist/compiled/zod'\n\nimport type { SizeLimit } from '../types'\nimport {\n LIGHTNINGCSS_FEATURE_NAMES,\n type ExportPathMap,\n type TurbopackLoaderItem,\n type TurbopackOptions,\n type TurbopackRuleConfigItem,\n type TurbopackRuleConfigCollection,\n type TurbopackRuleCondition,\n type TurbopackLoaderBuiltinCondition,\n} from './config-shared'\nimport type {\n Header,\n Rewrite,\n RouteHas,\n Redirect,\n} from '../lib/load-custom-routes'\nimport { SUPPORTED_TEST_RUNNERS_LIST } from '../cli/next-test'\n\n// A custom zod schema for the SizeLimit type\nconst zSizeLimit = z.custom<SizeLimit>((val) => {\n if (typeof val === 'number' || typeof val === 'string') {\n return true\n }\n return false\n})\n\nconst zExportMap: zod.ZodType<ExportPathMap> = z.record(\n z.string(),\n z.object({\n page: z.string(),\n query: z.any(), // NextParsedUrlQuery\n\n // private optional properties\n _fallbackRouteParams: z.array(z.any()).optional(),\n _isAppDir: z.boolean().optional(),\n _isDynamicError: z.boolean().optional(),\n _isRoutePPREnabled: z.boolean().optional(),\n _allowEmptyStaticShell: z.boolean().optional(),\n _isFallbackUpgradeable: z.boolean().optional(),\n })\n)\n\nconst zRouteHas: zod.ZodType<RouteHas> = z.union([\n z.object({\n type: z.enum(['header', 'query', 'cookie']),\n key: z.string(),\n value: z.string().optional(),\n }),\n z.object({\n type: z.literal('host'),\n key: z.undefined().optional(),\n value: z.string(),\n }),\n])\n\nconst zRewrite: zod.ZodType<Rewrite> = z.object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n})\n\nconst zRedirect: zod.ZodType<Redirect> = z\n .object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n })\n .and(\n z.union([\n z.object({\n statusCode: z.never().optional(),\n permanent: z.boolean(),\n }),\n z.object({\n statusCode: z.number(),\n permanent: z.never().optional(),\n }),\n ])\n )\n\nconst zHeader: zod.ZodType<Header> = z.object({\n source: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n headers: z.array(z.object({ key: z.string(), value: z.string() })),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n\n internal: z.boolean().optional(),\n})\n\nconst zTurbopackLoaderItem: zod.ZodType<TurbopackLoaderItem> = z.union([\n z.string(),\n z.strictObject({\n loader: z.string(),\n // Any JSON value can be used as turbo loader options, so use z.any() here\n options: z.record(z.string(), z.any()).optional(),\n }),\n])\n\nconst zTurbopackLoaderBuiltinCondition: zod.ZodType<TurbopackLoaderBuiltinCondition> =\n z.union([\n z.literal('browser'),\n z.literal('foreign'),\n z.literal('development'),\n z.literal('production'),\n z.literal('node'),\n z.literal('edge-light'),\n ])\n\nconst zTurbopackCondition: zod.ZodType<TurbopackRuleCondition> = z.union([\n z.strictObject({ all: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ any: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ not: z.lazy(() => zTurbopackCondition) }),\n zTurbopackLoaderBuiltinCondition,\n z.strictObject({\n path: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n content: z.instanceof(RegExp).optional(),\n query: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n contentType: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n }),\n])\n\nconst zTurbopackModuleType = z.enum([\n 'asset',\n 'ecmascript',\n 'typescript',\n 'css',\n 'css-module',\n 'json',\n 'wasm',\n 'raw',\n 'node',\n 'bytes',\n 'text',\n])\n\nconst zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> =\n z.strictObject({\n loaders: z.array(zTurbopackLoaderItem).optional(),\n as: z.string().optional(),\n condition: zTurbopackCondition.optional(),\n type: zTurbopackModuleType.optional(),\n })\n\nconst zTurbopackRuleConfigCollection: zod.ZodType<TurbopackRuleConfigCollection> =\n z.union([\n zTurbopackRuleConfigItem,\n z.array(z.union([zTurbopackLoaderItem, zTurbopackRuleConfigItem])),\n ])\n\nconst zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({\n rules: z.record(z.string(), zTurbopackRuleConfigCollection).optional(),\n resolveAlias: z\n .record(\n z.string(),\n z.union([\n z.string(),\n z.array(z.string()),\n z.record(z.string(), z.union([z.string(), z.array(z.string())])),\n ])\n )\n .optional(),\n resolveExtensions: z.array(z.string()).optional(),\n root: z.string().optional(),\n debugIds: z.boolean().optional(),\n chunkLoadingGlobal: z.string().optional(),\n ignoreIssue: z\n .array(\n z.object({\n path: z.union([z.string(), z.instanceof(RegExp)]),\n title: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n description: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n })\n )\n .optional(),\n})\n\nexport const experimentalSchema = {\n outputHashSalt: z.string().optional(),\n useSkewCookie: z.boolean().optional(),\n after: z.boolean().optional(),\n appNavFailHandling: z.boolean().optional(),\n coldCacheBadge: z.boolean().optional(),\n preloadEntriesOnStart: z.boolean().optional(),\n allowedRevalidateHeaderKeys: z.array(z.string()).optional(),\n staleTimes: z\n .object({\n dynamic: z.number().optional(),\n static: z.number().gte(30).optional(),\n })\n .optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n clientRouterFilter: z.boolean().optional(),\n clientRouterFilterRedirects: z.boolean().optional(),\n clientRouterFilterAllowedRate: z.number().optional(),\n cpus: z.number().optional(),\n memoryBasedWorkersCount: z.boolean().optional(),\n craCompat: z.boolean().optional(),\n caseSensitiveRoutes: z.boolean().optional(),\n clientParamParsingOrigins: z.array(z.string()).optional(),\n cachedNavigations: z.boolean().optional(),\n dynamicOnHover: z.boolean().optional(),\n useOffline: z.boolean().optional(),\n optimisticRouting: z.boolean().optional(),\n instrumentationClientRouterTransitionEvents: z.boolean().optional(),\n varyParams: z.boolean().optional(),\n prefetchInlining: z\n .union([\n z.boolean(),\n z.object({\n maxSize: z.number().optional(),\n maxBundleSize: z.number().optional(),\n }),\n ])\n .optional(),\n devMemoryThresholdRestart: z.boolean().optional(),\n disableOptimizedLoading: z.boolean().optional(),\n disablePostcssPresetEnv: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n inlineCss: z.boolean().optional(),\n esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),\n serverActions: z\n .object({\n bodySizeLimit: zSizeLimit.optional(),\n allowedOrigins: z.array(z.string()).optional(),\n })\n .optional(),\n maxPostponedStateSize: zSizeLimit.optional(),\n // The original type was Record<string, any>\n extensionAlias: z.record(z.string(), z.any()).optional(),\n externalDir: z.boolean().optional(),\n externalMiddlewareRewritesResolve: z.boolean().optional(),\n externalProxyRewritesResolve: z.boolean().optional(),\n exposeTestingApiInProductionBuild: z.boolean().optional(),\n requestInsights: z.boolean().optional(),\n fallbackNodePolyfills: z.literal(false).optional(),\n fetchCacheKeyPrefix: z.string().optional(),\n forceSwcTransforms: z.boolean().optional(),\n fullySpecified: z.boolean().optional(),\n gzipSize: z.boolean().optional(),\n imgOptConcurrency: z.number().int().optional().nullable(),\n imgOptOperationCache: z.boolean().optional().nullable(),\n imgOptTimeoutInSeconds: z.number().int().optional(),\n imgOptMaxInputPixels: z.number().int().optional(),\n imgOptSequentialRead: z.boolean().optional().nullable(),\n isrFlushToDisk: z.boolean().optional(),\n largePageDataBytes: z.number().optional(),\n linkNoTouchStart: z.boolean().optional(),\n manualClientBasePath: z.boolean().optional(),\n middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),\n proxyPrefetch: z.enum(['strict', 'flexible']).optional(),\n middlewareClientMaxBodySize: zSizeLimit.optional(),\n proxyClientMaxBodySize: zSizeLimit.optional(),\n multiZoneDraftMode: z.boolean().optional(),\n cssChunking: z\n .union([\n z.boolean(),\n z.literal('strict'),\n z.literal('loose'),\n z.literal('graph'),\n z.strictObject({ type: z.literal('strict') }),\n z.strictObject({ type: z.literal('loose') }),\n z.strictObject({\n type: z.literal('graph'),\n requestCost: z.number().nonnegative().finite().optional(),\n weightDistribution: z.number().nonnegative().finite().optional(),\n }),\n ])\n .optional(),\n nextScriptWorkers: z.boolean().optional(),\n // The critter option is unknown, use z.any() here\n optimizeCss: z.union([z.boolean(), z.any()]).optional(),\n optimisticClientCache: z.boolean().optional(),\n parallelServerCompiles: z.boolean().optional(),\n parallelServerBuildTraces: z.boolean().optional(),\n ppr: z\n .union([z.boolean(), z.literal('incremental')])\n .readonly()\n .optional(),\n taint: z.boolean().optional(),\n blockingSSR: z.boolean().optional(),\n prerenderEarlyExit: z.boolean().optional(),\n proxyTimeout: z.number().gte(0).optional(),\n rootParams: z.boolean().optional(),\n mcpServer: z.boolean().optional(),\n removeUncaughtErrorAndRejectionListeners: z.boolean().optional(),\n validateRSCRequestHeaders: z.boolean().optional(),\n scrollRestoration: z.boolean().optional(),\n sri: z\n .object({\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).optional(),\n })\n .optional(),\n swcPlugins: z\n // The specific swc plugin's option is unknown, use z.any() here\n .array(z.tuple([z.string(), z.record(z.string(), z.any())]))\n .optional(),\n swcEnvOptions: z\n .object({\n mode: z.enum(['usage', 'entry']).optional(),\n coreJs: z.string().optional(),\n skip: z.array(z.string()).optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n shippedProposals: z.boolean().optional(),\n forceAllTransforms: z.boolean().optional(),\n debug: z.boolean().optional(),\n loose: z.boolean().optional(),\n })\n .optional(),\n swcTraceProfiling: z.boolean().optional(),\n // NonNullable<webpack.Configuration['experiments']>['buildHttp']\n urlImports: z.any().optional(),\n workerThreads: z.boolean().optional(),\n webVitalsAttribution: z\n .array(\n z.union([\n z.literal('CLS'),\n z.literal('FCP'),\n z.literal('FID'),\n z.literal('INP'),\n z.literal('LCP'),\n z.literal('TTFB'),\n ])\n )\n .optional(),\n // This is partial set of mdx-rs transform options we support, aligned\n // with next_core::next_config::MdxRsOptions. Ensure both types are kept in sync.\n mdxRs: z\n .union([\n z.boolean(),\n z.object({\n development: z.boolean().optional(),\n jsxRuntime: z.string().optional(),\n jsxImportSource: z.string().optional(),\n providerImportSource: z.string().optional(),\n mdxType: z.enum(['gfm', 'commonmark']).optional(),\n }),\n ])\n .optional(),\n transitionIndicator: z.boolean().optional(),\n gestureTransition: z.boolean().optional(),\n typedRoutes: z.boolean().optional(),\n webpackBuildWorker: z.boolean().optional(),\n webpackMemoryOptimizations: z.boolean().optional(),\n turbopackMemoryEviction: z\n .union([z.literal(false), z.literal('full'), z.literal('auto')])\n .optional(),\n turbopackPluginRuntimeStrategy: z\n .enum(['workerThreads', 'childProcesses'])\n .optional(),\n turbopackMinify: z\n .union([\n z.boolean(),\n z.strictObject({\n server: z.boolean().optional(),\n client: z.boolean().optional(),\n edge: z.boolean().optional(),\n }),\n ])\n .optional(),\n turbopackFileSystemCacheForDev: z.boolean().optional(),\n turbopackFileSystemCacheForBuild: z.boolean().optional(),\n turbopackSeedCacheFromWorktree: z.boolean().optional(),\n turbopackSourceMaps: z.boolean().optional(),\n turbopackInputSourceMaps: z.boolean().optional(),\n turbopackModuleFragments: z.boolean().optional(),\n turbopackRemoveUnusedImports: z.boolean().optional(),\n turbopackRemoveUnusedExports: z.boolean().optional(),\n turbopackScopeHoisting: z.boolean().optional(),\n turbopackSharedRuntime: z.boolean().optional(),\n turbopackChunking: z\n .object({\n firstPageLoadPriority: z.number().min(0).max(1).optional(),\n priorityRoutes: z.array(z.instanceof(RegExp)).optional(),\n priorityBoost: z.number().min(1).optional(),\n requestCost: z.number().min(0).finite().optional(),\n minChunkSize: z.number().min(0).optional(),\n maxChunkCountPerGroup: z.number().min(0).optional(),\n maxMergeChunkSize: z.number().min(0).optional(),\n minComponentChunkSize: z.number().min(0).optional(),\n generateComponentChunks: z.boolean().optional(),\n })\n .optional(),\n turbopackWorkerAssetPrefix: z.string().optional(),\n turbopackClientSideNestedAsyncChunking: z.boolean().optional(),\n turbopackServerSideNestedAsyncChunking: z.boolean().optional(),\n turbopackImportTypeBytes: z.boolean().optional(),\n turbopackUseBuiltinBabel: z.boolean().optional(),\n turbopackUseBuiltinSass: z.boolean().optional(),\n turbopackLocalPostcssConfig: z.boolean().optional(),\n turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),\n turbopackInferModuleSideEffects: z.boolean().optional(),\n turbopackCjsTreeShaking: z.boolean().optional(),\n turbopackCjsScopeHoisting: z.boolean().optional(),\n turbopackServerFastRefresh: z.boolean().optional(),\n optimizePackageImports: z.array(z.string()).optional(),\n optimizeServerReact: z.boolean().optional(),\n strictRouteTypes: z.boolean().optional(),\n useTypeScriptCli: z.boolean().optional(),\n clientTraceMetadata: z.array(z.string()).optional(),\n serverMinification: z.boolean().optional(),\n serverSourceMaps: z.boolean().optional(),\n useWasmBinary: z.boolean().optional(),\n useLightningcss: z.boolean().optional(),\n lightningCssFeatures: z\n .object({\n include: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n exclude: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n })\n .optional(),\n testProxy: z.boolean().optional(),\n defaultTestRunner: z.enum(SUPPORTED_TEST_RUNNERS_LIST).optional(),\n allowDevelopmentBuild: z.literal(true).optional(),\n\n reactDebugChannel: z.boolean().optional(),\n instantInsights: z\n .object({\n validationLevel: z\n .enum([\n 'warning',\n 'manual-warning',\n 'experimental-error',\n 'experimental-manual-error',\n ])\n .optional(),\n })\n .optional(),\n devValidationWorker: z.boolean().optional(),\n staticGenerationRetryCount: z.number().int().optional(),\n staticGenerationMaxConcurrency: z.number().int().optional(),\n staticGenerationMinPagesPerWorker: z.number().int().optional(),\n typedEnv: z.boolean().optional(),\n serverComponentsHmrCache: z.boolean().optional(),\n serverComponentsHmrCancellation: z.boolean().optional(),\n authInterrupts: z.boolean().optional(),\n useCache: z.boolean().optional(),\n durableUseCacheEntries: z.boolean().optional(),\n useCacheTimeout: z.number().positive().optional(),\n slowModuleDetection: z\n .object({\n buildTimeThresholdMs: z.number().int(),\n })\n .optional(),\n globalNotFound: z.boolean().optional(),\n turbopackRustReactCompiler: z.boolean().optional(),\n browserDebugInfoInTerminal: z\n .union([\n z.boolean(),\n z.enum(['error', 'warn', 'verbose']),\n z.object({\n level: z.enum(['error', 'warn', 'verbose']).optional(),\n depthLimit: z.number().int().positive().optional(),\n edgeLimit: z.number().int().positive().optional(),\n showSourceLocation: z.boolean().optional(),\n }),\n ])\n .optional(),\n lockDistDir: z.boolean().optional(),\n hideLogsAfterAbort: z.boolean().optional(),\n runtimeServerDeploymentId: z.boolean().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n deferredEntries: z.array(z.string()).optional(),\n onBeforeDeferredEntries: z.function().returns(z.promise(z.void())).optional(),\n reportSystemEnvInlining: z.enum(['warn', 'error']).optional(),\n}\n\nexport const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>\n z.strictObject({\n adapterPath: z.string().optional(),\n agentRules: z.boolean().optional(),\n allowedDevOrigins: z.array(z.string()).optional(),\n assetPrefix: z.string().optional(),\n basePath: z.string().optional(),\n bundlePagesRouterDependencies: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n cacheHandler: z.string().min(1).optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheMaxMemorySize: z.number().optional(),\n cleanDistDir: z.boolean().optional(),\n compiler: z\n .strictObject({\n emotion: z\n .union([\n z.boolean(),\n z.object({\n sourceMap: z.boolean().optional(),\n autoLabel: z\n .union([\n z.literal('always'),\n z.literal('dev-only'),\n z.literal('never'),\n ])\n .optional(),\n labelFormat: z.string().min(1).optional(),\n importMap: z\n .record(\n z.string(),\n z.record(\n z.string(),\n z.object({\n canonicalImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n styledBaseImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n })\n )\n )\n .optional(),\n }),\n ])\n .optional(),\n reactRemoveProperties: z\n .union([\n z.boolean().optional(),\n z.object({\n properties: z.array(z.string()).optional(),\n }),\n ])\n .optional(),\n relay: z\n .object({\n src: z.string(),\n artifactDirectory: z.string().optional(),\n language: z.enum(['javascript', 'typescript', 'flow']).optional(),\n eagerEsModules: z.boolean().optional(),\n })\n .optional(),\n removeConsole: z\n .union([\n z.boolean().optional(),\n z.object({\n exclude: z.array(z.string()).min(1).optional(),\n }),\n ])\n .optional(),\n styledComponents: z.union([\n z.boolean().optional(),\n z.object({\n displayName: z.boolean().optional(),\n topLevelImportPaths: z.array(z.string()).optional(),\n ssr: z.boolean().optional(),\n fileName: z.boolean().optional(),\n meaninglessFileNames: z.array(z.string()).optional(),\n minify: z.boolean().optional(),\n transpileTemplateLiterals: z.boolean().optional(),\n namespace: z.string().min(1).optional(),\n pure: z.boolean().optional(),\n cssProp: z.boolean().optional(),\n }),\n ]),\n styledJsx: z.union([\n z.boolean().optional(),\n z.object({\n useLightningcss: z.boolean().optional(),\n }),\n ]),\n define: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n defineServer: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n runAfterProductionCompile: z\n .function()\n .returns(z.promise(z.void()))\n .optional(),\n })\n .optional(),\n compress: z.boolean().optional(),\n configOrigin: z.string().optional(),\n crossOrigin: z\n .union([z.literal('anonymous'), z.literal('use-credentials')])\n .optional(),\n deploymentId: z.string().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n outputHashSalt: z.string().optional(),\n devIndicators: z\n .union([\n z.object({\n position: z\n .union([\n z.literal('bottom-left'),\n z.literal('bottom-right'),\n z.literal('top-left'),\n z.literal('top-right'),\n ])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n distDir: z.string().min(1).optional(),\n env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(),\n enablePrerenderSourceMaps: z.boolean().optional(),\n excludeDefaultMomentLocales: z.boolean().optional(),\n experimental: z.strictObject(experimentalSchema).optional(),\n exportPathMap: z\n .function()\n .args(\n zExportMap,\n z.object({\n dev: z.boolean(),\n dir: z.string(),\n outDir: z.string().nullable(),\n distDir: z.string(),\n buildId: z.string(),\n })\n )\n .returns(z.union([zExportMap, z.promise(zExportMap)]))\n .optional(),\n generateBuildId: z\n .function()\n .args()\n .returns(\n z.union([\n z.string(),\n z.null(),\n z.promise(z.union([z.string(), z.null()])),\n ])\n )\n .optional(),\n generateEtags: z.boolean().optional(),\n headers: z\n .function()\n .args()\n .returns(z.promise(z.array(zHeader)))\n .optional(),\n htmlLimitedBots: z.instanceof(RegExp).optional(),\n httpAgentOptions: z\n .strictObject({ keepAlive: z.boolean().optional() })\n .optional(),\n i18n: z\n .strictObject({\n defaultLocale: z.string().min(1),\n domains: z\n .array(\n z.strictObject({\n defaultLocale: z.string().min(1),\n domain: z.string().min(1),\n http: z.literal(true).optional(),\n locales: z.array(z.string().min(1)).optional(),\n })\n )\n .optional(),\n localeDetection: z.literal(false).optional(),\n locales: z.array(z.string().min(1)),\n })\n .nullable()\n .optional(),\n images: z\n .strictObject({\n localPatterns: z\n .array(\n z.strictObject({\n pathname: z.string().optional(),\n search: z.string().optional(),\n })\n )\n .max(25)\n .optional(),\n remotePatterns: z\n .array(\n z.union([\n z.instanceof(URL),\n z.strictObject({\n hostname: z.string(),\n pathname: z.string().optional(),\n port: z.string().max(5).optional(),\n protocol: z.enum(['http', 'https']).optional(),\n search: z.string().optional(),\n }),\n ])\n )\n .max(50)\n .optional(),\n unoptimized: z.boolean().optional(),\n customCacheHandler: z.boolean().optional(),\n contentSecurityPolicy: z.string().optional(),\n contentDispositionType: z.enum(['inline', 'attachment']).optional(),\n dangerouslyAllowSVG: z.boolean().optional(),\n dangerouslyAllowLocalIP: z.boolean().optional(),\n deviceSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .max(25)\n .optional(),\n disableStaticImages: z.boolean().optional(),\n domains: z.array(z.string()).max(50).optional(),\n formats: z\n .array(z.enum(['image/avif', 'image/webp']))\n .max(4)\n .optional(),\n imageSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .min(0)\n .max(25)\n .optional(),\n loader: z.enum(VALID_LOADERS).optional(),\n loaderFile: z.string().optional(),\n maximumDiskCacheSize: z.number().int().min(0).optional(),\n maximumRedirects: z.number().int().min(0).max(20).optional(),\n maximumResponseBody: z\n .number()\n .int()\n .min(1)\n .max(Number.MAX_SAFE_INTEGER)\n .optional(),\n minimumCacheTTL: z.number().int().gte(0).optional(),\n path: z.string().optional(),\n qualities: z\n .array(z.number().int().gte(1).lte(100))\n .min(1)\n .max(20)\n .optional(),\n })\n .optional(),\n logging: z\n .union([\n z.object({\n fetches: z\n .object({\n fullUrl: z.boolean().optional(),\n hmrRefreshes: z.boolean().optional(),\n })\n .optional(),\n incomingRequests: z\n .union([\n z.boolean(),\n z.object({\n ignore: z.array(z.instanceof(RegExp)),\n }),\n ])\n .optional(),\n serverFunctions: z.boolean().optional(),\n browserToTerminal: z\n .union([z.boolean(), z.enum(['error', 'warn'])])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n modularizeImports: z\n .record(\n z.string(),\n z.object({\n transform: z.union([z.string(), z.record(z.string(), z.string())]),\n preventFullImport: z.boolean().optional(),\n skipDefaultConversion: z.boolean().optional(),\n })\n )\n .optional(),\n onDemandEntries: z\n .strictObject({\n maxInactiveAge: z.number().optional(),\n pagesBufferLength: z.number().optional(),\n })\n .optional(),\n output: z.enum(['standalone', 'export']).optional(),\n outputFileTracingRoot: z.string().optional(),\n outputFileTracingExcludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n outputFileTracingIncludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n pageExtensions: z.array(z.string()).min(1).optional(),\n instrumentationClientInject: z.array(z.string()).optional(),\n partialPrefetching: z\n .union([z.boolean(), z.literal('unstable_eager')])\n .optional(),\n poweredByHeader: z.boolean().optional(),\n productionBrowserSourceMaps: z.boolean().optional(),\n reactCompiler: z.union([\n z.boolean(),\n z\n .object({\n compilationMode: z.enum(['infer', 'annotation', 'all']).optional(),\n panicThreshold: z\n .enum(['none', 'critical_errors', 'all_errors'])\n .optional(),\n })\n .optional(),\n ]),\n reactProductionProfiling: z.boolean().optional(),\n reactStrictMode: z.boolean().nullable().optional(),\n reactMaxHeadersLength: z.number().nonnegative().int().optional(),\n redirects: z\n .function()\n .args()\n .returns(z.promise(z.array(zRedirect)))\n .optional(),\n rewrites: z\n .function()\n .args()\n .returns(\n z.promise(\n z.union([\n z.array(zRewrite),\n z.object({\n beforeFiles: z.array(zRewrite),\n afterFiles: z.array(zRewrite),\n fallback: z.array(zRewrite),\n }),\n ])\n )\n )\n .optional(),\n // sassOptions properties are unknown besides implementation, use z.any() here\n sassOptions: z\n .object({\n implementation: z.string().optional(),\n })\n .catchall(z.any())\n .optional(),\n serverExternalPackages: z.array(z.string()).optional(),\n skipMiddlewareUrlNormalize: z.boolean().optional(),\n skipProxyUrlNormalize: z.boolean().optional(),\n skipTrailingSlashRedirect: z.boolean().optional(),\n staticPageGenerationTimeout: z.number().optional(),\n expireTime: z.number().optional(),\n target: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n transpilePackages: z.array(z.string()).optional(),\n turbopack: zTurbopackConfig.optional(),\n typescript: z\n .strictObject({\n ignoreBuildErrors: z.boolean().optional(),\n tsconfigPath: z.string().min(1).optional(),\n })\n .optional(),\n typedRoutes: z.boolean().optional(),\n useFileSystemPublicRoutes: z.boolean().optional(),\n // The webpack config type is unknown, use z.any() here\n webpack: z.any().nullable().optional(),\n watchOptions: z\n .strictObject({\n pollIntervalMs: z.number().positive().finite().optional(),\n })\n .optional(),\n })\n)\n"],"names":["VALID_LOADERS","z","LIGHTNINGCSS_FEATURE_NAMES","SUPPORTED_TEST_RUNNERS_LIST","zSizeLimit","custom","val","zExportMap","record","string","object","page","query","any","_fallbackRouteParams","array","optional","_isAppDir","boolean","_isDynamicError","_isRoutePPREnabled","_allowEmptyStaticShell","_isFallbackUpgradeable","zRouteHas","union","type","enum","key","value","literal","undefined","zRewrite","source","destination","basePath","locale","has","missing","internal","zRedirect","and","statusCode","never","permanent","number","zHeader","headers","zTurbopackLoaderItem","strictObject","loader","options","zTurbopackLoaderBuiltinCondition","zTurbopackCondition","all","lazy","not","path","instanceof","RegExp","content","contentType","zTurbopackModuleType","zTurbopackRuleConfigItem","loaders","as","condition","zTurbopackRuleConfigCollection","zTurbopackConfig","rules","resolveAlias","resolveExtensions","root","debugIds","chunkLoadingGlobal","ignoreIssue","title","description","experimentalSchema","outputHashSalt","useSkewCookie","after","appNavFailHandling","coldCacheBadge","preloadEntriesOnStart","allowedRevalidateHeaderKeys","staleTimes","dynamic","static","gte","cacheLife","stale","revalidate","expire","cacheHandlers","clientRouterFilter","clientRouterFilterRedirects","clientRouterFilterAllowedRate","cpus","memoryBasedWorkersCount","craCompat","caseSensitiveRoutes","clientParamParsingOrigins","cachedNavigations","dynamicOnHover","useOffline","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","prefetchInlining","maxSize","maxBundleSize","devMemoryThresholdRestart","disableOptimizedLoading","disablePostcssPresetEnv","cacheComponents","inlineCss","esmExternals","serverActions","bodySizeLimit","allowedOrigins","maxPostponedStateSize","extensionAlias","externalDir","externalMiddlewareRewritesResolve","externalProxyRewritesResolve","exposeTestingApiInProductionBuild","requestInsights","fallbackNodePolyfills","fetchCacheKeyPrefix","forceSwcTransforms","fullySpecified","gzipSize","imgOptConcurrency","int","nullable","imgOptOperationCache","imgOptTimeoutInSeconds","imgOptMaxInputPixels","imgOptSequentialRead","isrFlushToDisk","largePageDataBytes","linkNoTouchStart","manualClientBasePath","middlewarePrefetch","proxyPrefetch","middlewareClientMaxBodySize","proxyClientMaxBodySize","multiZoneDraftMode","cssChunking","requestCost","nonnegative","finite","weightDistribution","nextScriptWorkers","optimizeCss","optimisticClientCache","parallelServerCompiles","parallelServerBuildTraces","ppr","readonly","taint","blockingSSR","prerenderEarlyExit","proxyTimeout","rootParams","mcpServer","removeUncaughtErrorAndRejectionListeners","validateRSCRequestHeaders","scrollRestoration","sri","algorithm","swcPlugins","tuple","swcEnvOptions","mode","coreJs","skip","include","exclude","shippedProposals","forceAllTransforms","debug","loose","swcTraceProfiling","urlImports","workerThreads","webVitalsAttribution","mdxRs","development","jsxRuntime","jsxImportSource","providerImportSource","mdxType","transitionIndicator","gestureTransition","typedRoutes","webpackBuildWorker","webpackMemoryOptimizations","turbopackMemoryEviction","turbopackPluginRuntimeStrategy","turbopackMinify","server","client","edge","turbopackFileSystemCacheForDev","turbopackFileSystemCacheForBuild","turbopackSeedCacheFromWorktree","turbopackSourceMaps","turbopackInputSourceMaps","turbopackModuleFragments","turbopackRemoveUnusedImports","turbopackRemoveUnusedExports","turbopackScopeHoisting","turbopackSharedRuntime","turbopackChunking","firstPageLoadPriority","min","max","priorityRoutes","priorityBoost","minChunkSize","maxChunkCountPerGroup","maxMergeChunkSize","minComponentChunkSize","generateComponentChunks","turbopackWorkerAssetPrefix","turbopackClientSideNestedAsyncChunking","turbopackServerSideNestedAsyncChunking","turbopackImportTypeBytes","turbopackUseBuiltinBabel","turbopackUseBuiltinSass","turbopackLocalPostcssConfig","turbopackModuleIds","turbopackInferModuleSideEffects","turbopackCjsTreeShaking","turbopackCjsScopeHoisting","turbopackServerFastRefresh","optimizePackageImports","optimizeServerReact","strictRouteTypes","useTypeScriptCli","clientTraceMetadata","serverMinification","serverSourceMaps","useWasmBinary","useLightningcss","lightningCssFeatures","testProxy","defaultTestRunner","allowDevelopmentBuild","reactDebugChannel","instantInsights","validationLevel","devValidationWorker","staticGenerationRetryCount","staticGenerationMaxConcurrency","staticGenerationMinPagesPerWorker","typedEnv","serverComponentsHmrCache","serverComponentsHmrCancellation","authInterrupts","useCache","durableUseCacheEntries","useCacheTimeout","positive","slowModuleDetection","buildTimeThresholdMs","globalNotFound","turbopackRustReactCompiler","browserDebugInfoInTerminal","level","depthLimit","edgeLimit","showSourceLocation","lockDistDir","hideLogsAfterAbort","runtimeServerDeploymentId","supportsImmutableAssets","deferredEntries","onBeforeDeferredEntries","function","returns","promise","void","reportSystemEnvInlining","configSchema","adapterPath","agentRules","allowedDevOrigins","assetPrefix","bundlePagesRouterDependencies","cacheHandler","cacheMaxMemorySize","cleanDistDir","compiler","emotion","sourceMap","autoLabel","labelFormat","importMap","canonicalImport","styledBaseImport","reactRemoveProperties","properties","relay","src","artifactDirectory","language","eagerEsModules","removeConsole","styledComponents","displayName","topLevelImportPaths","ssr","fileName","meaninglessFileNames","minify","transpileTemplateLiterals","namespace","pure","cssProp","styledJsx","define","defineServer","runAfterProductionCompile","compress","configOrigin","crossOrigin","deploymentId","devIndicators","position","distDir","env","enablePrerenderSourceMaps","excludeDefaultMomentLocales","experimental","exportPathMap","args","dev","dir","outDir","buildId","generateBuildId","null","generateEtags","htmlLimitedBots","httpAgentOptions","keepAlive","i18n","defaultLocale","domains","domain","http","locales","localeDetection","images","localPatterns","pathname","search","remotePatterns","URL","hostname","port","protocol","unoptimized","customCacheHandler","contentSecurityPolicy","contentDispositionType","dangerouslyAllowSVG","dangerouslyAllowLocalIP","deviceSizes","lte","disableStaticImages","formats","imageSizes","loaderFile","maximumDiskCacheSize","maximumRedirects","maximumResponseBody","Number","MAX_SAFE_INTEGER","minimumCacheTTL","qualities","logging","fetches","fullUrl","hmrRefreshes","incomingRequests","ignore","serverFunctions","browserToTerminal","modularizeImports","transform","preventFullImport","skipDefaultConversion","onDemandEntries","maxInactiveAge","pagesBufferLength","output","outputFileTracingRoot","outputFileTracingExcludes","outputFileTracingIncludes","pageExtensions","instrumentationClientInject","partialPrefetching","poweredByHeader","productionBrowserSourceMaps","reactCompiler","compilationMode","panicThreshold","reactProductionProfiling","reactStrictMode","reactMaxHeadersLength","redirects","rewrites","beforeFiles","afterFiles","fallback","sassOptions","implementation","catchall","serverExternalPackages","skipMiddlewareUrlNormalize","skipProxyUrlNormalize","skipTrailingSlashRedirect","staticPageGenerationTimeout","expireTime","target","trailingSlash","transpilePackages","turbopack","typescript","ignoreBuildErrors","tsconfigPath","useFileSystemPublicRo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'../request-meta';

config: {
pprConfig: this.nextConfig.experimental.ppr,
configFileName,

@@ -529,0 +528,0 @@ cacheComponents: Boolean(this.nextConfig.cacheComponents)

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = createPromiseWithResolvers<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value, cacheKey) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return (\n cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)\n )\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value, cacheKey) {\n return cacheKey.length + JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n // The router server or the render server may run in the same process and\n // have already registered the unhandled rejection listener, in which case\n // we must not register another one, to avoid logging unhandled rejections\n // multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["addRequestMeta","getRequestMeta","React","fs","Worker","installUseCacheProbe","installDevValidationWorker","join","pathJoin","PUBLIC_DIR_MIDDLEWARE_CONFLICT","findPagesDir","PHASE_DEVELOPMENT_SERVER","PAGES_MANIFEST","APP_PATHS_MANIFEST","COMPILER_NAMES","PRERENDER_MANIFEST","Server","WrappedBuildError","normalizePagePath","pathHasPrefix","removePathPrefix","Telemetry","hrtimeToEpochNanoseconds","setGlobal","trace","traceGlobals","findPageFile","getFormattedNodeOptionsWithoutInspect","withCoalescedInvoke","loadDefaultErrorComponents","DecodeError","MiddlewareNotFoundError","Log","isError","getProperError","defaultConfig","isMiddlewareFile","formatServerError","DevRouteMatcherManager","DevPagesRouteMatcherProvider","DevPagesAPIRouteMatcherProvider","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","NodeManifestLoader","BatchedFileReader","DefaultFileReader","LRUCache","getMiddlewareRouteMatcher","createPromiseWithResolvers","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","generateInterceptionRoutesRewrites","buildCustomRoute","decorateServerError","logRequests","FallbackMode","fallbackModeToFallbackField","ensureInstrumentationRegistered","getInstrumentationModule","getRouteRegex","HMR_MESSAGE_SENT_TO_BROWSER","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","createElement","DevServer","getStaticPathsWorker","worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","conf","bundlerService","startServerSpan","renderOpts","ErrorDebug","staticPathsCache","length","value","cacheKey","JSON","stringify","staticPaths","pagesDir","appDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","extensions","pageExtensions","extensionsExpression","RegExp","fileReader","pathnameFilter","test","push","localeNormalizer","ignorePartFilter","part","startsWith","isTurbopack","getBuildId","prepareImpl","existingTelemetry","get","telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","err","logErrorWithOriginalStack","hasPage","normalizedPath","console","error","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","requestStart","hrtime","bigint","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","devRequestTimingInternalsEnd","manualTraceChild","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","existsSync","publicDir","sent","__NEXT_PAGE","internalErr","body","send","type","getPagesManifest","serverDistDir","getAppPathsManifest","enabledDirectories","app","rewrites","Object","keys","appPathRoutes","map","route","regex","output","exit","getMiddleware","middleware","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","message","runInstrumentationHookIfAvailable","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":"AAWA,SACEA,cAAc,EACdC,cAAc,QAGT,kBAAiB;AAQxB,YAAYC,WAAW,QAAO;AAC9B,OAAOC,QAAQ,KAAI;AACnB,SAASC,MAAM,QAAQ,iCAAgC;AACvD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,0BAA0B,QAAQ,+BAA8B;AACzE,SAASC,QAAQC,QAAQ,QAAQ,OAAM;AACvC,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SACEC,wBAAwB,EACxBC,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,QACb,6BAA4B;AACnC,OAAOC,UAAUC,iBAAiB,QAAQ,iBAAgB;AAC1D,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,0BAAyB;AACnD,SAEEC,wBAAwB,EACxBC,SAAS,EACTC,KAAK,QACA,cAAa;AACpB,SAASC,YAAY,QAAQ,qBAAoB;AACjD,SAASC,YAAY,QAAQ,wBAAuB;AACpD,SAASC,qCAAqC,QAAQ,eAAc;AACpE,SAASC,mBAAmB,QAAQ,+BAA8B;AAClE,SACEC,0BAA0B,QAErB,mCAAkC;AACzC,SAASC,WAAW,EAAEC,uBAAuB,QAAQ,yBAAwB;AAC7E,YAAYC,SAAS,yBAAwB;AAC7C,OAAOC,WAAWC,cAAc,QAAQ,qBAAoB;AAC5D,SAASC,aAAa,QAAiC,mBAAkB;AACzE,SAASC,gBAAgB,QAAQ,oBAAmB;AACpD,SAASC,iBAAiB,QAAQ,gCAA+B;AACjE,SAASC,sBAAsB,QAAQ,sDAAqD;AAC5F,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,+BAA+B,QAAQ,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EAWJ,EAAwC;YACjC;QAAN,QAAM,cAAA,IAAI,CAACrC,KAAK,qBAAV,YAAY8G,OAAO;QAEzB,MAAM6H,iBAAiB,MAAM,IAAI,CAACC,mBAAmB,CAACzM;QACtD,IAAIwM,gBAAgB;YAClB,wDAAwD;YACxD,MAAM,IAAIvT,kBAAkBuT;QAC9B;QACA,IAAID,gBAAgB,IAAI,CAACG,aAAa,CAACC,YAAY,EAAE;YACnD,MAAM,IAAI,CAAC7M,UAAU,CAAC;gBACpBE;gBACAwH;gBACAvH,YAAY;gBACZF,YAAY9D;gBACZiE;YACF;QACF;QAEA,IAAI,CAAC0M,gBAAgB,GAAG,KAAK,CAAC9F;QAE9B,OAAO,MAAM,KAAK,CAACsF,mBAAmB;YACpCpM;YACAsM;YACAjK;YACAgK;YACAvE;YACAyE;YACArM;QACF;IACF;IAEA,MAAgB2M,2BACd3M,GAAY,EAC2C;QACvD,MAAM,IAAI,CAACnC,cAAc,CAAC8O,0BAA0B,CAAC3M;QACrD,OAAO,MAAMrG,2BAA2B,IAAI,CAACqF,OAAO;IACtD;IAEA,MAAMuN,oBAAoBzM,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACjC,cAAc,CAAC0O,mBAAmB,CAACzM;IACvD;IAEA,MAAgB8M,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACrL,SAASsL,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACrL,yBAAyB,CAACD,KAAK;QACtC;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = createPromiseWithResolvers<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value, cacheKey) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return (\n cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)\n )\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value, cacheKey) {\n return cacheKey.length + JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n // The router server or the render server may run in the same process and\n // have already registered the unhandled rejection listener, in which case\n // we must not register another one, to avoid logging unhandled rejections\n // multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["addRequestMeta","getRequestMeta","React","fs","Worker","installUseCacheProbe","installDevValidationWorker","join","pathJoin","PUBLIC_DIR_MIDDLEWARE_CONFLICT","findPagesDir","PHASE_DEVELOPMENT_SERVER","PAGES_MANIFEST","APP_PATHS_MANIFEST","COMPILER_NAMES","PRERENDER_MANIFEST","Server","WrappedBuildError","normalizePagePath","pathHasPrefix","removePathPrefix","Telemetry","hrtimeToEpochNanoseconds","setGlobal","trace","traceGlobals","findPageFile","getFormattedNodeOptionsWithoutInspect","withCoalescedInvoke","loadDefaultErrorComponents","DecodeError","MiddlewareNotFoundError","Log","isError","getProperError","defaultConfig","isMiddlewareFile","formatServerError","DevRouteMatcherManager","DevPagesRouteMatcherProvider","DevPagesAPIRouteMatcherProvider","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","NodeManifestLoader","BatchedFileReader","DefaultFileReader","LRUCache","getMiddlewareRouteMatcher","createPromiseWithResolvers","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","generateInterceptionRoutesRewrites","buildCustomRoute","decorateServerError","logRequests","FallbackMode","fallbackModeToFallbackField","ensureInstrumentationRegistered","getInstrumentationModule","getRouteRegex","HMR_MESSAGE_SENT_TO_BROWSER","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","createElement","DevServer","getStaticPathsWorker","worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","conf","bundlerService","startServerSpan","renderOpts","ErrorDebug","staticPathsCache","length","value","cacheKey","JSON","stringify","staticPaths","pagesDir","appDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","extensions","pageExtensions","extensionsExpression","RegExp","fileReader","pathnameFilter","test","push","localeNormalizer","ignorePartFilter","part","startsWith","isTurbopack","getBuildId","prepareImpl","existingTelemetry","get","telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","err","logErrorWithOriginalStack","hasPage","normalizedPath","console","error","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","requestStart","hrtime","bigint","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","devRequestTimingInternalsEnd","manualTraceChild","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","existsSync","publicDir","sent","__NEXT_PAGE","internalErr","body","send","type","getPagesManifest","serverDistDir","getAppPathsManifest","enabledDirectories","app","rewrites","Object","keys","appPathRoutes","map","route","regex","output","exit","getMiddleware","middleware","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","message","runInstrumentationHookIfAvailable","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":"AAWA,SACEA,cAAc,EACdC,cAAc,QAGT,kBAAiB;AAQxB,YAAYC,WAAW,QAAO;AAC9B,OAAOC,QAAQ,KAAI;AACnB,SAASC,MAAM,QAAQ,iCAAgC;AACvD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,0BAA0B,QAAQ,+BAA8B;AACzE,SAASC,QAAQC,QAAQ,QAAQ,OAAM;AACvC,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SACEC,wB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YACAoM;YACA/J;YACA8J;YACArE;YACAuE;YACAnM;QACF;IACF;IAEA,MAAgByM,2BACdzM,GAAY,EAC2C;QACvD,MAAM,IAAI,CAACnC,cAAc,CAAC4O,0BAA0B,CAACzM;QACrD,OAAO,MAAMrG,2BAA2B,IAAI,CAACqF,OAAO;IACtD;IAEA,MAAMqN,oBAAoBvM,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACjC,cAAc,CAACwO,mBAAmB,CAACvM;IACvD;IAEA,MAAgB4M,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACnL,SAASoL,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACnL,yBAAyB,CAACD,KAAK;QACtC;IACF;AACF","ignoreList":[0]}

@@ -7,3 +7,2 @@ import '../require-hook';

import { isAppPageRouteModule } from '../route-modules/checks';
import { checkIsRoutePPREnabled } from '../lib/experimental/ppr';
import { InvariantError } from '../../shared/lib/invariant-error';

@@ -57,3 +56,3 @@ import { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys';

}
const isRoutePPREnabled = isAppPageRouteModule(routeModule) && checkIsRoutePPREnabled(config.pprConfig);
const isRoutePPREnabled = isAppPageRouteModule(routeModule) && config.cacheComponents;
const rootParamKeys = collectRootParamKeys(routeModule);

@@ -60,0 +59,0 @@ return buildAppStaticPaths({

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/dev/static-paths-worker.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type {\n AppPageModule,\n AppPageRouteModule,\n} from '../route-modules/app-page/module'\nimport type {\n AppRouteModule,\n AppRouteRouteModule,\n} from '../route-modules/app-route/module.compiled'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { collectSegments } from '../../build/segment-config/app/app-segments'\nimport type { StaticPathsResult } from '../../build/static-paths/types'\nimport { loadComponents } from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport { isAppPageRouteModule } from '../route-modules/checks'\nimport {\n checkIsRoutePPREnabled,\n type ExperimentalPPRConfig,\n} from '../lib/experimental/ppr'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'\nimport { buildAppStaticPaths } from '../../build/static-paths/app'\nimport { buildPagesStaticPaths } from '../../build/static-paths/pages'\nimport { createIncrementalCache } from '../../export/helpers/create-incremental-cache'\nimport { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'\n\ntype RuntimeConfig = {\n pprConfig: ExperimentalPPRConfig | undefined\n configFileName: string\n cacheComponents: boolean\n}\n\n// we call getStaticPaths in a separate process to ensure\n// side-effects aren't relied on in dev that will break\n// during a production build\nexport async function loadStaticPaths({\n dir,\n distDir,\n pathname,\n config,\n httpAgentOptions,\n locales,\n defaultLocale,\n isAppPath,\n page,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n requestHeaders,\n cacheHandler,\n cacheHandlers,\n cacheLifeProfiles,\n nextConfigOutput,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n sriEnabled,\n}: {\n dir: string\n distDir: string\n pathname: string\n config: RuntimeConfig\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n locales?: readonly string[]\n defaultLocale?: string\n isAppPath: boolean\n page: string\n isrFlushToDisk?: boolean\n fetchCacheKeyPrefix?: string\n cacheMaxMemorySize: number\n requestHeaders: IncrementalCache['requestHeaders']\n cacheHandler?: string\n cacheHandlers?: NextConfigComplete['cacheHandlers']\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n nextConfigOutput: 'standalone' | 'export' | undefined\n buildId: string\n deploymentId: string\n authInterrupts: boolean\n useCacheTimeout: number\n staticPageGenerationTimeout: number\n sriEnabled: boolean\n}): Promise<StaticPathsResult> {\n // this needs to be initialized before loadComponents otherwise\n // \"use cache\" could be missing it's cache handlers\n await createIncrementalCache({\n dir,\n distDir,\n cacheHandler,\n cacheHandlers,\n requestHeaders,\n fetchCacheKeyPrefix,\n flushToDisk: isrFlushToDisk,\n cacheMaxMemorySize,\n })\n\n // update work memory runtime-config\n setHttpClientAndAgentOptions({\n httpAgentOptions,\n })\n\n const components = await loadComponents<AppPageModule | AppRouteModule>({\n distDir,\n // In `pages/`, the page is the same as the pathname.\n page: page || pathname,\n isAppPath,\n isDev: true,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n if (isAppPath) {\n const routeModule = components.routeModule\n const segments = await collectSegments(\n // We know this is an app page or app route module because we checked\n // above that the page type is 'app'.\n routeModule as AppPageRouteModule | AppRouteRouteModule\n )\n\n const route = parseNormalizedAppRoute(pathname)\n if (route.dynamicSegments.length === 0) {\n throw new InvariantError(\n `Expected a dynamic route, but got a static route: ${pathname}`\n )\n }\n\n const isRoutePPREnabled =\n isAppPageRouteModule(routeModule) &&\n checkIsRoutePPREnabled(config.pprConfig)\n\n const rootParamKeys = collectRootParamKeys(routeModule)\n\n return buildAppStaticPaths({\n dir,\n page: pathname,\n route,\n cacheComponents: config.cacheComponents,\n segments,\n distDir,\n requestHeaders,\n cacheHandler,\n cacheLifeProfiles,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n ComponentMod: components.ComponentMod,\n nextConfigOutput,\n isRoutePPREnabled,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n rootParamKeys,\n })\n } else if (!components.getStaticPaths) {\n // We shouldn't get to this point since the worker should only be called for\n // SSG pages with getStaticPaths.\n throw new InvariantError(\n `Failed to load page with getStaticPaths for ${pathname}`\n )\n }\n\n return buildPagesStaticPaths({\n page: pathname,\n getStaticPaths: components.getStaticPaths,\n configFileName: config.configFileName,\n locales,\n defaultLocale,\n })\n}\n"],"names":["collectSegments","loadComponents","setHttpClientAndAgentOptions","isAppPageRouteModule","checkIsRoutePPREnabled","InvariantError","collectRootParamKeys","buildAppStaticPaths","buildPagesStaticPaths","createIncrementalCache","parseNormalizedAppRoute","loadStaticPaths","dir","distDir","pathname","config","httpAgentOptions","locales","defaultLocale","isAppPath","page","isrFlushToDisk","fetchCacheKeyPrefix","cacheMaxMemorySize","requestHeaders","cacheHandler","cacheHandlers","cacheLifeProfiles","nextConfigOutput","buildId","deploymentId","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","flushToDisk","components","isDev","needsManifestsForLegacyReasons","routeModule","segments","route","dynamicSegments","length","isRoutePPREnabled","pprConfig","rootParamKeys","cacheComponents","ComponentMod","getStaticPaths","configFileName"],"mappings":"AAUA,OAAO,kBAAiB;AACxB,OAAO,sBAAqB;AAE5B,SAASA,eAAe,QAAQ,8CAA6C;AAE7E,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,4BAA4B,QAAQ,0BAAyB;AAEtE,SAASC,oBAAoB,QAAQ,0BAAyB;AAC9D,SACEC,sBAAsB,QAEjB,0BAAyB;AAChC,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,oBAAoB,QAAQ,yDAAwD;AAC7F,SAASC,mBAAmB,QAAQ,+BAA8B;AAClE,SAASC,qBAAqB,QAAQ,iCAAgC;AACtE,SAASC,sBAAsB,QAAQ,gDAA+C;AACtF,SAASC,uBAAuB,QAAQ,qCAAoC;AAQ5E,yDAAyD;AACzD,uDAAuD;AACvD,4BAA4B;AAC5B,OAAO,eAAeC,gBAAgB,EACpCC,GAAG,EACHC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EACPC,aAAa,EACbC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,mBAAmB,EACnBC,kBAAkB,EAClBC,cAAc,EACdC,YAAY,EACZC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,EAChBC,OAAO,EACPC,YAAY,EACZC,cAAc,EACdC,eAAe,EACfC,2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ACrCjC;QACAC;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/dev/static-paths-worker.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type {\n AppPageModule,\n AppPageRouteModule,\n} from '../route-modules/app-page/module'\nimport type {\n AppRouteModule,\n AppRouteRouteModule,\n} from '../route-modules/app-route/module.compiled'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { collectSegments } from '../../build/segment-config/app/app-segments'\nimport type { StaticPathsResult } from '../../build/static-paths/types'\nimport { loadComponents } from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport { isAppPageRouteModule } from '../route-modules/checks'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'\nimport { buildAppStaticPaths } from '../../build/static-paths/app'\nimport { buildPagesStaticPaths } from '../../build/static-paths/pages'\nimport { createIncrementalCache } from '../../export/helpers/create-incremental-cache'\nimport { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'\n\ntype RuntimeConfig = {\n configFileName: string\n cacheComponents: boolean\n}\n\n// we call getStaticPaths in a separate process to ensure\n// side-effects aren't relied on in dev that will break\n// during a production build\nexport async function loadStaticPaths({\n dir,\n distDir,\n pathname,\n config,\n httpAgentOptions,\n locales,\n defaultLocale,\n isAppPath,\n page,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n requestHeaders,\n cacheHandler,\n cacheHandlers,\n cacheLifeProfiles,\n nextConfigOutput,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n sriEnabled,\n}: {\n dir: string\n distDir: string\n pathname: string\n config: RuntimeConfig\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n locales?: readonly string[]\n defaultLocale?: string\n isAppPath: boolean\n page: string\n isrFlushToDisk?: boolean\n fetchCacheKeyPrefix?: string\n cacheMaxMemorySize: number\n requestHeaders: IncrementalCache['requestHeaders']\n cacheHandler?: string\n cacheHandlers?: NextConfigComplete['cacheHandlers']\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n nextConfigOutput: 'standalone' | 'export' | undefined\n buildId: string\n deploymentId: string\n authInterrupts: boolean\n useCacheTimeout: number\n staticPageGenerationTimeout: number\n sriEnabled: boolean\n}): Promise<StaticPathsResult> {\n // this needs to be initialized before loadComponents otherwise\n // \"use cache\" could be missing it's cache handlers\n await createIncrementalCache({\n dir,\n distDir,\n cacheHandler,\n cacheHandlers,\n requestHeaders,\n fetchCacheKeyPrefix,\n flushToDisk: isrFlushToDisk,\n cacheMaxMemorySize,\n })\n\n // update work memory runtime-config\n setHttpClientAndAgentOptions({\n httpAgentOptions,\n })\n\n const components = await loadComponents<AppPageModule | AppRouteModule>({\n distDir,\n // In `pages/`, the page is the same as the pathname.\n page: page || pathname,\n isAppPath,\n isDev: true,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n if (isAppPath) {\n const routeModule = components.routeModule\n const segments = await collectSegments(\n // We know this is an app page or app route module because we checked\n // above that the page type is 'app'.\n routeModule as AppPageRouteModule | AppRouteRouteModule\n )\n\n const route = parseNormalizedAppRoute(pathname)\n if (route.dynamicSegments.length === 0) {\n throw new InvariantError(\n `Expected a dynamic route, but got a static route: ${pathname}`\n )\n }\n\n const isRoutePPREnabled =\n isAppPageRouteModule(routeModule) && config.cacheComponents\n\n const rootParamKeys = collectRootParamKeys(routeModule)\n\n return buildAppStaticPaths({\n dir,\n page: pathname,\n route,\n cacheComponents: config.cacheComponents,\n segments,\n distDir,\n requestHeaders,\n cacheHandler,\n cacheLifeProfiles,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n ComponentMod: components.ComponentMod,\n nextConfigOutput,\n isRoutePPREnabled,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n rootParamKeys,\n })\n } else if (!components.getStaticPaths) {\n // We shouldn't get to this point since the worker should only be called for\n // SSG pages with getStaticPaths.\n throw new InvariantError(\n `Failed to load page with getStaticPaths for ${pathname}`\n )\n }\n\n return buildPagesStaticPaths({\n page: pathname,\n getStaticPaths: components.getStaticPaths,\n configFileName: config.configFileName,\n locales,\n defaultLocale,\n })\n}\n"],"names":["collectSegments","loadComponents","setHttpClientAndAgentOptions","isAppPageRouteModule","InvariantError","collectRootParamKeys","buildAppStaticPaths","buildPagesStaticPaths","createIncrementalCache","parseNormalizedAppRoute","loadStaticPaths","dir","distDir","pathname","config","httpAgentOptions","locales","defaultLocale","isAppPath","page","isrFlushToDisk","fetchCacheKeyPrefix","cacheMaxMemorySize","requestHeaders","cacheHandler","cacheHandlers","cacheLifeProfiles","nextConfigOutput","buildId","deploymentId","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","flushToDisk","components","isDev","needsManifestsForLegacyReasons","routeModule","segments","route","dynamicSegments","length","isRoutePPREnabled","cacheComponents","rootParamKeys","ComponentMod","getStaticPaths","configFileName"],"mappings":"AAUA,OAAO,kBAAiB;AACxB,OAAO,sBAAqB;AAE5B,SAASA,eAAe,QAAQ,8CAA6C;AAE7E,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,4BAA4B,QAAQ,0BAAyB;AAEtE,SAASC,oBAAoB,QAAQ,0BAAyB;AAC9D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,oBAAoB,QAAQ,yDAAwD;AAC7F,SAASC,mBAAmB,QAAQ,+BAA8B;AAClE,SAASC,qBAAqB,QAAQ,iCAAgC;AACtE,SAASC,sBAAsB,QAAQ,gDAA+C;AACtF,SAASC,uBAAuB,QAAQ,qCAAoC;AAO5E,yDAAyD;AACzD,uDAAuD;AACvD,4BAA4B;AAC5B,OAAO,eAAeC,gBAAgB,EACpCC,GAAG,EACHC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EACPC,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,IAAI3C,eACR,CAAC,4CAA4C,EAAES,UAAU,GADrD,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,OAAON,sBAAsB;QAC3BY,MAAMN;QACNkC,gBAAgBZ,WAAWY,cAAc;QACzCC,gBAAgBlC,OAAOkC,cAAc;QACrChC;QACAC;IACF;AACF","ignoreList":[0]}

@@ -187,3 +187,2 @@ import { RenderStage } from './app-render/staged-rendering';

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -315,3 +314,2 @@ case 'prerender-runtime':

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -318,0 +316,0 @@ case 'prerender-runtime':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function trackIncompatibleShellContent(workUnitStore: RequestStore) {\n workUnitStore.hasIncompatibleShellContent = true\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */\nexport function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {\n const methodCache: Record<string, (...args: any[]) => any> = {}\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n let patchedMethod = methodCache[prop]\n if (patchedMethod !== undefined) {\n return patchedMethod\n }\n\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n patchedMethod = {\n [prop]: (...args: unknown[]) => {\n try {\n onUse()\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err)\n }\n\n return originalMethod.apply(target, args)\n },\n }[prop]\n\n methodCache[prop] = patchedMethod\n return patchedMethod\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["RenderStage","workUnitAsyncStorage","getServerReact","getClientReact","ReflectAdapter","isHangingPromiseRejectionError","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","ClientHookDynamicError","isClientHookDynamicError","abortListenersBySignal","WeakMap","makeDynamicHangingPromise","signal","makeHangingPromiseWithError","makeUntrackedHangingPromise","makeRuntimeHangingPromise","workUnitStore","trackRuntimeDataAccessed","makeFallbackParamsHangingPromise","trackFallbackParamsAccessed","makeStageHangingPromise","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","trackIncompatibleShellContent","hasIncompatibleShellContent","makeClientHookHangingPromise","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","makePromiseFromTrigger","trigger","value","promise","then","makeDevtoolsIOAwarePromise","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","trackPromiseUsed","onUse","methodCache","Proxy","target","prop","receiver","patchedMethod","originalMethod","args","console","apply","RENDER_STAGES_BY_DATA_KIND","sessionData","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","applyOwnerStack","process","env","NODE_ENV","ownerStack","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":"AAAA,SACEA,WAAW,QAEN,gCAA+B;AAKtC,SAASC,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,cAAc,EAAEC,cAAc,QAAQ,4BAA2B;AAC1E,SAASC,cAAc,QAAQ,wCAAuC;AAEtE,OAAO,SAASC,+BACdC,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,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xE,sDAAsD;QACtD,MAAMC,kBACJ/F,EAAAA,kBAAAA,sCAAAA,oCAAAA,gBAAkBgG,iBAAiB,qBAAnChG,uCAAAA,uBACAD,kBAAAA,sCAAAA,oCAAAA,gBAAkBiG,iBAAiB,qBAAnCjG,uCAAAA;QAEF,OAAQsB,iCAAAA,cAAeO,IAAI;YACzB,KAAK;YACL,KAAK;gBACHiE,aACE,AAACE,CAAAA,mBAAmB,EAAC,IAAM1E,CAAAA,cAAc4E,eAAe,IAAI,EAAC,KAC7D7B;gBACF;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAKA;gBACHyB,aAAaE;gBACb;YACF;gBACE1E;QACJ;QAEA,IAAIwE,YAAY;YACd,IAAIK,QAAQL;YAEZ,IAAIvD,MAAM4D,KAAK,EAAE;gBACf,MAAMC,SAAmB,EAAE;gBAE3B,KAAK,MAAMC,SAAS9D,MAAM4D,KAAK,CAACG,KAAK,CAAC,MAAMC,KAAK,CAAC,GAAI;oBACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAOnD,IAAI,CAACoD;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEA5D,MAAM4D,KAAK,GAAG5D,MAAMmE,IAAI,GAAG,OAAOnE,MAAMoE,OAAO,GAAGR;QACpD;IACF;IAEA,OAAO5D;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function trackIncompatibleShellContent(workUnitStore: RequestStore) {\n workUnitStore.hasIncompatibleShellContent = true\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */\nexport function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {\n const methodCache: Record<string, (...args: any[]) => any> = {}\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n let patchedMethod = methodCache[prop]\n if (patchedMethod !== undefined) {\n return patchedMethod\n }\n\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n patchedMethod = {\n [prop]: (...args: unknown[]) => {\n try {\n onUse()\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err)\n }\n\n return originalMethod.apply(target, args)\n },\n }[prop]\n\n methodCache[prop] = patchedMethod\n return patchedMethod\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["RenderStage","workUnitAsyncStorage","getServerReact","getClientReact","ReflectAdapter","isHangingPromiseRejectionError","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","ClientHookDynamicError","isClientHookDynamicError","abortListenersBySignal","WeakMap","makeDynamicHangingPromise","signal","makeHangingPromiseWithError","makeUntrackedHangingPromise","makeRuntimeHangingPromise","workUnitStore","trackRuntimeDataAccessed","makeFallbackParamsHangingPromise","trackFallbackParamsAccessed","makeStageHangingPromise","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","trackIncompatibleShellContent","hasIncompatibleShellContent","makeClientHookHangingPromise","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","makePromiseFromTrigger","trigger","value","promise","then","makeDevtoolsIOAwarePromise","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","trackPromiseUsed","onUse","methodCache","Proxy","target","prop","receiver","patchedMethod","originalMethod","args","console","apply","RENDER_STAGES_BY_DATA_KIND","sessionData","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","applyOwnerStack","process","env","NODE_ENV","ownerStack","getStore","innerOwnerStack","capt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BAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEA5D,MAAM4D,KAAK,GAAG5D,MAAMmE,IAAI,GAAG,OAAOnE,MAAMoE,OAAO,GAAGR;QACpD;IACF;IAEA,OAAO5D;AACT","ignoreList":[0]}

@@ -14,3 +14,3 @@ import { loadEnvConfig } from '@next/env';

const versionSuffix = logBundler ? ` (${bundlerName(getBundlerFromEnv())})` : '';
Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.1-canary.11"}`))}${versionSuffix}`);
Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.1-canary.12"}`))}${versionSuffix}`);
if (appUrl) {

@@ -17,0 +17,0 @@ Log.bootstrap(`- Local: ${appUrl}`);

@@ -28,3 +28,2 @@ import { AppRenderSpan, NextNodeServerSpan } from './trace/constants';

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -321,3 +320,2 @@ case 'cache':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -360,3 +358,2 @@ case 'cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -468,3 +465,2 @@ case 'request':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -581,3 +577,2 @@ case 'cache':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -619,3 +614,2 @@ case 'cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -723,3 +717,2 @@ case 'unstable-cache':

// fallthrough
case 'prerender-ppr':
case 'prerender-legacy':

@@ -782,3 +775,2 @@ case 'cache':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -877,3 +869,2 @@ case 'cache':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -912,3 +903,2 @@ case 'cache':

case 'prerender-legacy':
case 'prerender-ppr':
case 'generate-static-params':

@@ -915,0 +905,0 @@ break;

@@ -25,3 +25,2 @@ // this must come first as it includes require hooks

import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request';
import { isPostpone } from './router-utils/is-postpone';
import { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest';

@@ -589,7 +588,2 @@ import { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url';

const logError = async (err)=>{
if (isPostpone(err)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return;
}
Log.error('uncaughtException: ', err);

@@ -596,0 +590,0 @@ };

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { releaseCompressionStream } from './release-compression-stream'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isPostpone } from './router-utils/is-postpone'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n const devMemoryThresholdRestart =\n development?.config.experimental.devMemoryThresholdRestart !== false\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n\n // On client disconnect the middleware never ends its zlib stream, which\n // then leaks past GC. See `releaseCompressionStream`.\n res.once('close', () => {\n if (res.writableFinished) return\n\n releaseCompressionStream(res)\n })\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n devMemoryThresholdRestart,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (err: Error | undefined) => {\n if (isPostpone(err)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n Log.error('uncaughtException: ', err)\n }\n\n process.on('uncaughtException', logError)\n\n // The render server may run in the same process and have already registered\n // the unhandled rejection listener, in which case we must not register\n // another one, to avoid logging unhandled rejections multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n devMemoryThresholdRestart,\n }\n}\n"],"names":["url","path","loadConfig","finalizeBundlerFromConfig","getBundlerFromEnv","serveStatic","setupDebug","Log","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","DecodeError","findPagesDir","setupFsCheck","proxyRequest","isAbortError","pipeToNodeResponse","getResolveRoutes","addRequestMeta","getRequestMeta","pathHasPrefix","removePathPrefix","setupCompression","releaseCompressionStream","signalFromNodeResponse","isPostpone","isNonHtmlSecFetchDest","parseUrl","parseUrlUtil","PHASE_PRODUCTION_SERVER","PHASE_DEVELOPMENT_SERVER","REQUEST_INSIGHTS_DEV_ENDPOINT","UNDERSCORE_NOT_FOUND_ROUTE","RedirectStatusCode","DevBundlerService","trace","ensureLeadingSlash","getNextPathnameInfo","getHostname","detectDomainLocale","MockedResponse","HMR_MESSAGE_SENT_TO_BROWSER","normalizedAssetPrefix","NEXT_PATCH_SYMBOL","filterInternalHeaders","blockCrossSiteDEV","traceGlobals","NoFallbackError","RouterServerContextSymbol","routerServerGlobal","handleChromeDevtoolsWorkspaceRequest","isChromeDevtoolsWorkspaceUrl","getNextConfigRuntime","getRequestInsightsSnapshot","isRequestInsightsEnabled","debug","isNextFont","pathname","test","requestHandlers","initialize","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","undefined","experimentalFeatures","config","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","compress","fsChecker","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","join","set","pagesDir","appDir","setupDevBundler","resetFetch","setupDevBundlerSpan","startServerSpan","traceChild","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","req","res","Boolean","requestInsights","bundler","service","devMemoryThresholdRestart","instance","requestHandlerImpl","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","headers","__NEXT_REQUEST_INSIGHTS","urlParts","split","basePath","allowedDevOrigins","hostname","setHeader","statusCode","end","JSON","stringify","error","i18n","localeDetection","urlNoQuery","pathnameInfo","domainLocale","domains","defaultLocale","getLocaleRedirect","parsedUrl","replace","redirect","pathLocale","locale","urlParsed","TemporaryRedirect","once","writableFinished","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","handleRequest","e","origUrl","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","closed","type","Object","keys","result","destination","format","PermanentRedirect","protocol","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","realRequestPathname","appNotFound","serverFields","hasAppNotFound","getItem","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","relative","cwd","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","URL","canParse","isHMRRequest","onHMR","client","isLegacyClient","send","ISR_MANIFEST","data","appIsrManifest","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;AAKpD,6EAA6E;AAC7E,OAAO,sBAAqB;AAC5B,OAAO,kBAAiB;AAExB,OAAOA,SAAS,MAAK;AACrB,OAAOC,UAAU,OAAM;AACvB,OAAOC,gBAAwD,YAAW;AAC1E,SAASC,yBAAyB,EAAEC,iBAAiB,QAAQ,oBAAmB;AAChF,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,OAAOC,gBAAgB,2BAA0B;AACjD,YAAYC,SAAS,yBAAwB;AAC7C,SACEC,sCAAsC,EACtCC,kCAAkC,QAC7B,wDAAuD;AAC9D,SAASC,WAAW,QAAQ,yBAAwB;AACpD,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SAASC,YAAY,QAAQ,4BAA2B;AACxD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,mBAAkB;AACnE,SAASC,gBAAgB,QAAQ,gCAA+B;AAChE,SAASC,cAAc,EAAEC,cAAc,QAAQ,kBAAiB;AAChE,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,m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W;oBACT,MAAM,qBAEL,CAFK,IAAI/F,MACR,mFADI,qBAAA;+BAAA;oCAAA;sCAAA;oBAEN;gBACF;YACF;YACA,MAAM,EAAEa,QAAQ,EAAEG,aAAa,EAAEtC,SAAS,EAAEb,UAAU,EAAE,GACtD,MAAMoD,cAAc;gBAClBvE;gBACAC;gBACAuE,cAAc;gBACdC,QAAQvK,uBAAuBsO;YACjC;YAEF,mDAAmD;YACnD,oCAAoC;YACpC,IAAIlE,eAAe;gBACjB,OAAOkE,OAAOpH,GAAG;YACnB;YAEA,IAAI+C,YAAYnC,UAAUkD,QAAQ,EAAE;gBAClC,IAAI,CAAC/D,YAAY;oBACf,OAAO,MAAM3H,aAAawG,KAAKwI,QAAQxG,WAAWyG;gBACpD;gBAEA,OAAOD,OAAOpH,GAAG;YACnB;QAEA,sEAAsE;QACtE,sDAAsD;QACxD,EAAE,OAAOuC,KAAK;YACZiD,QAAQrF,KAAK,CAAC,kCAAkCoC;YAChD6E,OAAOpH,GAAG;QACZ;IACF;IAEA,OAAO;QACLsC;QACA6E;QACArB,QAAQ7D,SAAS6D,MAAM;QACvBoC;gBACE9M,kCAAAA;YAAAA,gCAAAA,uBAAAA,YAAa4D,OAAO,sBAApB5D,mCAAAA,qBAAsByH,WAAW,qBAAjCzH,iCAAmC+M,KAAK;QAC1C;QACAlL,SAASrB,OAAOqB,OAAO;QACvBtB;QACA0K,iBAAiBzK,OAAOyK,eAAe;QACvCC,oBAAoB1K,OAAO0K,kBAAkB;QAC7C8B,YAAYxM,OAAOwM,UAAU;QAC7BlJ;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { releaseCompressionStream } from './release-compression-stream'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n const devMemoryThresholdRestart =\n development?.config.experimental.devMemoryThresholdRestart !== false\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n\n // On client disconnect the middleware never ends its zlib stream, which\n // then leaks past GC. See `releaseCompressionStream`.\n res.once('close', () => {\n if (res.writableFinished) return\n\n releaseCompressionStream(res)\n })\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n devMemoryThresholdRestart,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (err: Error | undefined) => {\n Log.error('uncaughtException: ', err)\n }\n\n process.on('uncaughtException', logError)\n\n // The render server may run in the same process and have already registered\n // the unhandled rejection listener, in which case we must not register\n // another one, to avoid logging unhandled rejections multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n devMemoryThresholdRestart,\n }\n}\n"],"names":["url","path","loadConfig","finalizeBundlerFromConfig","getBundlerFromEnv","serveStatic","setupDebug","Log","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","DecodeError","findPagesDir","setupFsCheck","proxyRequest","isAbortError","pipeToNodeResponse","getResolveRoutes","addRequestMeta","getRequestMeta","pathHasPrefix","removePathPrefix","setupCompression","releaseCompressionStream","signalFromNodeResponse","isNonHtmlSecFetchDest","parseUrl","parseUrlUtil","PHASE_PRODUCTION_SERVER","PHASE_DEVELOPMENT_SERVER","REQUEST_INSIGHTS_DEV_ENDPOINT","UNDERSCORE_NOT_FOUND_ROUTE","RedirectStatusCode","DevBundlerService","trace","ensureLeadingSlash","getNextPathnameInfo","getHostname","detectDomainLocale","MockedResponse","HMR_MESSAGE_SENT_TO_BROWSER","normalizedAssetPrefix","NEXT_PATCH_SYMBOL","filterInternalHeaders","blockCrossSiteDEV","traceGlobals","NoFallbackError","RouterServerContextSymbol","routerServerGlobal","handleChromeDevtoolsWorkspaceRequest","isChromeDevtoolsWorkspaceUrl","getNextConfigRuntime","getRequestInsightsSnapshot","isRequestInsightsEnabled","debug","isNextFont","pathname","test","requestHandlers","initialize","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","undefined","experimentalFeatures","config","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","compress","fsChecker","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","join","set","pagesDir","appDir","setupDevBundler","resetFetch","setupDevBundlerSpan","startServerSpan","traceChild","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","req","res","Boolean","requestInsights","bundler","service","devMemoryThresholdRestart","instance","requestHandlerImpl","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","headers","__NEXT_REQUEST_INSIGHTS","urlParts","split","basePath","allowedDevOrigins","hostname","setHeader","statusCode","end","JSON","stringify","error","i18n","localeDetection","urlNoQuery","pathnameInfo","domainLocale","domains","defaultLocale","getLocaleRedirect","parsedUrl","replace","redirect","pathLocale","locale","urlParsed","TemporaryRedirect","once","writableFinished","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","handleRequest","e","origUrl","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","closed","type","Object","keys","result","destination","format","PermanentRedirect","protocol","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","realRequestPathname","appNotFound","serverFields","hasAppNotFound","getItem","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","relative","cwd","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","URL","canParse","isHMRRequest","onHMR","client","isLegacyClient","send","ISR_MANIFEST","data","appIsrManifest","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;AAKpD,6EAA6E;AAC7E,OAAO,sBAAqB;AAC5B,OAAO,kBAAiB;AAExB,OAAOA,SAAS,MAAK;AACrB,OAAOC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,qBAAsByH,WAAW,qBAAjCzH,iCAAmC+M,KAAK;QAC1C;QACAlL,SAASrB,OAAOqB,OAAO;QACvBtB;QACA0K,iBAAiBzK,OAAOyK,eAAe;QACvCC,oBAAoB1K,OAAO0K,kBAAkB;QAC7C8B,YAAYxM,OAAOwM,UAAU;QAC7BlJ;IACF;AACF","ignoreList":[0]}

@@ -112,3 +112,3 @@ // Start CPU profile if it wasn't already started.

let { port } = serverOptions;
process.title = `next-server (v${"16.3.1-canary.11"})`;
process.title = `next-server (v${"16.3.1-canary.12"})`;
let handlersReady = ()=>{};

@@ -115,0 +115,0 @@ let handlersError = ()=>{};

@@ -202,3 +202,2 @@ import * as inspector from 'node:inspector';

case 'prerender-legacy':
case 'prerender-ppr':
case 'cache':

@@ -205,0 +204,0 @@ case 'unstable-cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/node-environment-extensions/console-dim.external.tsx"],"sourcesContent":["import * as inspector from 'node:inspector'\nimport { dim } from '../../lib/picocolors'\nimport {\n consoleAsyncStorage,\n type ConsoleStore,\n} from '../app-render/console-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value\nconst DIMMED_STYLE = 'dimmed'\nconst HIDDEN_STYLE = 'hidden'\n\ntype LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE\n\nlet currentAbortedLogsStyle: LogStyle = 'dimmed'\nexport function setAbortedLogsStyle(style: LogStyle) {\n currentAbortedLogsStyle = style\n}\n\ntype InterceptableConsoleMethod =\n | 'error'\n | 'assert'\n | 'debug'\n | 'dir'\n | 'dirxml'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'info'\n | 'log'\n | 'table'\n | 'trace'\n | 'warn'\n\nconst isColorSupported = dim('test') !== 'test'\n\n// 50% opacity for dimmed text\nconst dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'\nconst reactBadgeFormat = '\\x1b[0m\\x1b[7m%c%s\\x1b[0m%c '\n\nfunction dimmedConsoleArgs(...inputArgs: any[]): any[] {\n if (!isColorSupported) {\n return inputArgs\n }\n\n const newArgs = inputArgs.slice(0)\n let template = ''\n let argumentsPointer = 0\n if (typeof inputArgs[0] === 'string') {\n const originalTemplateString = inputArgs[0]\n // Remove the original template string from the args.\n newArgs.splice(argumentsPointer, 1)\n argumentsPointer += 1\n\n let i = 0\n if (originalTemplateString.startsWith(reactBadgeFormat)) {\n i = reactBadgeFormat.length\n // for `format` we already moved the pointer earlier\n // style, badge, reset style\n argumentsPointer += 3\n template += reactBadgeFormat\n // React's badge reset styles, reapply dimming\n template += '\\x1b[2m%c'\n // argumentsPointer includes template\n newArgs.splice(argumentsPointer - 1, 0, dimStyle)\n // dim the badge\n newArgs[0] += `;${dimStyle}`\n }\n\n for (i; i < originalTemplateString.length; i++) {\n const currentChar = originalTemplateString[i]\n if (currentChar !== '%') {\n template += currentChar\n continue\n }\n\n const nextChar = originalTemplateString[i + 1]\n ++i\n\n switch (nextChar) {\n case 'f':\n case 'O':\n case 'o':\n case 'd':\n case 's':\n case 'i':\n case 'c':\n ++argumentsPointer\n template += `%${nextChar}`\n break\n default:\n template += `%${nextChar}`\n }\n }\n }\n\n for (\n argumentsPointer;\n argumentsPointer < inputArgs.length;\n ++argumentsPointer\n ) {\n const arg = inputArgs[argumentsPointer]\n const argType = typeof arg\n if (argumentsPointer > 0) {\n template += ' '\n }\n switch (argType) {\n case 'boolean':\n case 'string':\n template += '%s'\n break\n case 'bigint':\n template += '%s'\n break\n case 'number':\n if (arg % 0) {\n template += '%f'\n } else {\n template += '%d'\n }\n break\n case 'object':\n template += '%O'\n break\n case 'symbol':\n case 'undefined':\n case 'function':\n template += '%s'\n break\n default:\n // deopt to string for new, unknown types\n template += '%s'\n }\n }\n\n template += '\\x1b[22m'\n\n return [dim(`%c${template}`), dimStyle, ...newArgs]\n}\n\nfunction convertToDimmedArgs(\n methodName: InterceptableConsoleMethod,\n args: any[]\n): any[] {\n // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely.\n // Dimming wraps arguments in a format string which defeats inspector\n // affordances such as collapsible objects and clickable/linkified stack\n // traces. Ideally we would only skip dimming when a debugger frontend is\n // actually attached, but Node.js does not expose a synchronous API for that.\n // Detecting would require async polling of the /json/list HTTP endpoint.\n if (inspector.url() !== undefined) {\n return args\n }\n\n switch (methodName) {\n case 'dir':\n case 'dirxml':\n case 'group':\n case 'groupCollapsed':\n case 'groupEnd':\n case 'table': {\n // These methods cannot be colorized because they don't take a formatting string.\n return args\n }\n case 'assert': {\n // assert takes formatting options as the second argument.\n return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))\n }\n case 'error':\n case 'debug':\n case 'info':\n case 'log':\n case 'trace':\n case 'warn':\n return dimmedConsoleArgs(args[0], ...args.slice(1))\n default:\n return methodName satisfies never\n }\n}\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethod(methodName: InterceptableConsoleMethod): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n const wrapperMethod = function (this: typeof console, ...args: any[]) {\n const consoleStore = consoleAsyncStorage.getStore()\n\n // First we see if there is a cache signal for our current scope. If we're in a client render it'll\n // come from the client React cacheSignal implementation. If we are in a server render it'll come from\n // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither\n // scope and these signals return null if you are out of scope so this can be called from a single global patch\n // and still work properly.\n const signal =\n getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()\n if (signal) {\n // We are in a React Server render and can consult the React cache signal to determine if logs\n // are now dimmable.\n if (signal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n }\n\n // We need to fall back to checking the work unit store for two reasons.\n // 1. Client React does not yet implement cacheSignal (it always returns null)\n // 2. route.ts files aren't rendered with React but do have prerender semantics\n // TODO in the future we should be able to remove this once there is a runnable cache\n // scope independent of actual React rendering.\n const workUnitStore = workUnitAsyncStorage.getStore()\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // These can be hit in a route handler. In the future we can use potential React.createCache API\n // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.\n // fallthrough\n case 'prerender-client':\n case 'validation-client': {\n // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.\n const renderSignal = workUnitStore.renderSignal\n if (renderSignal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n }\n }\n // intentional fallthrough\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n case 'request':\n case 'generate-static-params':\n case undefined:\n if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n default:\n workUnitStore satisfies never\n }\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\nfunction applyWithDimming<F extends (this: Console, ...args: any[]) => any>(\n this: Console,\n consoleStore: undefined | ConsoleStore,\n method: F,\n methodName: InterceptableConsoleMethod,\n args: Parameters<F>\n): ReturnType<F> {\n if (consoleStore?.dim === true) {\n return method.apply(this, convertToDimmedArgs(methodName, args))\n } else {\n return consoleAsyncStorage.run(\n DIMMED_STORE,\n method.bind(this, ...convertToDimmedArgs(methodName, args))\n )\n }\n}\n\nconst DIMMED_STORE = { dim: true }\n\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["inspector","dim","consoleAsyncStorage","workUnitAsyncStorage","getServerReact","getClientReact","DIMMED_STYLE","HIDDEN_STYLE","currentAbortedLogsStyle","setAbortedLogsStyle","style","isColorSupported","dimStyle","reactBadgeFormat","dimmedConsoleArgs","inputArgs","newArgs","slice","template","argumentsPointer","originalTemplateString","splice","i","startsWith","length","currentChar","nextChar","arg","argType","convertToDimmedArgs","methodName","args","url","undefined","concat","patchConsoleMethod","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","consoleStore","getStore","signal","cacheSignal","aborted","applyWithDimming","call","apply","workUnitStore","type","renderSignal","defineProperty","method","run","DIMMED_STORE","bind"],"mappings":"AAAA,YAAYA,eAAe,iBAAgB;AAC3C,SAASC,GAAG,QAAQ,uBAAsB;AAC1C,SACEC,mBAAmB,QAEd,+CAA8C;AACrD,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,cAAc,EAAEC,cAAc,QAAQ,6BAA4B;AAE3E,6HAA6H;AAC7H,MAAMC,eAAe;AACrB,MAAMC,eAAe;AAIrB,IAAIC,0BAAoC;AACxC,OAAO,SAASC,oBAAoBC,KAAe;IACjDF,0BAA0BE;AAC5B;AAiBA,MAAMC,mBAAmBV,IAAI,YAAY;AAEzC,8BAA8B;AAC9B,MAAMW,WAAW;AACjB,MAAMC,mBAAmB;A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gBACAb,YACAC;wBAEJ;oBACF;gBACA,0BAA0B;gBAC1B,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAKE;oBACH,IAAIa,CAAAA,gCAAAA,aAAc7C,GAAG,MAAK,MAAM;wBAC9B,OAAOkD,iBAAiBC,IAAI,CAC1B,IAAI,EACJN,cACAH,gBACAb,YACAC;oBAEJ,OAAO;wBACL,OAAOY,eAAeU,KAAK,CAAC,IAAI,EAAEtB;oBACpC;gBACF;oBACEuB;YACJ;QACF;QACA,IAAIV,cAAc;YAChBP,OAAOoB,cAAc,CAACZ,eAAe,QAAQD;QAC/C;QACAP,OAAOoB,cAAc,CAAClB,SAAST,YAAY;YACzCY,OAAOG;QACT;IACF;AACF;AAEA,SAASM,iBAEPL,YAAsC,EACtCY,MAAS,EACT5B,UAAsC,EACtCC,IAAmB;IAEnB,IAAIe,CAAAA,gCAAAA,aAAc7C,GAAG,MAAK,MAAM;QAC9B,OAAOyD,OAAOL,KAAK,CAAC,IAAI,EAAExB,oBAAoBC,YAAYC;IAC5D,OAAO;QACL,OAAO7B,oBAAoByD,GAAG,CAC5BC,cACAF,OAAOG,IAAI,CAAC,IAAI,KAAKhC,oBAAoBC,YAAYC;IAEzD;AACF;AAEA,MAAM6B,eAAe;IAAE3D,KAAK;AAAK;AAEjCkC,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/node-environment-extensions/console-dim.external.tsx"],"sourcesContent":["import * as inspector from 'node:inspector'\nimport { dim } from '../../lib/picocolors'\nimport {\n consoleAsyncStorage,\n type ConsoleStore,\n} from '../app-render/console-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value\nconst DIMMED_STYLE = 'dimmed'\nconst HIDDEN_STYLE = 'hidden'\n\ntype LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE\n\nlet currentAbortedLogsStyle: LogStyle = 'dimmed'\nexport function setAbortedLogsStyle(style: LogStyle) {\n currentAbortedLogsStyle = style\n}\n\ntype InterceptableConsoleMethod =\n | 'error'\n | 'assert'\n | 'debug'\n | 'dir'\n | 'dirxml'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'info'\n | 'log'\n | 'table'\n | 'trace'\n | 'warn'\n\nconst isColorSupported = dim('test') !== 'test'\n\n// 50% opacity for dimmed text\nconst dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'\nconst reactBadgeFormat = '\\x1b[0m\\x1b[7m%c%s\\x1b[0m%c '\n\nfunction dimmedConsoleArgs(...inputArgs: any[]): any[] {\n if (!isColorSupported) {\n return inputArgs\n }\n\n const newArgs = inputArgs.slice(0)\n let template = ''\n let argumentsPointer = 0\n if (typeof inputArgs[0] === 'string') {\n const originalTemplateString = inputArgs[0]\n // Remove the original template string from the args.\n newArgs.splice(argumentsPointer, 1)\n argumentsPointer += 1\n\n let i = 0\n if (originalTemplateString.startsWith(reactBadgeFormat)) {\n i = reactBadgeFormat.length\n // for `format` we already moved the pointer earlier\n // style, badge, reset style\n argumentsPointer += 3\n template += reactBadgeFormat\n // React's badge reset styles, reapply dimming\n template += '\\x1b[2m%c'\n // argumentsPointer includes template\n newArgs.splice(argumentsPointer - 1, 0, dimStyle)\n // dim the badge\n newArgs[0] += `;${dimStyle}`\n }\n\n for (i; i < originalTemplateString.length; i++) {\n const currentChar = originalTemplateString[i]\n if (currentChar !== '%') {\n template += currentChar\n continue\n }\n\n const nextChar = originalTemplateString[i + 1]\n ++i\n\n switch (nextChar) {\n case 'f':\n case 'O':\n case 'o':\n case 'd':\n case 's':\n case 'i':\n case 'c':\n ++argumentsPointer\n template += `%${nextChar}`\n break\n default:\n template += `%${nextChar}`\n }\n }\n }\n\n for (\n argumentsPointer;\n argumentsPointer < inputArgs.length;\n ++argumentsPointer\n ) {\n const arg = inputArgs[argumentsPointer]\n const argType = typeof arg\n if (argumentsPointer > 0) {\n template += ' '\n }\n switch (argType) {\n case 'boolean':\n case 'string':\n template += '%s'\n break\n case 'bigint':\n template += '%s'\n break\n case 'number':\n if (arg % 0) {\n template += '%f'\n } else {\n template += '%d'\n }\n break\n case 'object':\n template += '%O'\n break\n case 'symbol':\n case 'undefined':\n case 'function':\n template += '%s'\n break\n default:\n // deopt to string for new, unknown types\n template += '%s'\n }\n }\n\n template += '\\x1b[22m'\n\n return [dim(`%c${template}`), dimStyle, ...newArgs]\n}\n\nfunction convertToDimmedArgs(\n methodName: InterceptableConsoleMethod,\n args: any[]\n): any[] {\n // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely.\n // Dimming wraps arguments in a format string which defeats inspector\n // affordances such as collapsible objects and clickable/linkified stack\n // traces. Ideally we would only skip dimming when a debugger frontend is\n // actually attached, but Node.js does not expose a synchronous API for that.\n // Detecting would require async polling of the /json/list HTTP endpoint.\n if (inspector.url() !== undefined) {\n return args\n }\n\n switch (methodName) {\n case 'dir':\n case 'dirxml':\n case 'group':\n case 'groupCollapsed':\n case 'groupEnd':\n case 'table': {\n // These methods cannot be colorized because they don't take a formatting string.\n return args\n }\n case 'assert': {\n // assert takes formatting options as the second argument.\n return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))\n }\n case 'error':\n case 'debug':\n case 'info':\n case 'log':\n case 'trace':\n case 'warn':\n return dimmedConsoleArgs(args[0], ...args.slice(1))\n default:\n return methodName satisfies never\n }\n}\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethod(methodName: InterceptableConsoleMethod): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n const wrapperMethod = function (this: typeof console, ...args: any[]) {\n const consoleStore = consoleAsyncStorage.getStore()\n\n // First we see if there is a cache signal for our current scope. If we're in a client render it'll\n // come from the client React cacheSignal implementation. If we are in a server render it'll come from\n // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither\n // scope and these signals return null if you are out of scope so this can be called from a single global patch\n // and still work properly.\n const signal =\n getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()\n if (signal) {\n // We are in a React Server render and can consult the React cache signal to determine if logs\n // are now dimmable.\n if (signal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n }\n\n // We need to fall back to checking the work unit store for two reasons.\n // 1. Client React does not yet implement cacheSignal (it always returns null)\n // 2. route.ts files aren't rendered with React but do have prerender semantics\n // TODO in the future we should be able to remove this once there is a runnable cache\n // scope independent of actual React rendering.\n const workUnitStore = workUnitAsyncStorage.getStore()\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // These can be hit in a route handler. In the future we can use potential React.createCache API\n // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.\n // fallthrough\n case 'prerender-client':\n case 'validation-client': {\n // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.\n const renderSignal = workUnitStore.renderSignal\n if (renderSignal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n }\n }\n // intentional fallthrough\n case 'prerender-legacy':\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n case 'request':\n case 'generate-static-params':\n case undefined:\n if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n default:\n workUnitStore satisfies never\n }\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\nfunction applyWithDimming<F extends (this: Console, ...args: any[]) => any>(\n this: Console,\n consoleStore: undefined | ConsoleStore,\n method: F,\n methodName: InterceptableConsoleMethod,\n args: Parameters<F>\n): ReturnType<F> {\n if (consoleStore?.dim === true) {\n return method.apply(this, convertToDimmedArgs(methodName, args))\n } else {\n return consoleAsyncStorage.run(\n DIMMED_STORE,\n method.bind(this, ...convertToDimmedArgs(methodName, args))\n )\n }\n}\n\nconst DIMMED_STORE = { dim: true }\n\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["inspector","dim","consoleAsyncStorage","workUnitAsyncStorage","getServerReact","getClientReact","DIMMED_STYLE","HIDDEN_STYLE","currentAbortedLogsStyle","setAbortedLogsStyle","style","isColorSupported","dimStyle","reactBadgeFormat","dimmedConsoleArgs","inputArgs","newArgs","slice","template","argumentsPointer","originalTemplateString","splice","i","startsWith","length","currentChar","nextChar","arg","argType","convertToDimmedArgs","methodName","args","url","undefined","concat","patchConsoleMethod","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","consoleStore","getStore","signal","cacheSignal","aborted","applyWithDimming","call","apply","workUnitStore","type","renderSignal","defineProperty","method","run","DIMMED_STORE","bind"],"mappings":"AAAA,YAAYA,eAAe,iBAAgB;AAC3C,SAASC,GAAG,QAAQ,uBAAsB;AAC1C,SACEC,mBAAmB,QAEd,+CAA8C;AACrD,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,cAAc,EAAEC,cAAc,QAAQ,6BAA4B;AAE3E,6HAA6H;AAC7H,MAAMC,eAAe;AACrB,MAAMC,eAAe;AAIrB,IAAIC,0BAAoC;AACxC,OAAO,SAASC,oBAAoBC,KAAe;IACjDF,0BAA0BE;AAC5B;AAiBA,MAAMC,mBAAmBV,IAAI,YAAY;AAEzC,8BAA8B;AAC9B,MAAMW,WAAW;AACjB,MAAMC,mBAAmB;AAEzB,SAASC,kBAAkB,GAAGC,SAAgB;IAC5C,IAAI,CAACJ,kBAAkB;QACrB,OAAOI;IACT;IAEA,MAAMC,UAAUD,UAAUE,KAAK,CAAC;IAChC,IAAIC,WAAW;IACf,IAAIC,mBAAmB;IACvB,IAAI,OAAOJ,SAAS,CAAC,EAAE,KAAK,UAAU;QACpC,MAAMK,yBAAyBL,SAAS,CAAC,EAAE;QAC3C,qDAAqD;QACrDC,QAAQK,MAAM,CAACF,kBAAkB;QACjCA,oBAAoB;QAEpB,IAAIG,IAAI;QACR,IAAIF,uBAAuBG,UAAU,CAACV,mBAAmB;YACvDS,IAAIT,iBAAiBW,MAAM;YAC3B,oDAAoD;YACpD,4BAA4B;YAC5BL,oBAAoB;YACpBD,YAAYL;YACZ,8CAA8C;YAC9CK,YAAY;YACZ,qCAAqC;YACrCF,QAAQK,MAAM,CAACF,mBAAmB,GAAG,GAAGP;YACxC,gBAAgB;YAChBI,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC,EAAEJ,UAAU;QAC9B;QAEA,IAAKU,GAAGA,IAAIF,uBAAuBI,MAAM,EAAEF,IAAK;Y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B,oBAAoByD,GAAG,CAC5BC,cACAF,OAAOG,IAAI,CAAC,IAAI,KAAKhC,oBAAoBC,YAAYC;IAEzD;AACF;AAEA,MAAM6B,eAAe;IAAE3D,KAAK;AAAK;AAEjCkC,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB","ignoreList":[0]}

@@ -80,3 +80,2 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external';

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -83,0 +82,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/node-environment-extensions/io-utils.tsx"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport {\n createSyncIOClientError,\n createSyncIOError,\n createSyncIORuntimeError,\n type SyncIOApiType,\n} from '../app-render/sync-io-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function io(expression: string, type: SyncIOApiType) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const workStore = workAsyncStorage.getStore()\n\n if (!workUnitStore || !workStore) {\n return\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(createSyncIOError(workStore.route, expression, type)),\n workUnitStore\n )\n }\n break\n }\n case 'prerender-client': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(\n createSyncIOClientError(workStore.route, expression, type)\n ),\n workUnitStore\n )\n }\n break\n }\n case 'request': {\n const stageController = workUnitStore.stagedRendering\n if (stageController && stageController.shouldTrackSyncInterrupt()) {\n let syncIOError: Error\n // NOTE: keep stages where we can interrupt in sync with\n // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`\n switch (stageController.currentStage) {\n case RenderStage.ShellStatic:\n case RenderStage.Static: {\n syncIOError = createSyncIOError(workStore.route, expression, type)\n break\n }\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n // We're in the Runtime stage.\n // We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.\n syncIOError = createSyncIORuntimeError(\n workStore.route,\n expression,\n type\n )\n break\n }\n case RenderStage.Before:\n case RenderStage.Dynamic:\n case RenderStage.Abandoned: {\n throw new InvariantError(\n `shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${RenderStage[stageController.currentStage]}`\n )\n }\n }\n\n syncIOError = applyOwnerStack(syncIOError)\n stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n // A validation render uses a 'request' store type, but may be abortable.\n // If we're rendering with filled caches, Sync IO is an error and should trigger an abort.\n if (\n workUnitStore.controller &&\n !workUnitStore.controller.signal.aborted\n ) {\n workUnitStore.controller.abort(syncIOError)\n }\n }\n break\n }\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","abortOnSynchronousPlatformIOAccess","RenderStage","applyOwnerStack","createSyncIOClientError","createSyncIOError","createSyncIORuntimeError","InvariantError","io","expression","type","workUnitStore","getStore","workStore","prerenderSignal","controller","signal","aborted","route","stageController","stagedRendering","shouldTrackSyncInterrupt","syncIOError","currentStage","ShellStatic","Static","ShellRuntime","Runtime","Before","Dynamic","Abandoned","syncInterruptCurrentStageWithReason","abort"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,kCAAkC,QAAQ,kCAAiC;AACpF,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,wBAAwB,QAEnB,iCAAgC;AACvC,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC,GAAGC,UAAkB,EAAEC,IAAmB;IACxD,MAAMC,gBAAgBX,qBAAqBY,QAAQ;IACnD,MAAMC,YAAYd,iBAAiBa,QAAQ;IAE3C,IAAI,CAACD,iBAAiB,CAACE,WAAW;QAChC;IACF;IAEA,OAAQF,cAAcD,IAAI;QACxB,KAAK;QACL,KAAK;YAAqB;gBACxB,MAAMI,kBAAkBH,cAAcI,UAAU,CAACC,MAAM;gBAEvD,IAAIF,gBAAgBG,OAAO,KAAK,OAAO;oBACrC,wEAAwE;oBACxE,uEAAuE;oBACvEhB,mCACEY,UAAUK,KAAK,EACfT,YACAN,gBAAgBE,kBAAkBQ,UAAUK,KAAK,EAAET,YAAYC,QAC/DC;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBACvB,MAAMG,kBAAkBH,cAAcI,UAAU,CAACC,MAAM;gBAEvD,IAAIF,gBAAgBG,OAAO,KAAK,OAAO;oBACrC,wEAAwE;oBACxE,uEAAuE;oBACvEhB,mCACEY,UAAUK,KAAK,EACfT,YACAN,gBACEC,wBAAwBS,UAAUK,KAAK,EAAET,YAAYC,QAEvDC;gBAEJ;gBACA;YACF;QACA,KAAK;YAAW;gBACd,MAAMQ,kBAAkBR,cAAcS,eAAe;gBACrD,IAAID,mBAAmBA,gBAAgBE,wBAAwB,IAAI;oBACjE,IAAIC;oBACJ,wDAAwD;oBACxD,mEAAmE;oBACnE,OAAQH,gBAAgBI,YAAY;wBAClC,KAAKrB,YAAYsB,WAAW;wBAC5B,KAAKtB,YAAYuB,MAAM;4BAAE;gCACvBH,cAAcjB,kBAAkBQ,UAAUK,KAAK,EAAET,YAAYC;gCAC7D;4BACF;wBACA,KAAKR,YAAYwB,YAAY;wBAC7B,KAAKxB,YAAYyB,OAAO;4BAAE;gCACxB,8BAA8B;gCAC9B,8FAA8F;gCAC9FL,cAAchB,yBACZO,UAAUK,KAAK,EACfT,YACAC;gCAEF;4BACF;wBACA,KAAKR,YAAY0B,MAAM;wBACvB,KAAK1B,YAAY2B,OAAO;wBACxB,KAAK3B,YAAY4B,SAAS;4BAAE;gCAC1B,MAAM,qBAEL,CAFK,IAAIvB,eACR,CAAC,6EAA6E,EAAEL,WAAW,CAACiB,gBAAgBI,YAAY,CAAC,EAAE,GADvH,qBAAA;2CAAA;gDAAA;kDAAA;gCAEN;4BACF;oBACF;oBAEAD,cAAcnB,gBAAgBmB;oBAC9BH,gBAAgBY,mCAAmC,CAACT;oBAEpD,yEAAyE;oBACzE,0FAA0F;oBAC1F,IACEX,cAAcI,UAAU,IACxB,CAACJ,cAAcI,UAAU,CAACC,MAAM,CAACC,OAAO,EACxC;wBACAN,cAAcI,UAAU,CAACiB,KAAK,CAACV;oBACjC;gBACF;gBACA;YACF;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEX;IACJ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/node-environment-extensions/io-utils.tsx"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport {\n createSyncIOClientError,\n createSyncIOError,\n createSyncIORuntimeError,\n type SyncIOApiType,\n} from '../app-render/sync-io-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function io(expression: string, type: SyncIOApiType) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const workStore = workAsyncStorage.getStore()\n\n if (!workUnitStore || !workStore) {\n return\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(createSyncIOError(workStore.route, expression, type)),\n workUnitStore\n )\n }\n break\n }\n case 'prerender-client': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(\n createSyncIOClientError(workStore.route, expression, type)\n ),\n workUnitStore\n )\n }\n break\n }\n case 'request': {\n const stageController = workUnitStore.stagedRendering\n if (stageController && stageController.shouldTrackSyncInterrupt()) {\n let syncIOError: Error\n // NOTE: keep stages where we can interrupt in sync with\n // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`\n switch (stageController.currentStage) {\n case RenderStage.ShellStatic:\n case RenderStage.Static: {\n syncIOError = createSyncIOError(workStore.route, expression, type)\n break\n }\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n // We're in the Runtime stage.\n // We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.\n syncIOError = createSyncIORuntimeError(\n workStore.route,\n expression,\n type\n )\n break\n }\n case RenderStage.Before:\n case RenderStage.Dynamic:\n case RenderStage.Abandoned: {\n throw new InvariantError(\n `shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${RenderStage[stageController.currentStage]}`\n )\n }\n }\n\n syncIOError = applyOwnerStack(syncIOError)\n stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n // A validation render uses a 'request' store type, but may be abortable.\n // If we're rendering with filled caches, Sync IO is an error and should trigger an abort.\n if (\n workUnitStore.controller &&\n !workUnitStore.controller.signal.aborted\n ) {\n workUnitStore.controller.abort(syncIOError)\n }\n }\n break\n }\n case 'validation-client':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","abortOnSynchronousPlatformIOAccess","RenderStage","applyOwnerStack","createSyncIOClientError","createSyncIOError","createSyncIORuntimeError","InvariantError","io","expression","type","workUnitStore","getStore","workStore","prerenderSignal","controller","signal","aborted","route","stageController","stagedRendering","shouldTrackSyncInterrupt","syncIOError","currentStage","ShellStatic","Static","ShellRuntime","Runtime","Before","Dynamic","Abandoned","syncInterruptCurrentStageWithReason","abort"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,kCAAkC,QAAQ,kCAAiC;AACpF,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,wBAAwB,QAEnB,iCAAgC;AACvC,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC,GAAGC,UAAkB,EAAEC,IAAmB;IACxD,MAAMC,gBAAgBX,qBAAqBY,QAAQ;IACnD,MAAMC,YAAYd,iBAAiBa,QAAQ;IAE3C,IAAI,CAACD,iBAAiB,CAACE,WAAW;QAChC;IACF;IAEA,OAAQF,cAAcD,IAAI;QACxB,KAAK;QACL,KAAK;YAAqB;gBACxB,MA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BAAgBmB;oBAC9BH,gBAAgBY,mCAAmC,CAACT;oBAEpD,yEAAyE;oBACzE,0FAA0F;oBAC1F,IACEX,cAAcI,UAAU,IACxB,CAACJ,cAAcI,UAAU,CAACC,MAAM,CAACC,OAAO,EACxC;wBACAN,cAAcI,UAAU,CAACiB,KAAK,CAACV;oBACjC;gBACF;gBACA;YACF;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEX;IACJ;AACF","ignoreList":[0]}

@@ -1,2 +0,1 @@

import { isPostpone } from '../lib/router-utils/is-postpone';
import * as Log from '../../build/output/log';

@@ -9,7 +8,2 @@ let _global = globalThis;

function unhandledRejectionListener(reason) {
if (isPostpone(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return;
}
// Immediately log the error.

@@ -35,5 +29,5 @@ // TODO: Ideally, if we knew that this error was triggered by application

* Registers the Next.js unhandled rejection listener, which logs unhandled
* rejections (except React postpones) and prevents them from crashing the
* process. Safe to call unconditionally: if the listener is already attached,
* this is a no-op, so it never registers a duplicate.
* rejections and prevents them from crashing the process. Safe to call
* unconditionally: if the listener is already attached, this is a no-op, so it
* never registers a duplicate.
*/ export function registerUnhandledRejectionListener() {

@@ -101,5 +95,2 @@ if (isUnhandledRejectionListenerRegistered()) {

process.on('uncaughtException', (reason)=>{
if (isPostpone(reason)) {
return;
}
console.error(reason);

@@ -106,0 +97,0 @@ });

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/node-environment-extensions/process-error-handlers.ts"],"sourcesContent":["import { isPostpone } from '../lib/router-utils/is-postpone'\nimport * as Log from '../../build/output/log'\n\nlet _global = globalThis as typeof globalThis & {\n nextInitializedProcessErrorHandlers?: boolean\n [UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener\n}\n\n// The listener function is shared via globalThis so that multiple copies of\n// this module (e.g. in the pre-compiled server bundle and in a route module\n// bundle) still register and detect a single listener instance.\nconst UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(\n 'next.unhandledRejectionListener'\n)\n\nfunction unhandledRejectionListener(reason: unknown) {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n // Immediately log the error.\n // TODO: Ideally, if we knew that this error was triggered by application\n // code, we would suppress it entirely without logging. We can't reliably\n // detect all of these, but when cacheComponents is enabled, we could suppress\n // at least some of them by waiting to log the error until after all in-\n // progress renders have completed. Then, only log errors for which there\n // was not a corresponding \"rejectionHandled\" event.\n Log.error('unhandledRejection:', reason)\n}\n\n/**\n * Checks if the Next.js unhandled rejection listener is currently attached.\n * This queries the actual process listeners instead of relying on a module\n * global, so it stays accurate even if the listener was removed externally,\n * e.g. via `process.removeAllListeners('unhandledRejection')`.\n */\nexport function isUnhandledRejectionListenerRegistered(): boolean {\n const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]\n\n return (\n listener !== undefined &&\n process.listeners('unhandledRejection').includes(listener)\n )\n}\n\n/**\n * Registers the Next.js unhandled rejection listener, which logs unhandled\n * rejections (except React postpones) and prevents them from crashing the\n * process. Safe to call unconditionally: if the listener is already attached,\n * this is a no-op, so it never registers a duplicate.\n */\nexport function registerUnhandledRejectionListener(): void {\n if (isUnhandledRejectionListenerRegistered()) {\n return\n }\n\n const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=\n unhandledRejectionListener)\n\n process.on('unhandledRejection', listener)\n}\n\nexport function installProcessErrorHandlers(\n shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n if (!_global.nextInitializedProcessErrorHandlers) {\n _global.nextInitializedProcessErrorHandlers = true\n // The conventional wisdom of Node.js and other runtimes is to treat\n // unhandled errors as fatal and exit the process.\n //\n // But Next.js is not a generic JS runtime — it's a specialized runtime for\n // React Server Components.\n //\n // Many unhandled rejections are due to the late-awaiting pattern for\n // prefetching data. In Next.js it's OK to call an async function without\n // immediately awaiting it, to start the request as soon as possible\n // without blocking unncessarily on the result. These can end up\n // triggering an \"unhandledRejection\" if it later turns out that the\n // data is not needed to render the page. Example:\n //\n // const promise = fetchData()\n // const shouldShow = await checkCondition()\n // if (shouldShow) {\n // return <Component promise={promise} />\n // }\n //\n // In this example, `fetchData` is called immediately to start the request\n // as soon as possible, but if `shouldShow` is false, then it will be\n // discarded without unwrapping its result. If it errors, it will trigger\n // an \"unhandledRejection\" event.\n //\n // Ideally, we would suppress these rejections completely without warning,\n // because we don't consider them real errors. (TODO: Currently we do warn.)\n //\n // But regardless of whether we do or don't warn, we definitely shouldn't\n // crash the entire process.\n //\n // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n // prevent the rest of the page from rendering.\n //\n // So, we're going to intentionally override the default error handling\n // behavior of the outer JS runtime to be more forgiving\n\n // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n // This is gated behind an experimental flag until we've considered the impact\n // in various deployment environments. It's possible this may always need to\n // be configurable.\n if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n process.removeAllListeners('uncaughtException')\n process.removeAllListeners('unhandledRejection')\n }\n\n process.on('rejectionHandled', () => {\n // TODO: See note in the unhandledRejection listener above. In the\n // future, we may use the \"rejectionHandled\" event to de-queue an error\n // from being logged.\n })\n\n // Unhandled exceptions are errors triggered by non-async functions, so this\n // is unrelated to the late-awaiting pattern. However, for similar reasons,\n // we still shouldn't crash the process. Just log it.\n process.on('uncaughtException', (reason: unknown) => {\n if (isPostpone(reason)) {\n return\n }\n console.error(reason)\n })\n }\n\n // Register the listener unconditionally, and not only during the guarded\n // initialization above: a previous registration may have been undone by the\n // `removeAllListeners` call of a later `installProcessErrorHandlers` call\n // (or by external code), and registering is a no-op if the listener is\n // still attached.\n registerUnhandledRejectionListener()\n}\n"],"names":["isPostpone","Log","_global","globalThis","UNHANDLED_REJECTION_LISTENER_KEY","Symbol","for","unhandledRejectionListener","reason","error","isUnhandledRejectionListenerRegistered","listener","undefined","process","listeners","includes","registerUnhandledRejectionListener","on","installProcessErrorHandlers","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","console"],"mappings":"AAAA,SAASA,UAAU,QAAQ,kCAAiC;AAC5D,YAAYC,SAAS,yBAAwB;AAE7C,IAAIC,UAAUC;AAKd,4EAA4E;AAC5E,4EAA4E;AAC5E,gEAAgE;AAChE,MAAMC,mCAAmCC,OAAOC,GAAG,CACjD;AAGF,SAASC,2BAA2BC,MAAe;IACjD,IAAIR,WAAWQ,SAAS;QACtB,0EAA0E;QAC1E,qDAAqD;QACrD;IACF;IACA,6BAA6B;IAC7B,yEAAyE;IACzE,yEAAyE;IACzE,8EAA8E;IAC9E,wEAAwE;IACxE,yEAAyE;IACzE,oDAAoD;IACpDP,IAAIQ,KAAK,CAAC,uBAAuBD;AACnC;AAEA;;;;;CAKC,GACD,OAAO,SAASE;IACd,MAAMC,WAAWT,OAAO,CAACE,iCAAiC;IAE1D,OACEO,aAAaC,aACbC,QAAQC,SAAS,CAAC,sBAAsBC,QAAQ,CAACJ;AAErD;AAEA;;;;;CAKC,GACD,OAAO,SAASK;IACd,IAAIN,0CAA0C;QAC5C;IACF;IAEA,MAAMC,WAAYT,OAAO,CAACE,iCAAiC,KACzDG;IAEFM,QAAQI,EAAE,CAAC,sBAAsBN;AACnC;AAEA,OAAO,SAASO,4BACdC,8CAAuD;IAEvD,IAAI,CAACjB,QAAQkB,mCAAmC,EAAE;QAChDlB,QAAQkB,mCAAmC,GAAG;QAC9C,oEAAoE;QACpE,kDAAkD;QAClD,EAAE;QACF,2EAA2E;QAC3E,2BAA2B;QAC3B,EAAE;QACF,qEAAqE;QACrE,yEAAyE;QACzE,oEAAoE;QACpE,gEAAgE;QAChE,oEAAoE;QACpE,kDAAkD;QAClD,EAAE;QACF,kCAAkC;QAClC,gDAAgD;QAChD,wBAAwB;QACxB,+CAA+C;QAC/C,QAAQ;QACR,EAAE;QACF,0EAA0E;QAC1E,qEAAqE;QACrE,yEAAyE;QACzE,iCAAiC;QACjC,EAAE;QACF,0EAA0E;QAC1E,4EAA4E;QAC5E,EAAE;QACF,yEAAyE;QACzE,4BAA4B;QAC5B,EAAE;QACF,oEAAoE;QACpE,+CAA+C;QAC/C,EAAE;QACF,uEAAuE;QACvE,wDAAwD;QAExD,6EAA6E;QAC7E,8EAA8E;QAC9E,4EAA4E;QAC5E,mBAAmB;QACnB,IAAID,gDAAgD;YAClDN,QAAQQ,kBAAkB,CAAC;YAC3BR,QAAQQ,kBAAkB,CAAC;QAC7B;QAEAR,QAAQI,EAAE,CAAC,oBAAoB;QAC7B,kEAAkE;QAClE,uEAAuE;QACvE,qBAAqB;QACvB;QAEA,4EAA4E;QAC5E,2EAA2E;QAC3E,qDAAqD;QACrDJ,QAAQI,EAAE,CAAC,qBAAqB,CAACT;YAC/B,IAAIR,WAAWQ,SAAS;gBACtB;YACF;YACAc,QAAQb,KAAK,CAACD;QAChB;IACF;IAEA,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,uEAAuE;IACvE,kBAAkB;IAClBQ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/node-environment-extensions/process-error-handlers.ts"],"sourcesContent":["import * as Log from '../../build/output/log'\n\nlet _global = globalThis as typeof globalThis & {\n nextInitializedProcessErrorHandlers?: boolean\n [UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener\n}\n\n// The listener function is shared via globalThis so that multiple copies of\n// this module (e.g. in the pre-compiled server bundle and in a route module\n// bundle) still register and detect a single listener instance.\nconst UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(\n 'next.unhandledRejectionListener'\n)\n\nfunction unhandledRejectionListener(reason: unknown) {\n // Immediately log the error.\n // TODO: Ideally, if we knew that this error was triggered by application\n // code, we would suppress it entirely without logging. We can't reliably\n // detect all of these, but when cacheComponents is enabled, we could suppress\n // at least some of them by waiting to log the error until after all in-\n // progress renders have completed. Then, only log errors for which there\n // was not a corresponding \"rejectionHandled\" event.\n Log.error('unhandledRejection:', reason)\n}\n\n/**\n * Checks if the Next.js unhandled rejection listener is currently attached.\n * This queries the actual process listeners instead of relying on a module\n * global, so it stays accurate even if the listener was removed externally,\n * e.g. via `process.removeAllListeners('unhandledRejection')`.\n */\nexport function isUnhandledRejectionListenerRegistered(): boolean {\n const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]\n\n return (\n listener !== undefined &&\n process.listeners('unhandledRejection').includes(listener)\n )\n}\n\n/**\n * Registers the Next.js unhandled rejection listener, which logs unhandled\n * rejections and prevents them from crashing the process. Safe to call\n * unconditionally: if the listener is already attached, this is a no-op, so it\n * never registers a duplicate.\n */\nexport function registerUnhandledRejectionListener(): void {\n if (isUnhandledRejectionListenerRegistered()) {\n return\n }\n\n const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=\n unhandledRejectionListener)\n\n process.on('unhandledRejection', listener)\n}\n\nexport function installProcessErrorHandlers(\n shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n if (!_global.nextInitializedProcessErrorHandlers) {\n _global.nextInitializedProcessErrorHandlers = true\n // The conventional wisdom of Node.js and other runtimes is to treat\n // unhandled errors as fatal and exit the process.\n //\n // But Next.js is not a generic JS runtime — it's a specialized runtime for\n // React Server Components.\n //\n // Many unhandled rejections are due to the late-awaiting pattern for\n // prefetching data. In Next.js it's OK to call an async function without\n // immediately awaiting it, to start the request as soon as possible\n // without blocking unncessarily on the result. These can end up\n // triggering an \"unhandledRejection\" if it later turns out that the\n // data is not needed to render the page. Example:\n //\n // const promise = fetchData()\n // const shouldShow = await checkCondition()\n // if (shouldShow) {\n // return <Component promise={promise} />\n // }\n //\n // In this example, `fetchData` is called immediately to start the request\n // as soon as possible, but if `shouldShow` is false, then it will be\n // discarded without unwrapping its result. If it errors, it will trigger\n // an \"unhandledRejection\" event.\n //\n // Ideally, we would suppress these rejections completely without warning,\n // because we don't consider them real errors. (TODO: Currently we do warn.)\n //\n // But regardless of whether we do or don't warn, we definitely shouldn't\n // crash the entire process.\n //\n // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n // prevent the rest of the page from rendering.\n //\n // So, we're going to intentionally override the default error handling\n // behavior of the outer JS runtime to be more forgiving\n\n // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n // This is gated behind an experimental flag until we've considered the impact\n // in various deployment environments. It's possible this may always need to\n // be configurable.\n if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n process.removeAllListeners('uncaughtException')\n process.removeAllListeners('unhandledRejection')\n }\n\n process.on('rejectionHandled', () => {\n // TODO: See note in the unhandledRejection listener above. In the\n // future, we may use the \"rejectionHandled\" event to de-queue an error\n // from being logged.\n })\n\n // Unhandled exceptions are errors triggered by non-async functions, so this\n // is unrelated to the late-awaiting pattern. However, for similar reasons,\n // we still shouldn't crash the process. Just log it.\n process.on('uncaughtException', (reason: unknown) => {\n console.error(reason)\n })\n }\n\n // Register the listener unconditionally, and not only during the guarded\n // initialization above: a previous registration may have been undone by the\n // `removeAllListeners` call of a later `installProcessErrorHandlers` call\n // (or by external code), and registering is a no-op if the listener is\n // still attached.\n registerUnhandledRejectionListener()\n}\n"],"names":["Log","_global","globalThis","UNHANDLED_REJECTION_LISTENER_KEY","Symbol","for","unhandledRejectionListener","reason","error","isUnhandledRejectionListenerRegistered","listener","undefined","process","listeners","includes","registerUnhandledRejectionListener","on","installProcessErrorHandlers","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","console"],"mappings":"AAAA,YAAYA,SAAS,yBAAwB;AAE7C,IAAIC,UAAUC;AAKd,4EAA4E;AAC5E,4EAA4E;AAC5E,gEAAgE;AAChE,MAAMC,mCAAmCC,OAAOC,GAAG,CACjD;AAGF,SAASC,2BAA2BC,MAAe;IACjD,6BAA6B;IAC7B,yEAAyE;IACzE,yEAAyE;IACzE,8EAA8E;IAC9E,wEAAwE;IACxE,yEAAyE;IACzE,oDAAoD;IACpDP,IAAIQ,KAAK,CAA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B,CAACT;YAC/Bc,QAAQb,KAAK,CAACD;QAChB;IACF;IAEA,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,uEAAuE;IACvE,kBAAkB;IAClBQ;AACF","ignoreList":[0]}

@@ -464,3 +464,2 @@ /**

}
case 'prerender-ppr':
case 'prerender-legacy':

@@ -467,0 +466,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/node-environment-extensions/unhandled-rejection.external.tsx"],"sourcesContent":["/**\n * Manages unhandled rejection listeners to intelligently filter rejections\n * from aborted prerenders when cache components are enabled.\n *\n * THE PROBLEM:\n * When we abort prerenders we expect to find numerous unhandled promise rejections due to\n * things like awaiting Request data like `headers()`. The rejections are fine and should\n * not be construed as problematic so we need to avoid the appearance of a problem by\n * omitting them from the logged output.\n *\n * THE STRATEGY:\n * 1. Install a filtering unhandled rejection handler\n * 2. Intercept process event methods to capture new handlers in our internal queue\n * 3. For each rejection, check if it comes from an aborted prerender context\n * 4. If yes, suppress it. If no, delegate to all handlers in our queue\n * 5. This provides precise filtering without time-based windows\n *\n * This ensures we suppress noisy prerender-related rejections while preserving\n * normal error logging for genuine unhandled rejections.\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\nconst MODE:\n | 'enabled'\n | 'debug'\n | 'silent'\n | 'true'\n | 'false'\n | '1'\n | '0'\n | ''\n | string\n | undefined = process.env.NEXT_UNHANDLED_REJECTION_FILTER\n\nlet ENABLE_UHR_FILTER = true\nlet UHR_FILTER_LOG_LEVEL: 'debug' | 'warn' | 'silent' = 'warn'\n\nswitch (MODE) {\n case 'silent':\n UHR_FILTER_LOG_LEVEL = 'silent'\n break\n case 'debug':\n UHR_FILTER_LOG_LEVEL = 'debug'\n break\n case 'false':\n case 'disabled':\n case '0':\n ENABLE_UHR_FILTER = false\n break\n case '':\n case undefined:\n case 'enabled':\n case 'true':\n case '1':\n break\n default:\n if (typeof MODE === 'string') {\n console.error(\n `NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use \"enabled\", \"disabled\", \"silent\", or \"debug\", or omit the environment variable altogether`\n )\n }\n}\n\nlet debug: typeof console.debug | undefined\nlet debugWithTrace: typeof console.debug | undefined\nlet warn: typeof console.warn | undefined\nlet warnWithTrace: typeof console.warn | undefined\n\nswitch (UHR_FILTER_LOG_LEVEL) {\n case 'debug':\n debug = (message: string) =>\n console.log('[Next.js Unhandled Rejection Filter]: ' + message)\n debugWithTrace = (message: string) => {\n console.log(new DebugWithStack(message))\n }\n // Intentional fallthrough\n case 'warn':\n warn = (message: string) => {\n console.warn('[Next.js Unhandled Rejection Filter]: ' + message)\n }\n warnWithTrace = (message: string) => {\n console.warn(new WarnWithStack(message))\n }\n break\n case 'silent':\n default:\n}\n\nclass DebugWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nclass WarnWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nlet didWarnUninstalled = false\nconst warnUninstalledOnce = warn\n ? function warnUninstalledOnce(...args: any[]) {\n if (!didWarnUninstalled) {\n didWarnUninstalled = true\n warn(...args)\n }\n }\n : undefined\n\ntype ListenerMetadata = {\n listener: NodeJS.UnhandledRejectionListener\n once: boolean\n}\n\n// We use a global symbol to detect if the filter has already been installed.\n// If two instances of this module are loaded, each captures the other's handler\n// as an underlying listener, creating mutual recursion that overflows the stack.\n// We error defensively rather than silently degrading.\nconst FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter')\nlet filterInstalled = false\n\n// We store the proxied listeners for unhandled rejections here.\nlet underlyingListeners: Array<NodeJS.UnhandledRejectionListener> = []\n// We store a unique pointer to each event listener registration to track\n// details like whether the listener is a once listener.\nlet listenerMetadata: Array<ListenerMetadata> = []\n\n// These methods are used to restore the original implementations when uninstalling the patch\nlet originalProcessAddListener: typeof process.addListener\nlet originalProcessRemoveListener: typeof process.removeListener\nlet originalProcessOn: typeof process.on\nlet originalProcessOff: typeof process.off\nlet originalProcessPrependListener: typeof process.prependListener\nlet originalProcessOnce: typeof process.once\nlet originalProcessPrependOnceListener: typeof process.prependOnceListener\nlet originalProcessRemoveAllListeners: typeof process.removeAllListeners\nlet originalProcessListeners: typeof process.listeners\n\ntype UnderlyingMethod =\n | typeof originalProcessAddListener\n | typeof originalProcessRemoveListener\n | typeof originalProcessOn\n | typeof originalProcessOff\n | typeof originalProcessPrependListener\n | typeof originalProcessOnce\n | typeof originalProcessPrependOnceListener\n | typeof originalProcessRemoveAllListeners\n | typeof originalProcessListeners\n\n// Some of these base methods call others and we don't want them to call the patched version so we\n// need a way to synchronously disable the patch temporarily.\nlet bypassPatch = false\n\n// This patch ensures that if any patched methods end up calling other methods internally they will\n// bypass the patch during their execution. This is important for removeAllListeners in particular\n// because it calls removeListener internally and we want to ensure it actually clears the listeners\n// from the process queue and not our private queue.\nfunction patchWithoutReentrancy<T extends UnderlyingMethod>(\n original: T,\n patchedImpl: T\n): T {\n // Produce a function which has the correct name\n const patched = {\n [original.name]: function (...args: Parameters<T>) {\n if (bypassPatch) {\n return Reflect.apply(original, process, args)\n }\n\n const previousBypassPatch = bypassPatch\n bypassPatch = true\n try {\n return Reflect.apply(patchedImpl, process, args)\n } finally {\n bypassPatch = previousBypassPatch\n }\n } as any,\n }[original.name]\n\n // Preserve the original toString behavior\n Object.defineProperty(patched, 'toString', {\n value: original.toString.bind(original),\n writable: true,\n configurable: true,\n })\n\n return patched\n}\n\nconst MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'\n\n/**\n * Installs a filtering unhandled rejection handler that intelligently suppresses\n * rejections from aborted prerender contexts.\n *\n * This should be called once during server startup to install the global filter.\n */\nfunction installUnhandledRejectionFilter(): void {\n if ((globalThis as any)[FILTER_INSTALLED_KEY] || filterInstalled) {\n // Already installed by another evaluation of this module in the same\n // process (e.g., Jest's module system re-evaluating an already-loaded\n // module). Safe to skip since the filter is already active.\n return\n }\n\n debug?.('Installing Filter')\n\n // Capture existing handlers\n underlyingListeners = Array.from(process.listeners('unhandledRejection'))\n // We assume all existing handlers are not \"once\"\n listenerMetadata = underlyingListeners.map((l) => ({\n listener: l,\n once: false,\n }))\n\n // Remove all existing handlers\n process.removeAllListeners('unhandledRejection')\n\n // Install our filtering handler\n process.addListener('unhandledRejection', filteringUnhandledRejectionHandler)\n\n // Store the original process methods\n originalProcessAddListener = process.addListener\n originalProcessRemoveListener = process.removeListener\n originalProcessOn = process.on\n originalProcessOff = process.off\n originalProcessPrependListener = process.prependListener\n originalProcessOnce = process.once\n originalProcessPrependOnceListener = process.prependOnceListener\n originalProcessRemoveAllListeners = process.removeAllListeners\n originalProcessListeners = process.listeners\n\n process.addListener = patchWithoutReentrancy(\n originalProcessAddListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessAddListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessAddListener.call(process, event as any, listener)\n } as typeof process.addListener\n )\n\n // Intercept process.removeListener (alias for process.off)\n process.removeListener = patchWithoutReentrancy(\n originalProcessRemoveListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeListener('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessRemoveListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessRemoveListener.call(process, event, listener)\n } as typeof process.removeListener\n )\n\n // If the process.on is referentially process.addListener then share the patched version as well\n if (originalProcessOn === originalProcessAddListener) {\n process.on = process.addListener\n } else {\n process.on = patchWithoutReentrancy(originalProcessOn, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOn.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessOn.call(process, event, listener)\n } as typeof process.on)\n }\n\n // If the process.off is referentially process.addListener then share the patched version as well\n if (originalProcessOff === originalProcessRemoveListener) {\n process.off = process.removeListener\n } else {\n process.off = patchWithoutReentrancy(originalProcessOff, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.off('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessOff.call(process, MACGUFFIN_EVENT as any, listener)\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessOff.call(process, event, listener)\n } as typeof process.off)\n }\n\n // Intercept process.prependListener for handlers that should go first\n process.prependListener = patchWithoutReentrancy(\n originalProcessPrependListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add new handlers to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependListener\n )\n\n // Intercept process.once for one-time handlers\n process.once = patchWithoutReentrancy(originalProcessOnce, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' once-listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOnce.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessOnce.call(process, event, listener)\n } as typeof process.once)\n\n // Intercept process.prependOnceListener for one-time handlers that should go first\n process.prependOnceListener = patchWithoutReentrancy(\n originalProcessPrependOnceListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' once-listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependOnceListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependOnceListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependOnceListener\n )\n\n // Intercept process.removeAllListeners\n process.removeAllListeners = patchWithoutReentrancy(\n originalProcessRemoveAllListeners,\n function (event?: string | symbol) {\n if (event === 'unhandledRejection') {\n // TODO add warning for this case once we stop importing this in test scopes automatically. Currently\n // we pull this file in whenever build/utils.tsx is imported which is not the right layering.\n // The extensions should be loaded from entrypoints like build/index or next-server\n // warnRemoveAllOnce?.(\n // `\\`process.removeAllListeners('unhandledRejection')\\` was called. Next.js maintains the first 'unhandledRejection' listener to filter out unnecessary rejection warnings caused by aborting prerenders early. It is not recommended that you uninstall this behavior, but if you want to you must you can acquire the listener with \\`process.listeners('unhandledRejection')[0]\\` and remove it with \\`process.removeListener('unhandledRejection', listener)\\`.\n\n // You can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\n // You can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n // )\n debugWithTrace?.(\n `Removing all 'unhandledRejection' listeners except for the Next.js filter.`\n )\n\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n return process\n }\n\n // For other specific events, use the original method\n if (event !== undefined) {\n return originalProcessRemoveAllListeners.call(process, event)\n }\n\n // If no event specified (removeAllListeners()), uninstall our patch completely\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeAllListeners()\\` was called. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return originalProcessRemoveAllListeners.call(process)\n } as typeof process.removeAllListeners\n )\n\n // Intercept process.listeners to return our internal handlers for unhandled rejection\n process.listeners = patchWithoutReentrancy(\n originalProcessListeners,\n function (event: string | symbol) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(`Retrieving all 'unhandledRejection' listeners.`)\n return [filteringUnhandledRejectionHandler, ...underlyingListeners]\n }\n return originalProcessListeners.call(process, event as any)\n } as typeof process.listeners\n )\n\n filterInstalled = true\n ;(globalThis as any)[FILTER_INSTALLED_KEY] = true\n}\n\n/**\n * Uninstalls the unhandled rejection filter and restores original process methods.\n * This is called when someone explicitly removes our filtering handler.\n * @internal\n */\nfunction uninstallUnhandledRejectionFilter(): void {\n if (!filterInstalled) {\n warnWithTrace?.(\n 'Unexpected subsequent filter uninstallation. This is a bug in Next.js'\n )\n return\n }\n\n debug?.('Uninstalling Filter')\n\n // Restore original process methods\n process.on = originalProcessOn\n process.addListener = originalProcessAddListener\n process.once = originalProcessOnce\n process.prependListener = originalProcessPrependListener\n process.prependOnceListener = originalProcessPrependOnceListener\n process.removeListener = originalProcessRemoveListener\n process.off = originalProcessOff\n process.removeAllListeners = originalProcessRemoveAllListeners\n process.listeners = originalProcessListeners\n\n // Remove our filtering handler\n process.removeListener(\n 'unhandledRejection',\n filteringUnhandledRejectionHandler\n )\n\n // Re-register all the handlers that were in our internal queue\n for (const meta of listenerMetadata) {\n if (meta.once) {\n process.once('unhandledRejection', meta.listener)\n } else {\n process.addListener('unhandledRejection', meta.listener)\n }\n }\n\n // Reset state\n filterInstalled = false\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n}\n\n/**\n * The filtering handler that decides whether to suppress or delegate unhandled rejections.\n */\nlet handlingRejection = false\n\nfunction filteringUnhandledRejectionHandler(\n reason: any,\n promise: Promise<any>\n): void {\n if (handlingRejection) {\n // An underlying listener synchronously re-emitted 'unhandledRejection'.\n // Re-entering the listener loop would overflow the stack.\n return\n }\n\n const capturedListenerMetadata = Array.from(listenerMetadata)\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'request': {\n const signal = workUnitStore.renderSignal\n if (signal && signal.aborted) {\n // This unhandledRejection is from async work spawned in a now\n // aborted prerender. We don't need to report this.\n return\n }\n break\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n // Not from an aborted prerender, delegate to original handlers\n if (capturedListenerMetadata.length === 0) {\n // We need to log something because the default behavior when there is\n // no event handler installed is to trigger an Unhandled Exception.\n // We don't do that here b/c we don't want to rely on this implicit default\n // to kill the process since it can be disabled by installing a userland listener\n // and you may also choose to run Next.js with args such that unhandled rejections\n // do not automatically terminate the process.\n console.error('Unhandled Rejection:', reason)\n } else {\n handlingRejection = true\n try {\n for (const meta of capturedListenerMetadata) {\n if (meta.once) {\n // This is a once listener. we remove it from our set before we call it\n const index = listenerMetadata.indexOf(meta)\n if (index !== -1) {\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n }\n }\n const listener = meta.listener\n listener(reason, promise)\n }\n } catch (error) {\n // If any handlers error we produce an Uncaught Exception\n setImmediate(() => {\n throw error\n })\n } finally {\n handlingRejection = false\n }\n }\n}\n\n// Install the filter when this module is imported\nif (ENABLE_UHR_FILTER) {\n installUnhandledRejectionFilter()\n}\n"],"names":["workUnitAsyncStorage","MODE","process","env","NEXT_UNHANDLED_REJECTION_FILTER","ENABLE_UHR_FILTER","UHR_FILTER_LOG_LEVEL","undefined","console","error","JSON","stringify","debug","debugWithTrace","warn","warnWithTrace","message","log","DebugWithStack","WarnWithStack","Error","constructor","name","didWarnUninstalled","warnUninstalledOnce","args","FILTER_INSTALLED_KEY","Symbol","for","filterInstalled","underlyingListeners","listenerMetadata","originalProcessAddListener","originalProcessRemoveListener","originalProcessOn","originalProcessOff","originalProcessPrependListener","originalProcessOnce","originalProcessPrependOnceListener","originalProcessRemoveAllListeners","originalProcessListeners","bypassPatch","patchWithoutReentrancy","original","patchedImpl","patched","Reflect","apply","previousBypassPatch","Object","defineProperty","value","toString","bind","writable","configurable","MACGUFFIN_EVENT","installUnhandledRejectionFilter","globalThis","Array","from","listeners","map","l","listener","once","removeAllListeners","addListener","filteringUnhandledRejectionHandler","removeListener","on","off","prependListener","prependOnceListener","event","call","push","uninstallUnhandledRejectionFilter","index","lastIndexOf","splice","unshift","length","meta","handlingRejection","reason","promise","capturedListenerMetadata","workUnitStore","getStore","type","signal","renderSignal","aborted","indexOf","setImmediate"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC,GAED,SAASA,oBAAoB,QAAQ,iDAAgD;AAErF,MAAMC,OAUUC,QAAQC,GAAG,CAACC,+BAA+B;AAE3D,IAAIC,oBAAoB;AACxB,IAAIC,uBAAoD;AAExD,OAAQL;IACN,KAAK;QACHK,uBAAuB;QACvB;IACF,KAAK;QACHA,uBAAuB;QACvB;IACF,KAAK;IACL,KAAK;IACL,KAAK;QACHD,oBAAoB;QACpB;IACF,KAAK;IACL,KAAKE;IACL,KAAK;IACL,KAAK;IACL,KAAK;QACH;IACF;QACE,IAAI,OAAON,SAAS,UAAU;YAC5BO,QAAQC,KAAK,CACX,CAAC,2DAA2D,EAAEC,KAAKC,SAAS,CAACV,MAAM,8FAA8F,CAAC;QAEtL;AACJ;AAEA,IAAIW;AACJ,IAAIC;AACJ,IAAIC;AACJ,IAAIC;AAEJ,OAAQT;IACN,KAAK;QACHM,QAAQ,CAACI,UACPR,QAAQS,GAAG,CAAC,2CAA2CD;QACzDH,iBAAiB,CAACG;YAChBR,QAAQS,GAAG,CAAC,IAAIC,eAAeF;QACjC;IACF,0BAA0B;IAC1B,KAAK;QACHF,OAAO,CAACE;YACNR,QAAQM,IAAI,CAAC,2CAA2CE;QAC1D;QACAD,gBAAgB,CAACC;YACfR,QAAQM,IAAI,CAAC,IAAIK,cAAcH;QACjC;QACA;IACF,KAAK;IACL;AACF;AAEA,MAAME,uBAAuBE;IAC3BC,YAAYL,OAAe,CAAE;QAC3B,KAAK,CAACA;QAAN,qBAAc,CAAd,IAAc,EAAd,qBAAA;mBAAA;wBAAA;0BAAA;QAAa;QACb,IAAI,CAACM,IAAI,GAAG;IACd;AACF;AAEA,MAA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,UAAUA,OAAOE,OAAO,EAAE;wBAC5B,8DAA8D;wBAC9D,mDAAmD;wBACnD;oBACF;oBACA;gBACF;YACA,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEL;QACJ;IACF;IAEA,+DAA+D;IAC/D,IAAID,yBAAyBL,MAAM,KAAK,GAAG;QACzC,sEAAsE;QACtE,mEAAmE;QACnE,2EAA2E;QAC3E,iFAAiF;QACjF,kFAAkF;QAClF,8CAA8C;QAC9C1E,QAAQC,KAAK,CAAC,wBAAwB4E;IACxC,OAAO;QACLD,oBAAoB;QACpB,IAAI;YACF,KAAK,MAAMD,QAAQI,yBAA0B;gBAC3C,IAAIJ,KAAKlB,IAAI,EAAE;oBACb,uEAAuE;oBACvE,MAAMa,QAAQ/C,iBAAiB+D,OAAO,CAACX;oBACvC,IAAIL,UAAU,CAAC,GAAG;wBAChBhD,oBAAoBkD,MAAM,CAACF,OAAO;wBAClC/C,iBAAiBiD,MAAM,CAACF,OAAO;oBACjC;gBACF;gBACA,MAAMd,WAAWmB,KAAKnB,QAAQ;gBAC9BA,SAASqB,QAAQC;YACnB;QACF,EAAE,OAAO7E,OAAO;YACd,yDAAyD;YACzDsF,aAAa;gBACX,MAAMtF;YACR;QACF,SAAU;YACR2E,oBAAoB;QACtB;IACF;AACF;AAEA,kDAAkD;AAClD,IAAI/E,mBAAmB;IACrBoD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/node-environment-extensions/unhandled-rejection.external.tsx"],"sourcesContent":["/**\n * Manages unhandled rejection listeners to intelligently filter rejections\n * from aborted prerenders when cache components are enabled.\n *\n * THE PROBLEM:\n * When we abort prerenders we expect to find numerous unhandled promise rejections due to\n * things like awaiting Request data like `headers()`. The rejections are fine and should\n * not be construed as problematic so we need to avoid the appearance of a problem by\n * omitting them from the logged output.\n *\n * THE STRATEGY:\n * 1. Install a filtering unhandled rejection handler\n * 2. Intercept process event methods to capture new handlers in our internal queue\n * 3. For each rejection, check if it comes from an aborted prerender context\n * 4. If yes, suppress it. If no, delegate to all handlers in our queue\n * 5. This provides precise filtering without time-based windows\n *\n * This ensures we suppress noisy prerender-related rejections while preserving\n * normal error logging for genuine unhandled rejections.\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\nconst MODE:\n | 'enabled'\n | 'debug'\n | 'silent'\n | 'true'\n | 'false'\n | '1'\n | '0'\n | ''\n | string\n | undefined = process.env.NEXT_UNHANDLED_REJECTION_FILTER\n\nlet ENABLE_UHR_FILTER = true\nlet UHR_FILTER_LOG_LEVEL: 'debug' | 'warn' | 'silent' = 'warn'\n\nswitch (MODE) {\n case 'silent':\n UHR_FILTER_LOG_LEVEL = 'silent'\n break\n case 'debug':\n UHR_FILTER_LOG_LEVEL = 'debug'\n break\n case 'false':\n case 'disabled':\n case '0':\n ENABLE_UHR_FILTER = false\n break\n case '':\n case undefined:\n case 'enabled':\n case 'true':\n case '1':\n break\n default:\n if (typeof MODE === 'string') {\n console.error(\n `NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use \"enabled\", \"disabled\", \"silent\", or \"debug\", or omit the environment variable altogether`\n )\n }\n}\n\nlet debug: typeof console.debug | undefined\nlet debugWithTrace: typeof console.debug | undefined\nlet warn: typeof console.warn | undefined\nlet warnWithTrace: typeof console.warn | undefined\n\nswitch (UHR_FILTER_LOG_LEVEL) {\n case 'debug':\n debug = (message: string) =>\n console.log('[Next.js Unhandled Rejection Filter]: ' + message)\n debugWithTrace = (message: string) => {\n console.log(new DebugWithStack(message))\n }\n // Intentional fallthrough\n case 'warn':\n warn = (message: string) => {\n console.warn('[Next.js Unhandled Rejection Filter]: ' + message)\n }\n warnWithTrace = (message: string) => {\n console.warn(new WarnWithStack(message))\n }\n break\n case 'silent':\n default:\n}\n\nclass DebugWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nclass WarnWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nlet didWarnUninstalled = false\nconst warnUninstalledOnce = warn\n ? function warnUninstalledOnce(...args: any[]) {\n if (!didWarnUninstalled) {\n didWarnUninstalled = true\n warn(...args)\n }\n }\n : undefined\n\ntype ListenerMetadata = {\n listener: NodeJS.UnhandledRejectionListener\n once: boolean\n}\n\n// We use a global symbol to detect if the filter has already been installed.\n// If two instances of this module are loaded, each captures the other's handler\n// as an underlying listener, creating mutual recursion that overflows the stack.\n// We error defensively rather than silently degrading.\nconst FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter')\nlet filterInstalled = false\n\n// We store the proxied listeners for unhandled rejections here.\nlet underlyingListeners: Array<NodeJS.UnhandledRejectionListener> = []\n// We store a unique pointer to each event listener registration to track\n// details like whether the listener is a once listener.\nlet listenerMetadata: Array<ListenerMetadata> = []\n\n// These methods are used to restore the original implementations when uninstalling the patch\nlet originalProcessAddListener: typeof process.addListener\nlet originalProcessRemoveListener: typeof process.removeListener\nlet originalProcessOn: typeof process.on\nlet originalProcessOff: typeof process.off\nlet originalProcessPrependListener: typeof process.prependListener\nlet originalProcessOnce: typeof process.once\nlet originalProcessPrependOnceListener: typeof process.prependOnceListener\nlet originalProcessRemoveAllListeners: typeof process.removeAllListeners\nlet originalProcessListeners: typeof process.listeners\n\ntype UnderlyingMethod =\n | typeof originalProcessAddListener\n | typeof originalProcessRemoveListener\n | typeof originalProcessOn\n | typeof originalProcessOff\n | typeof originalProcessPrependListener\n | typeof originalProcessOnce\n | typeof originalProcessPrependOnceListener\n | typeof originalProcessRemoveAllListeners\n | typeof originalProcessListeners\n\n// Some of these base methods call others and we don't want them to call the patched version so we\n// need a way to synchronously disable the patch temporarily.\nlet bypassPatch = false\n\n// This patch ensures that if any patched methods end up calling other methods internally they will\n// bypass the patch during their execution. This is important for removeAllListeners in particular\n// because it calls removeListener internally and we want to ensure it actually clears the listeners\n// from the process queue and not our private queue.\nfunction patchWithoutReentrancy<T extends UnderlyingMethod>(\n original: T,\n patchedImpl: T\n): T {\n // Produce a function which has the correct name\n const patched = {\n [original.name]: function (...args: Parameters<T>) {\n if (bypassPatch) {\n return Reflect.apply(original, process, args)\n }\n\n const previousBypassPatch = bypassPatch\n bypassPatch = true\n try {\n return Reflect.apply(patchedImpl, process, args)\n } finally {\n bypassPatch = previousBypassPatch\n }\n } as any,\n }[original.name]\n\n // Preserve the original toString behavior\n Object.defineProperty(patched, 'toString', {\n value: original.toString.bind(original),\n writable: true,\n configurable: true,\n })\n\n return patched\n}\n\nconst MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'\n\n/**\n * Installs a filtering unhandled rejection handler that intelligently suppresses\n * rejections from aborted prerender contexts.\n *\n * This should be called once during server startup to install the global filter.\n */\nfunction installUnhandledRejectionFilter(): void {\n if ((globalThis as any)[FILTER_INSTALLED_KEY] || filterInstalled) {\n // Already installed by another evaluation of this module in the same\n // process (e.g., Jest's module system re-evaluating an already-loaded\n // module). Safe to skip since the filter is already active.\n return\n }\n\n debug?.('Installing Filter')\n\n // Capture existing handlers\n underlyingListeners = Array.from(process.listeners('unhandledRejection'))\n // We assume all existing handlers are not \"once\"\n listenerMetadata = underlyingListeners.map((l) => ({\n listener: l,\n once: false,\n }))\n\n // Remove all existing handlers\n process.removeAllListeners('unhandledRejection')\n\n // Install our filtering handler\n process.addListener('unhandledRejection', filteringUnhandledRejectionHandler)\n\n // Store the original process methods\n originalProcessAddListener = process.addListener\n originalProcessRemoveListener = process.removeListener\n originalProcessOn = process.on\n originalProcessOff = process.off\n originalProcessPrependListener = process.prependListener\n originalProcessOnce = process.once\n originalProcessPrependOnceListener = process.prependOnceListener\n originalProcessRemoveAllListeners = process.removeAllListeners\n originalProcessListeners = process.listeners\n\n process.addListener = patchWithoutReentrancy(\n originalProcessAddListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessAddListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessAddListener.call(process, event as any, listener)\n } as typeof process.addListener\n )\n\n // Intercept process.removeListener (alias for process.off)\n process.removeListener = patchWithoutReentrancy(\n originalProcessRemoveListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeListener('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessRemoveListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessRemoveListener.call(process, event, listener)\n } as typeof process.removeListener\n )\n\n // If the process.on is referentially process.addListener then share the patched version as well\n if (originalProcessOn === originalProcessAddListener) {\n process.on = process.addListener\n } else {\n process.on = patchWithoutReentrancy(originalProcessOn, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOn.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessOn.call(process, event, listener)\n } as typeof process.on)\n }\n\n // If the process.off is referentially process.addListener then share the patched version as well\n if (originalProcessOff === originalProcessRemoveListener) {\n process.off = process.removeListener\n } else {\n process.off = patchWithoutReentrancy(originalProcessOff, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.off('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessOff.call(process, MACGUFFIN_EVENT as any, listener)\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessOff.call(process, event, listener)\n } as typeof process.off)\n }\n\n // Intercept process.prependListener for handlers that should go first\n process.prependListener = patchWithoutReentrancy(\n originalProcessPrependListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add new handlers to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependListener\n )\n\n // Intercept process.once for one-time handlers\n process.once = patchWithoutReentrancy(originalProcessOnce, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' once-listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOnce.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessOnce.call(process, event, listener)\n } as typeof process.once)\n\n // Intercept process.prependOnceListener for one-time handlers that should go first\n process.prependOnceListener = patchWithoutReentrancy(\n originalProcessPrependOnceListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' once-listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependOnceListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependOnceListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependOnceListener\n )\n\n // Intercept process.removeAllListeners\n process.removeAllListeners = patchWithoutReentrancy(\n originalProcessRemoveAllListeners,\n function (event?: string | symbol) {\n if (event === 'unhandledRejection') {\n // TODO add warning for this case once we stop importing this in test scopes automatically. Currently\n // we pull this file in whenever build/utils.tsx is imported which is not the right layering.\n // The extensions should be loaded from entrypoints like build/index or next-server\n // warnRemoveAllOnce?.(\n // `\\`process.removeAllListeners('unhandledRejection')\\` was called. Next.js maintains the first 'unhandledRejection' listener to filter out unnecessary rejection warnings caused by aborting prerenders early. It is not recommended that you uninstall this behavior, but if you want to you must you can acquire the listener with \\`process.listeners('unhandledRejection')[0]\\` and remove it with \\`process.removeListener('unhandledRejection', listener)\\`.\n\n // You can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\n // You can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n // )\n debugWithTrace?.(\n `Removing all 'unhandledRejection' listeners except for the Next.js filter.`\n )\n\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n return process\n }\n\n // For other specific events, use the original method\n if (event !== undefined) {\n return originalProcessRemoveAllListeners.call(process, event)\n }\n\n // If no event specified (removeAllListeners()), uninstall our patch completely\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeAllListeners()\\` was called. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return originalProcessRemoveAllListeners.call(process)\n } as typeof process.removeAllListeners\n )\n\n // Intercept process.listeners to return our internal handlers for unhandled rejection\n process.listeners = patchWithoutReentrancy(\n originalProcessListeners,\n function (event: string | symbol) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(`Retrieving all 'unhandledRejection' listeners.`)\n return [filteringUnhandledRejectionHandler, ...underlyingListeners]\n }\n return originalProcessListeners.call(process, event as any)\n } as typeof process.listeners\n )\n\n filterInstalled = true\n ;(globalThis as any)[FILTER_INSTALLED_KEY] = true\n}\n\n/**\n * Uninstalls the unhandled rejection filter and restores original process methods.\n * This is called when someone explicitly removes our filtering handler.\n * @internal\n */\nfunction uninstallUnhandledRejectionFilter(): void {\n if (!filterInstalled) {\n warnWithTrace?.(\n 'Unexpected subsequent filter uninstallation. This is a bug in Next.js'\n )\n return\n }\n\n debug?.('Uninstalling Filter')\n\n // Restore original process methods\n process.on = originalProcessOn\n process.addListener = originalProcessAddListener\n process.once = originalProcessOnce\n process.prependListener = originalProcessPrependListener\n process.prependOnceListener = originalProcessPrependOnceListener\n process.removeListener = originalProcessRemoveListener\n process.off = originalProcessOff\n process.removeAllListeners = originalProcessRemoveAllListeners\n process.listeners = originalProcessListeners\n\n // Remove our filtering handler\n process.removeListener(\n 'unhandledRejection',\n filteringUnhandledRejectionHandler\n )\n\n // Re-register all the handlers that were in our internal queue\n for (const meta of listenerMetadata) {\n if (meta.once) {\n process.once('unhandledRejection', meta.listener)\n } else {\n process.addListener('unhandledRejection', meta.listener)\n }\n }\n\n // Reset state\n filterInstalled = false\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n}\n\n/**\n * The filtering handler that decides whether to suppress or delegate unhandled rejections.\n */\nlet handlingRejection = false\n\nfunction filteringUnhandledRejectionHandler(\n reason: any,\n promise: Promise<any>\n): void {\n if (handlingRejection) {\n // An underlying listener synchronously re-emitted 'unhandledRejection'.\n // Re-entering the listener loop would overflow the stack.\n return\n }\n\n const capturedListenerMetadata = Array.from(listenerMetadata)\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'request': {\n const signal = workUnitStore.renderSignal\n if (signal && signal.aborted) {\n // This unhandledRejection is from async work spawned in a now\n // aborted prerender. We don't need to report this.\n return\n }\n break\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n // Not from an aborted prerender, delegate to original handlers\n if (capturedListenerMetadata.length === 0) {\n // We need to log something because the default behavior when there is\n // no event handler installed is to trigger an Unhandled Exception.\n // We don't do that here b/c we don't want to rely on this implicit default\n // to kill the process since it can be disabled by installing a userland listener\n // and you may also choose to run Next.js with args such that unhandled rejections\n // do not automatically terminate the process.\n console.error('Unhandled Rejection:', reason)\n } else {\n handlingRejection = true\n try {\n for (const meta of capturedListenerMetadata) {\n if (meta.once) {\n // This is a once listener. we remove it from our set before we call it\n const index = listenerMetadata.indexOf(meta)\n if (index !== -1) {\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n }\n }\n const listener = meta.listener\n listener(reason, promise)\n }\n } catch (error) {\n // If any handlers error we produce an Uncaught Exception\n setImmediate(() => {\n throw error\n })\n } finally {\n handlingRejection = false\n }\n }\n}\n\n// Install the filter when this module is imported\nif (ENABLE_UHR_FILTER) {\n installUnhandledRejectionFilter()\n}\n"],"names":["workUnitAsyncStorage","MODE","process","env","NEXT_UNHANDLED_REJECTION_FILTER","ENABLE_UHR_FILTER","UHR_FILTER_LOG_LEVEL","undefined","console","error","JSON","stringify","debug","debugWithTrace","warn","warnWithTrace","message","log","DebugWithStack","WarnWithStack","Error","constructor","name","didWarnUninstalled","warnUninstalledOnce","args","FILTER_INSTALLED_KEY","Symbol","for","filterInstalled","underlyingListeners","listenerMetadata","originalProcessAddListener","originalProcessRemoveListener","originalProcessOn","originalProcessOff","originalProcessPrependListener","originalProcessOnce","originalProcessPrependOnceListener","originalProcessRemoveAllListeners","originalProcessListeners","bypassPatch","patchWithoutReentrancy","original","patchedImpl","patched","Reflect","apply","previousBypassPatch","Object","defineProperty","value","toString","bind","writable","configurable","MACGUFFIN_EVENT","installUnhandledRejectionFilter","globalThis","Array","from","listeners","map","l","listener","once","removeAllListeners","addListener","filteringUnhandledRejectionHandler","removeListener","on","off","prependListener","prependOnceListener","event","call","push","uninstallUnhandledRejectionFilter","index","lastIndexOf","splice","unshift","length","meta","handlingRejection","reason","promise","capturedListenerMetadata","workUnitStore","getStore","type","signal","renderSignal","aborted","indexOf","setImmediate"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC,GAED,SAASA,oBAAoB,QAAQ,iDAAgD;AAErF,MAAMC,OAUUC,QAAQC,GAAG,CAACC,+BAA+B;AAE3D,IAAIC,oBAAoB;AACxB,IAAIC,uBAAoD;AAExD,OAAQL;IACN,KAAK;QACHK,uBAAuB;QACvB;IACF,KAAK;QACHA,uBAAuB;QACvB;IACF,KAAK;IACL,KAAK;IACL,KAAK;QACHD,oBAAoB;QACpB;IACF,KAAK;IACL,KAAKE;IACL,KAAK;IACL,KAAK;IACL,KAAK;QACH;IACF;QACE,IAAI,OAAON,SAAS,UAAU;YAC5BO,QAAQC,KAAK,CACX,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BAClC/C,iBAAiBiD,MAAM,CAACF,OAAO;oBACjC;gBACF;gBACA,MAAMd,WAAWmB,KAAKnB,QAAQ;gBAC9BA,SAASqB,QAAQC;YACnB;QACF,EAAE,OAAO7E,OAAO;YACd,yDAAyD;YACzDsF,aAAa;gBACX,MAAMtF;YACR;QACF,SAAU;YACR2E,oBAAoB;QACtB;IACF;AACF;AAEA,kDAAkD;AAClD,IAAI/E,mBAAmB;IACrBoD;AACF","ignoreList":[0]}

@@ -61,3 +61,2 @@ import { Readable } from 'node:stream';

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -64,0 +63,0 @@ case 'generate-static-params':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["Readable","createHash","InvariantError","workAsyncStorage","workUnitAsyncStorage","createHangingInputAbortSignal","makeDynamicHangingPromise","getClientReferenceManifest","getServerModuleMap","prerenderToNodeStream","createFromNodeStream","importOgModule","getCachedImageResponseBody","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","element","options","hangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","prelude","signal","filterStackFrame","onError","error","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","from","moduleLoading","moduleMap","serverModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,UAAU,QAAmB,cAAa;AAEnD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,6BAA6B,QAAQ,kCAAiC;AAC/E,SAASC,yBAAyB,QAAQ,6BAA4B;AACtE,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,oCAAmC;AAC1C,6DAA6D;AAC7D,SAASC,qBAAqB,QAAQ,kCAAiC;AACvE,6DAA6D;AAC7D,SAASC,oBAAoB,QAAQ,kCAAiC;AAMtE,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,2BACdC,IAAuB;IAEvB,OAAO,IAAIC,eAA2B;QACpC,MAAMC,OAAMC,UAAU;YACpB,MAAMC,cAAc,MAAMC,kCAAkCL;YAC5D,IAAII,YAAYE,UAAU,GAAG,GAAG;gBAC9BH,WAAWI,OAAO,CAAC,IAAIC,WAAWJ;YACpC;YACAD,WAAW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iC,CAACqB,IAAI;IACrE;AACF;AAEA;;;;CAIC,GACD,SAASpB,oBAAoBtB,IAAU,EAAE2C,GAAW,EAAEC,KAAiB;IACrE5C,KAAKC,MAAM,CAAC,GAAG0C,MAAMC,MAAMpF,UAAU,CAAC,CAAC,CAAC;IACxCwC,KAAKC,MAAM,CAAC2C;AACd;AAEA,eAAe5E,+BACbd,IAAuB;IAEvB,MAAM2F,kBAAkB,AAAC,CAAA,MAAM7F,gBAAe,EAAG8F,aAAa;IAC9D,MAAMC,gBAAgB,IAAIF,mBAAmB3F;IAE7C,IAAI,CAAC6F,cAAcC,IAAI,EAAE;QACvB,OAAO,IAAIxB,YAAY;IACzB;IAEA,OAAOuB,cAAczF,WAAW;AAClC;AAEA,MAAM2F,kBAAkBC,OAAOC,GAAG,CAAC;AAEnC;;;;;;CAMC,GACD,SAASpC,oBAAoBqC,IAAa;IACxC,IAAIA,SAAS,QAAQ,OAAOA,SAAS,UAAU;QAC7C,OAAOA;IACT;IAEA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAM1C,UAAU+E;IAChB,IAAI/E,QAAQqF,KAAK,IAAI,cAAcrF,QAAQqF,KAAK,EAAE;QAChD,OAAO;YACL,GAAGrF,OAAO;YACVqF,OAAO;gBACL,GAAGrF,QAAQqF,KAAK;gBAChBC,UAAU5C,oBAAoB1C,QAAQqF,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["Readable","createHash","InvariantError","workAsyncStorage","workUnitAsyncStorage","createHangingInputAbortSignal","makeDynamicHangingPromise","getClientReferenceManifest","getServerModuleMap","prerenderToNodeStream","createFromNodeStream","importOgModule","getCachedImageResponseBody","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","element","options","hangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","prelude","signal","filterStackFrame","onError","error","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","from","moduleLoading","moduleMap","serverModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,UAAU,QAAmB,cAAa;AAEnD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAAS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QAC7C,OAAOA;IACT;IAEA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAM1C,UAAU+E;IAChB,IAAI/E,QAAQqF,KAAK,IAAI,cAAcrF,QAAQqF,KAAK,EAAE;QAChD,OAAO;YACL,GAAGrF,OAAO;YACVqF,OAAO;gBACL,GAAGrF,QAAQqF,KAAK;gBAChBC,UAAU5C,oBAAoB1C,QAAQqF,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]}
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { throwForMissingRequestStore, workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';
import { postponeWithTracking, throwToInterruptStaticGeneration, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { throwToInterruptStaticGeneration, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';

@@ -96,6 +96,2 @@ import { makeDynamicHangingPromise, makeDevtoolsIOAwarePromise } from '../dynamic-rendering-utils';

}
case 'prerender-ppr':
// We use React's postpone API to interrupt rendering here to create a
// dynamic hole
return postponeWithTracking(workStore.route, 'connection', workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -102,0 +98,0 @@ // We throw an error here to interrupt prerendering to mark the route

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-ppr':\n // We use React's postpone API to interrupt rendering here to create a\n // dynamic hole\n return postponeWithTracking(\n workStore.route,\n 'connection',\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDynamicHangingPromise","makeDevtoolsIOAwarePromise","isRequestApiAllowedInCurrentPhase","applyOwnerStack","RenderStage","InvariantError","connection","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","renderSignal","exportName","dynamicTracking","process","env","NODE_ENV","asyncApiPromises","Dynamic"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SACEC,2BAA2B,EAC3BC,oBAAoB,QACf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,cAAc,QAAQ,mCAAkC;AAEjE;;;;CAIC,GACD,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAA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,sDAAsD;IACtDhB,4BAA4Ba;AAC9B","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDynamicHangingPromise","makeDevtoolsIOAwarePromise","isRequestApiAllowedInCurrentPhase","applyOwnerStack","RenderStage","InvariantError","connection","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","renderSignal","exportName","process","env","NODE_ENV","asyncApiPromises","Dynamic"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SACEC,2BAA2B,EAC3BC,oBAAoB,QACf,iDAAgD;AACvD,SACEC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,WAAW,QAAQ,iCA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A8G;IAC9G,sDAAsD;IACtDf,4BAA4BY;AAC9B","ignoreList":[0]}

@@ -5,3 +5,3 @@ import { areCookiesMutableInCurrentPhase, RequestCookiesAdapter } from '../web/spec-extension/adapters/request-cookies';

import { throwForMissingRequestStore, workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';
import { postponeWithTracking, throwToInterruptStaticGeneration, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { throwToInterruptStaticGeneration, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';

@@ -72,6 +72,2 @@ import { makeDevtoolsIOAwarePromise, makeRuntimeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils';

});
case 'prerender-ppr':
// We need track dynamic access here eagerly to keep continuity with
// how cookies has worked in PPR without cacheComponents.
return postponeWithTracking(workStore.route, callingExpression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -78,0 +74,0 @@ // We track dynamic access here so we don't need to wrap the cookies

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // We need track dynamic access here eagerly to keep continuity with\n // how cookies has worked in PPR without cacheComponents.\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["areCookiesMutableInCurrentPhase","RequestCookiesAdapter","RequestCookies","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","cookies","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","makeHangingCookies","exportName","dynamicTracking","stagedRendering","delayUntilStage","sessionData","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","seal","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SAEEA,+BAA+B,EAC/BC,qBAAqB,QAChB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,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AChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASf,8CACPQ,MAAe,EACfrD,KAAyB;IAEzB,OAAO;QACLuD,YAAY;QACZ1B;YACEU,kBAAkBvC,OAAO;YACzB,OAAOwD;QACT;QACAxB,KAAIyB,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPxC,KAAyB,EACzB6D,UAAkB;IAElB,MAAMC,SAAS9D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG+D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["areCookiesMutableInCurrentPhase","RequestCookiesAdapter","RequestCookies","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","cookies","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","makeHangingCookies","exportName","stagedRendering","delayUntilStage","sessionData","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","seal","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SAEEA,+BAA+B,EAC/BC,qBAAqB,QAChB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,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pB,yBACPvC,KAAyB,EACzB4D,UAAkB;IAElB,MAAMC,SAAS7D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG8D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
import { getDraftModeProviderForCacheScope, throwForMissingRequestStore } from '../app-render/work-unit-async-storage.external';
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';
import { abortAndThrowOnSynchronousRequestDataAccess, postponeWithTracking, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { abortAndThrowOnSynchronousRequestDataAccess, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger';

@@ -44,3 +44,2 @@ import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -202,4 +201,2 @@ // Return empty draft mode

});
case 'prerender-ppr':
return postponeWithTracking(workStore.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -206,0 +203,0 @@ workUnitStore.revalidate = 0;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/draft-mode.ts"],"sourcesContent":["import {\n getDraftModeProviderForCacheScope,\n throwForMissingRequestStore,\n} from '../app-render/work-unit-async-storage.external'\n\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\n\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n applyOwnerStack,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\n\nexport function draftMode(): Promise<DraftMode> {\n const callingExpression = 'draftMode'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n throwForMissingRequestStore(callingExpression)\n }\n\n switch (workUnitStore.type) {\n case 'prerender-runtime': {\n // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'draftMode',\n new DraftMode(workUnitStore.draftMode)\n )\n } else {\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n }\n }\n case 'request':\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside of `\"use cache\"` or `unstable_cache`, draft mode is available if\n // the outmost work unit store is a request store (or a runtime prerender),\n // and if draft mode is enabled.\n const draftModeProvider = getDraftModeProviderForCacheScope(\n workStore,\n workUnitStore\n )\n\n if (draftModeProvider) {\n return createOrGetCachedDraftMode(draftModeProvider, workStore)\n }\n\n // Otherwise, we fall through to providing an empty draft mode.\n // eslint-disable-next-line no-fallthrough\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Return empty draft mode\n return createOrGetCachedDraftMode(null, workStore)\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${callingExpression}()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n\n default:\n return workUnitStore satisfies never\n }\n}\n\nfunction createOrGetCachedDraftMode(\n draftModeProvider: DraftModeProvider | null,\n workStore: WorkStore | undefined\n): Promise<DraftMode> {\n const cacheKey = draftModeProvider ?? NullDraftMode\n const cachedDraftMode = CachedDraftModes.get(cacheKey)\n\n if (cachedDraftMode) {\n return cachedDraftMode\n }\n\n if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {\n const route = workStore?.route\n return createDraftModeWithDevWarnings(draftModeProvider, route)\n } else {\n return Promise.resolve(new DraftMode(draftModeProvider))\n }\n}\n\ninterface CacheLifetime {}\nconst NullDraftMode = {}\nconst CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()\n\nfunction createDraftModeWithDevWarnings(\n underlyingProvider: null | DraftModeProvider,\n route: undefined | string\n): Promise<DraftMode> {\n const instance = new DraftMode(underlyingProvider)\n const promise = Promise.resolve(instance)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'isEnabled':\n warnForSyncAccess(route, `\\`draftMode().${prop}\\``)\n break\n case 'enable':\n case 'disable': {\n warnForSyncAccess(route, `\\`draftMode().${prop}()\\``)\n break\n }\n default: {\n // We only warn for well-defined properties of the draftMode object.\n }\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n return proxiedPromise\n}\n\nclass DraftMode {\n /**\n * @internal - this declaration is stripped via `tsc --stripInternal`\n */\n private readonly _provider: null | DraftModeProvider\n\n constructor(provider: null | DraftModeProvider) {\n this._provider = provider\n }\n get isEnabled() {\n if (this._provider !== null) {\n return this._provider.isEnabled\n }\n return false\n }\n public enable() {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n trackDynamicDraftMode('draftMode().enable()', this.enable)\n if (this._provider !== null) {\n this._provider.enable()\n }\n }\n public disable() {\n trackDynamicDraftMode('draftMode().disable()', this.disable)\n if (this._provider !== null) {\n this._provider.disable()\n }\n }\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createDraftModeAccessError\n)\n\nfunction createDraftModeAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`draftMode()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction trackDynamicDraftMode(expression: string, constructorOpt: Function) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n if (workUnitStore?.phase === 'after') {\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside \\`after()\\`. The enabled status of \\`draftMode()\\` can be read inside \\`after()\\` but you cannot enable or disable \\`draftMode()\\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache': {\n const error = new Error(\n `Route ${workStore.route} used \"${expression}\" inside \"use cache\". The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, constructorOpt)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside a function cached with \\`unstable_cache()\\`. The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n\n case 'prerender':\n case 'prerender-runtime': {\n const error = new Error(\n `Route ${workStore.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n workStore.route,\n expression,\n error,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n workStore.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n workStore.dynamicUsageDescription = expression\n workStore.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n break\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${expression}\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n default:\n workUnitStore satisfies never\n }\n }\n }\n}\n"],"names":["getDraftModeProviderForCacheScope","throwForMissingRequestStore","workAsyncStorage","workUnitAsyncStorage","abortAndThrowOnSynchronousRequestDataAccess","postponeWithTracking","trackDynamicDataInDynamicRender","createDedupedByCallsiteServerErrorLoggerDev","StaticGenBailoutError","DynamicServerError","InvariantError","ReflectAdapter","applyOwnerStack","RENDER_STAGES_BY_DATA_KIND","draftMode","callingExpression","workStore","getStore","workUnitStore","type","stagedRendering","delayUntilStage","sessionData","DraftMode","createOrGetCachedDraftMode","draftModeProvider","exportName","Error","route","cacheKey","NullDraftMode","cachedDraftMode","CachedDraftModes","get","process","env","NODE_ENV","isPrefetchRequest","createDraftModeWithDevWarnings","Promise","resolve","WeakMap","underlyingProvider","instance","promise","proxiedPromise","Proxy","target","prop","receiver","warnForSyncAccess","constructor","provider","_provider","isEnabled","enable","trackDynamicDraftMode","disable","createDraftModeAccessError","expression","prefix","constructorOpt","phase","dynamicShouldError","error","captureStackTrace","invalidDynamicUsageError","dynamicTracking","revalidate","err","dynamicUsageDescription","dynamicUsageStack","stack"],"mappings":"AAAA,SACEA,iCAAiC,EACjCC,2BAA2B,QACtB,iDAAgD;AAIvD,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SACEC,2CAA2C,EAC3CC,oBAAoB,EACpBC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,kBAAkB,QAAQ,+CAA8C;AACjF,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,eAAe,EACfC,0BAA0B,QACrB,6BAA4B;AAEnC,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYd,iBAAiBe,QAAQ;IAC3C,MAAMC,gBAAgBf,qBAAqBc,QAAQ;IAEnD,IAAI,CAACD,aAAa,CAACE,eAAe;QAChCjB,4BAA4Bc;IAC9B;IAEA,OAAQG,cAAcC,IAAI;QACxB,KAAK;YAAqB;gBACxB,uFAAuF;gBACvF,MAAM,EAAEC,eAAe,EAAE,GAAGF;gBAC5B,IAAIE,iBAAiB;oBACnB,OAAOA,gBAAgBC,eAAe,CACpCR,2BAA2BS,WAAW,EAC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{\n getDraftModeProviderForCacheScope,\n throwForMissingRequestStore,\n} from '../app-render/work-unit-async-storage.external'\n\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\n\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n abortAndThrowOnSynchronousRequestDataAccess,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n applyOwnerStack,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\n\nexport function draftMode(): Promise<DraftMode> {\n const callingExpression = 'draftMode'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n throwForMissingRequestStore(callingExpression)\n }\n\n switch (workUnitStore.type) {\n case 'prerender-runtime': {\n // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'draftMode',\n new DraftMode(workUnitStore.draftMode)\n )\n } else {\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n }\n }\n case 'request':\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside of `\"use cache\"` or `unstable_cache`, draft mode is available if\n // the outmost work unit store is a request store (or a runtime prerender),\n // and if draft mode is enabled.\n const draftModeProvider = getDraftModeProviderForCacheScope(\n workStore,\n workUnitStore\n )\n\n if (draftModeProvider) {\n return createOrGetCachedDraftMode(draftModeProvider, workStore)\n }\n\n // Otherwise, we fall through to providing an empty draft mode.\n // eslint-disable-next-line no-fallthrough\n case 'prerender':\n case 'prerender-legacy':\n // Return empty draft mode\n return createOrGetCachedDraftMode(null, workStore)\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${callingExpression}()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n\n default:\n return workUnitStore satisfies never\n }\n}\n\nfunction createOrGetCachedDraftMode(\n draftModeProvider: DraftModeProvider | null,\n workStore: WorkStore | undefined\n): Promise<DraftMode> {\n const cacheKey = draftModeProvider ?? NullDraftMode\n const cachedDraftMode = CachedDraftModes.get(cacheKey)\n\n if (cachedDraftMode) {\n return cachedDraftMode\n }\n\n if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {\n const route = workStore?.route\n return createDraftModeWithDevWarnings(draftModeProvider, route)\n } else {\n return Promise.resolve(new DraftMode(draftModeProvider))\n }\n}\n\ninterface CacheLifetime {}\nconst NullDraftMode = {}\nconst CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()\n\nfunction createDraftModeWithDevWarnings(\n underlyingProvider: null | DraftModeProvider,\n route: undefined | string\n): Promise<DraftMode> {\n const instance = new DraftMode(underlyingProvider)\n const promise = Promise.resolve(instance)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'isEnabled':\n warnForSyncAccess(route, `\\`draftMode().${prop}\\``)\n break\n case 'enable':\n case 'disable': {\n warnForSyncAccess(route, `\\`draftMode().${prop}()\\``)\n break\n }\n default: {\n // We only warn for well-defined properties of the draftMode object.\n }\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n return proxiedPromise\n}\n\nclass DraftMode {\n /**\n * @internal - this declaration is stripped via `tsc --stripInternal`\n */\n private readonly _provider: null | DraftModeProvider\n\n constructor(provider: null | DraftModeProvider) {\n this._provider = provider\n }\n get isEnabled() {\n if (this._provider !== null) {\n return this._provider.isEnabled\n }\n return false\n }\n public enable() {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n trackDynamicDraftMode('draftMode().enable()', this.enable)\n if (this._provider !== null) {\n this._provider.enable()\n }\n }\n public disable() {\n trackDynamicDraftMode('draftMode().disable()', this.disable)\n if (this._provider !== null) {\n this._provider.disable()\n }\n }\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createDraftModeAccessError\n)\n\nfunction createDraftModeAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`draftMode()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction trackDynamicDraftMode(expression: string, constructorOpt: Function) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n if (workUnitStore?.phase === 'after') {\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside \\`after()\\`. The enabled status of \\`draftMode()\\` can be read inside \\`after()\\` but you cannot enable or disable \\`draftMode()\\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache': {\n const error = new Error(\n `Route ${workStore.route} used \"${expression}\" inside \"use cache\". The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, constructorOpt)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside a function cached with \\`unstable_cache()\\`. The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n\n case 'prerender':\n case 'prerender-runtime': {\n const error = new Error(\n `Route ${workStore.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n workStore.route,\n expression,\n error,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n workStore.dynamicUsageDescription = expression\n workStore.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n break\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${expression}\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n default:\n workUnitStore satisfies never\n }\n }\n }\n}\n"],"names":["getDraftModeProviderForCacheScope","throwForMissingRequestStore","workAsyncStorage","workUnitAsyncStorage","abortAndThrowOnSynchronousRequestDataAccess","trackDynamicDataInDynamicRender","createDedupedByCallsiteServerErrorLoggerDev","StaticGenBailoutError","DynamicServerError","InvariantError","ReflectAdapter","applyOwnerStack","RENDER_STAGES_BY_DATA_KIND","draftMode","callingExpression","workStore","getStore","workUnitStore","type","stagedRendering","delayUntilStage","sessionData","DraftMode","createOrGetCachedDraftMode","draftModeProvider","exportName","Error","route","cacheKey","NullDraftMode","cachedDraftMode","CachedDraftModes","get","process","env","NODE_ENV","isPrefetchRequest","createDraftModeWithDevWarnings","Promise","resolve","WeakMap","underlyingProvider","instance","promise","proxiedPromise","Proxy","target","prop","receiver","warnForSyncAccess","constructor","provider","_provider","isEnabled","enable","trackDynamicDraftMode","disable","createDraftModeAccessError","expression","prefix","constructorOpt","phase","dynamicShouldError","error","captureStackTrace","invalidDynamicUsageError","revalidate","err","dynamicUsageDescription","dynamicUsageStack","stack"],"mappings":"AAAA,SACEA,iCAAiC,EACjCC,2BAA2B,QACtB,iDAAgD;AAIvD,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SACEC,2CAA2C,EAC3CC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,kBAAkB,QAAQ,+CAA8C;AACjF,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,eAAe,EACfC,0BAA0B,QACrB,6BAA4B;AAEnC,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYb,iBAAiBc,QAAQ;IAC3C,MAAMC,gBAAgBd,qBAAqBa,QAAQ;IAEnD,IAAI,CAACD,aAAa,CAACE,eAAe;QAChChB,4BAA4Ba;IAC9B;IAEA,OAAQG,cAAcC,IAAI;QACxB,KAA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0]}
import { HeadersAdapter } from '../web/spec-extension/adapters/headers';
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { throwForMissingRequestStore, workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';
import { postponeWithTracking, throwToInterruptStaticGeneration, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { throwToInterruptStaticGeneration, trackDynamicDataInDynamicRender } from '../app-render/dynamic-rendering';
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';

@@ -68,3 +68,2 @@ import { makeDevtoolsIOAwarePromise, makeRuntimeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils';

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -96,8 +95,2 @@ case 'request':

});
case 'prerender-ppr':
// PPR Prerender (no cacheComponents)
// We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how headers has worked in PPR without cacheComponents.
// TODO consider switching the semantic to throw on property access instead
return postponeWithTracking(workStore.route, callingExpression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -104,0 +97,0 @@ // Legacy Prerender

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // PPR Prerender (no cacheComponents)\n // We are prerendering with PPR. We need track dynamic access here eagerly\n // to keep continuity with how headers has worked in PPR without cacheComponents.\n // TODO consider switching the semantic to throw on property access instead\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["HeadersAdapter","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","headers","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingHeaders","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","invalidDynamicUsageError","dynamicShouldError","makeHangingHeaders","exportName","dynamicTracking","stagedRendering","delayUntilStage","sessionData","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SACEA,cAAc,QAET,yCAAwC;AAC/C,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qB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E,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAAStB,yBACPpC,KAAyB,EACzB2D,UAAkB;IAElB,MAAMC,SAAS5D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG6D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["HeadersAdapter","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","headers","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingHeaders","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","invalidDynamicUsageError","dynamicShouldError","makeHangingHeaders","exportName","stagedRendering","delayUntilStage","sessionData","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SACEA,cAAc,QAET,yCAAwC;AAC/C,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,cAAc,QAAQ,mCAAkC;AAEjE;;;;;;;;CAQC,GACD,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYf,iBAAiBgB,QAAQ;IAC3C,MAAMC,gBAAgBf,qBAAqBc,QAAQ;IAEnD,IAAID,WAAW;QACb,IAAIE,iBAAiB,CAACP,kCAAkCO,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAI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BACPQ,MAAe,EACfC,IAAY,EACZnD,KAAyB;IAEzB,OAAO;QACLoD,YAAY;QACZ3B;YACES,kBAAkBlC,OAAO,CAAC,YAAY,EAAEmD,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACAzB,KAAI0B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASjB,8CACPU,MAAe,EACflD,KAAyB;IAEzB,OAAO;QACLoD,YAAY;QACZ3B;YACES,kBAAkBlC,OAAO;YACzB,OAAOqD;QACT;QACAzB,KAAI0B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQZ,OAAOC,QAAQ,EAAE;gBAC7Ce;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAAStB,yBACPnC,KAAyB,EACzB0D,UAAkB;IAElB,MAAMC,SAAS3D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG4D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}

@@ -5,3 +5,2 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external';

import { RenderStage } from '../app-render/staged-rendering';
import { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error';
import { isRequestApiAllowedInCurrentPhase } from './utils';

@@ -58,6 +57,2 @@ // A fulfilled thenable that React can unwrap synchronously via `use()` without

return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, '`io()`');
case 'prerender-ppr':
// Dead code to be removed when we eliminate legacy ppr code
throwPrerenderPPRRemovedError();
break;
case 'cache':

@@ -64,0 +59,0 @@ case 'private-cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'prerender-ppr':\n // Dead code to be removed when we eliminate legacy ppr code\n throwPrerenderPPRRemovedError()\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","makeDynamicHangingPromise","makeDevtoolsIOAwarePromise","RenderStage","throwPrerenderPPRRemovedError","isRequestApiAllowedInCurrentPhase","resolvedIOPromise","Promise","resolve","undefined","status","value","io","workStore","getStore","workUnitStore","Error","route","type","process","env","NODE_ENV","asyncApiPromises","Dynamic","renderSignal"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,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;YACL,KAAK;YACL,KAAK;YACL,kDAAkD;YAClD,iEAAiE;YACjE,8CAA8C;YAC9C,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,iEAAiE;YACjE,sCAAsC;YACtC,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,4DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOE;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","makeDynamicHangingPromise","makeDevtoolsIOAwarePromise","RenderStage","isRequestApiAllowedInCurrentPhase","resolvedIOPromise","Promise","resolve","undefined","status","value","io","workStore","getStore","workUnitStore","Error","route","type","process","env","NODE_ENV","asyncApiPromises","Dynamic","renderSignal"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SACEC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,iCAAiC,QAAQ,UAAS;AAE3D,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAMC,oBAAmCC,QAAQC,OAAO,CAACC;AACvDH,kBAA0BI,MAAM,GAAG;AACnCJ,kBAA0BK,KAAK,GAAGF;AAEpC;;;;;;;;;;CAUC,GACD,OAAO,SAASG;IACd,MAAMC,YAAYb,iBAAiBc,QAAQ;IAC3C,MAAMC,gBAAgBd,qBAAqBa,QAAQ;IAEnD,IAAID,aAAaE,eAAe;QAC9B,IAAIA,iBAAiB,CAACV,kCAAkCU,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,oLAAoL,CAAC,GAD1M,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QACA,OAAQF,cAAcG,IAAI;YACxB,KAAK;gBACH,kEAAkE;gBAClE,mEAAmE;gBACnE,6DAA6D;gBAC7D,uEAAuE;gBACvE,oEAAoE;gBACpE,kBAAkB;gBAClB,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;oBAC1C,IAAIN,cAAcO,gBAAgB,EAAE;wBAClC,OAAOP,cAAcO,gBAAgB,CAACV,EAAE;oBAC1C;oBACA,OAAOT,2BACLM,WACAM,eACAX,YAAYmB,OAAO;gBAEvB,OAAO,IAAIR,cAAcO,gBAAgB,EAAE;oBACzC,OAAOP,cAAcO,gBAAgB,CAACV,EAAE;gBAC1C;gBACA,OAAON;YACT,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,wEAAwE;gBACxE,2DAA2D;gBAC3D,OAAOJ,0BACLa,cAAcS,YAAY,EAC1BX,UAAUI,KAAK,EACf;YAEJ,KAAK;YACL,KAAK;YACL,KAAK;YACL,kDAAkD;YAClD,iEAAiE;YACjE,8CAA8C;YAC9C,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,iEAAiE;YACjE,sCAAsC;YACtC,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,4DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOX;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]}
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { createVaryingParams, getMetadataVaryParamsAccumulator } from '../app-render/vary-params';
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect';
import { throwToInterruptStaticGeneration, postponeWithTracking } from '../app-render/dynamic-rendering';
import { workUnitAsyncStorage, throwInvariantForMissingStore } from '../app-render/work-unit-async-storage.external';

@@ -26,3 +25,2 @@ import { InvariantError } from '../../shared/lib/invariant-error';

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -98,3 +96,2 @@ // Client params don't need additional vary tracking because by the

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -159,3 +156,2 @@ return createStaticPrerenderParams(underlyingParams, null, workStore, workUnitStore, varyParamsAccumulator);

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -244,3 +240,2 @@ return createStaticPrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator);

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -305,14 +300,2 @@ case 'request':

}
case 'prerender-ppr':
{
const fallbackParams = prerenderStore.fallbackRouteParams;
if (fallbackParams) {
for(const key in underlyingParams){
if (fallbackParams.has(key)) {
return makeErroringParams(underlyingParams, fallbackParams, workStore, prerenderStore);
}
}
}
break;
}
case 'prerender-legacy':

@@ -502,45 +485,2 @@ break;

}
function makeErroringParams(underlyingParams, fallbackParams, workStore, prerenderStore) {
const cachedParams = CachedParams.get(underlyingParams);
if (cachedParams) {
return cachedParams;
}
const augmentedUnderlying = {
...underlyingParams
};
// We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(augmentedUnderlying);
CachedParams.set(underlyingParams, promise);
Object.keys(underlyingParams).forEach((prop)=>{
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
if (fallbackParams.has(prop)) {
Object.defineProperty(augmentedUnderlying, prop, {
get () {
const expression = describeStringPropertyAccess('params', prop);
// In most dynamic APIs we also throw if `dynamic = "error"` however
// for params is only dynamic when we're generating a fallback shell
// and even when `dynamic = "error"` we still support generating dynamic
// fallback shells
// TODO remove this comment when cacheComponents is the default since there
// will be no `dynamic = "error"`
if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
postponeWithTracking(workStore.route, expression, prerenderStore.dynamicTracking);
} else {
// Legacy Prerender
throwToInterruptStaticGeneration(expression, workStore, prerenderStore);
}
},
enumerable: true
});
}
}
});
return promise;
}
function makeUntrackedParams(underlyingParams) {

@@ -547,0 +487,0 @@ const cachedParams = CachedParams.get(underlyingParams);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsAppShell`.\n const staticParamsStage = workUnitStore.needsAppShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(null, workUnitStore)\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["workAsyncStorage","createVaryingParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","trackFallbackParamsAccessed","RENDER_STAGES_BY_DATA_KIND","trackPromiseUsed","trackIncompatibleShellContent","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","isEmptyParams","hasFallbackRouteParams","allParamsAreRootParams","createParamsFromClient","underlyingParams","workStore","getStore","workUnitStore","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","optionalCatchAllParamName","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","createRenderParamsForPage","createPrerenderParamsForClientSegment","fallbackRouteParams","key","has","renderSignal","route","Promise","resolve","prerenderStore","makeHangingParams","stagedRendering","rootParams","staticParamsStage","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsAppShell","__NEXT_DEV_SERVER","bind","trigger","reject","then","catch","noop","displayName","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","args","undefined","store","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","defineProperty","expression","dynamicTracking","enumerable","hasFallbackParams","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createParamsAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAGlD,SACEC,mBAAmB,EACnBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,QACf,kCAAiC;AAExC,SACEC,oBAAoB,EAKpBC,6BAA6B,QAIxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,4BAA4B,EAC5BC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,0BAA0B,EAC1BC,gCAAgC,EAChCC,sBAAsB,EACtBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,gBAAgB,EAChBC,6BAA6B,QACxB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SACEC,aAAa,EACbC,sBAAsB,EACtBC,sBAAsB,QACjB,sBAAqB;AAK5B,OAAO,SAASC,uBACdC,gBAAwB;IAExB,MAAMC,YAAYzB,iBAAiB0B,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIjB,eAAe,yCAA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AEb,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n workUnitAsyncStorage,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsAppShell`.\n const staticParamsStage = workUnitStore.needsAppShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(null, workUnitStore)\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["workAsyncStorage","createVaryingParams","getMetadataVaryParamsAccumulator","ReflectAdapter","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","trackFallbackParamsAccessed","RENDER_STAGES_BY_DATA_KIND","trackPromiseUsed","trackIncompatibleShellContent","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","isEmptyParams","hasFallbackRouteParams","allParamsAreRootParams","createParamsFromClient","underlyingParams","workStore","getStore","workUnitStore","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","optionalCatchAllParamName","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","createRenderParamsForPage","createPrerenderParamsForClientSegment","fallbackRouteParams","key","has","renderSignal","route","Promise","resolve","prerenderStore","makeHangingParams","stagedRendering","rootParams","staticParamsStage","staticLinkData","delayUntilStage","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsAppShell","__NEXT_DEV_SERVER","bind","trigger","reject","then","catch","noop","displayName","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","args","undefined","store","abortController","abort","Error","Proxy","apply","cachedParams","set","hasFallbackParams","proxiedPromise","proxiedProperties","forEach","add","expression","warnForSyncAccess","value","delete","ownKeys","Reflect","createParamsAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAGlD,SACEC,mBAAmB,EACnBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,oBAAoB,EAGpBC,6BAA6B,QAIxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,4BAA4B,EAC5BC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,0BAA0B,EAC1BC,gCAAgC,EAChCC,sBAAsB,EACtBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,gBAAgB,EAChBC,6BAA6B,QACxB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SACEC,aAAa,EACbC,sBAAsB,EACtBC,sBAA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AAkB;IAElB,MAAMO,SAAStE,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIqD,MACT,GAAGiB,OAAO,KAAK,EAAEP,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { postponeWithTracking } from '../app-render/dynamic-rendering';
import { throwInvariantForMissingStore, workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';

@@ -19,3 +18,2 @@ import { makeDynamicHangingPromise, makeFallbackParamsHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils';

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -88,10 +86,2 @@ {

}
case 'prerender-ppr':
{
const fallbackParams = prerenderStore.fallbackRouteParams;
if (fallbackParams && fallbackParams.size > 0) {
return makeErroringPathname(workStore, prerenderStore.dynamicTracking);
}
break;
}
case 'prerender-legacy':

@@ -105,26 +95,2 @@ break;

}
function makeErroringPathname(workStore, dynamicTracking) {
let reject = null;
const promise = new Promise((_, re)=>{
reject = re;
});
const originalThen = promise.then.bind(promise);
// We instrument .then so that we can generate a tracking event only if you actually
// await this promise, not just that it is created.
promise.then = (onfulfilled, onrejected)=>{
if (reject) {
try {
postponeWithTracking(workStore.route, 'metadata relative url resolving', dynamicTracking);
} catch (error) {
reject(error);
reject = null;
}
}
return originalThen(onfulfilled, onrejected);
};
// We wrap in a noop proxy to trick the runtime into thinking it
// isn't a native promise (it's not really). This is so that awaiting
// the promise will call the `then` property triggering the lazy postpone
return new Proxy(promise, {});
}
function createRenderPathname(underlyingPathname) {

@@ -131,0 +97,0 @@ return Promise.resolve(underlyingPathname);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n postponeWithTracking,\n type DynamicTrackingState,\n} from '../app-render/dynamic-rendering'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeDynamicHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname only hangs when there are fallback params, and a\n // concrete (ISR-upgraded) prerender resolves it — so this access is\n // fallback-param data for the static-prefetch hint.\n return makeFallbackParamsHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeErroringPathname(workStore, prerenderStore.dynamicTracking)\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction makeErroringPathname<T>(\n workStore: WorkStore,\n dynamicTracking: null | DynamicTrackingState\n): Promise<T> {\n let reject: null | ((reason: unknown) => void) = null\n const promise = new Promise<T>((_, re) => {\n reject = re\n })\n\n const originalThen = promise.then.bind(promise)\n\n // We instrument .then so that we can generate a tracking event only if you actually\n // await this promise, not just that it is created.\n promise.then = (onfulfilled, onrejected) => {\n if (reject) {\n try {\n postponeWithTracking(\n workStore.route,\n 'metadata relative url resolving',\n dynamicTracking\n )\n } catch (error) {\n reject(error)\n reject = null\n }\n }\n return originalThen(onfulfilled, onrejected)\n }\n\n // We wrap in a noop proxy to trick the runtime into thinking it\n // isn't a native promise (it's not really). This is so that awaiting\n // the promise will call the `then` property triggering the lazy postpone\n return new Proxy(promise, {})\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["workAsyncStorage","postponeWithTracking","throwInvariantForMissingStore","workUnitAsyncStorage","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","RENDER_STAGES_BY_DATA_KIND","InvariantError","createServerPathnameForMetadata","underlyingPathname","workStore","getStore","workUnitStore","type","createPrerenderPathname","stagedRendering","pathnameStage","runtimeLinkData","delayUntilStage","undefined","isSessionShell","renderSignal","route","createRenderPathname","prerenderStore","fallbackParams","fallbackRouteParams","size","makeErroringPathname","dynamicTracking","Promise","resolve","reject","promise","_","re","originalThen","then","bind","onfulfilled","onrejected","error","Proxy"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,oBAAoB,QAEf,kCAAiC;AAExC,SACEC,6BAA6B,EAC7BC,oBAAoB,QAIf,iDAAgD;AACvD,SACEC,yBAAyB,EACzBC,gCAAgC,EAChCC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYV,iBAAiBW,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIH,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMK,gBAAgBT,qBAAqBQ,QAAQ;IACnD,IAAIC,eAAe;QACjB,OAAQA,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLL,oBACAC,WACAE;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIL,eACR,6EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,eACR,4EADI,qBAAA;2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,SAASmB,qBACPlB,SAAoB,EACpBmB,eAA4C;IAE5C,IAAIG,SAA6C;IACjD,MAAMC,UAAU,IAAIH,QAAW,CAACI,GAAGC;QACjCH,SAASG;IACX;IAEA,MAAMC,eAAeH,QAAQI,IAAI,CAACC,IAAI,CAACL;IAEvC,oFAAoF;IACpF,mDAAmD;IACnDA,QAAQI,IAAI,GAAG,CAACE,aAAaC;QAC3B,IAAIR,QAAQ;YACV,IAAI;gBACF/B,qBACES,UAAUY,KAAK,EACf,mCACAO;YAEJ,EAAE,OAAOY,OAAO;gBACdT,OAAOS;gBACPT,SAAS;YACX;QACF;QACA,OAAOI,aAAaG,aAAaC;IACnC;IAEA,gEAAgE;IAChE,qEAAqE;IACrE,yEAAyE;IACzE,OAAO,IAAIE,MAAMT,SAAS,CAAC;AAC7B;AAEA,SAASV,qBAAqBd,kBAA0B;IACtD,OAAOqB,QAAQC,OAAO,CAACtB;AACzB","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeDynamicHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname only hangs when there are fallback params, and a\n // concrete (ISR-upgraded) prerender resolves it — so this access is\n // fallback-param data for the static-prefetch hint.\n return makeFallbackParamsHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["workAsyncStorage","throwInvariantForMissingStore","workUnitAsyncStorage","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","RENDER_STAGES_BY_DATA_KIND","InvariantError","createServerPathnameForMetadata","underlyingPathname","workStore","getStore","workUnitStore","type","createPrerenderPathname","stagedRendering","pathnameStage","runtimeLinkData","delayUntilStage","undefined","isSessionShell","renderSignal","route","createRenderPathname","prerenderStore","fallbackParams","fallbackRouteParams","size","Promise","resolve"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,6BAA6B,EAC7BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,yBAAyB,EACzBC,gCAAgC,EAChCC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYT,iBAAiBU,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIH,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMK,gBAAgBT,qBAAqBQ,QAAQ;IACnD,IAAIC,eAAe;QACjB,OAAQA,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLL,oBACAC,WACAE;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIL,eACR,6EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,eACR,4EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,eACR,sFADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBAAqB;oBACxB,iEAAiE;oBACjE,kDAAkD;oBAClD,4CAA4C;oBAC5C,sEAAsE;oBACtE,oDAAoD;oBACpD,iEAAiE;oBACjE,MAAM,EAAEQ,eAAe,EAAE,GAAGH;oBAC5B,IAAIG,iBAAiB;wBACnB,MAAMC,gBAAgBV,2BAA2BW,eAAe;wBAChE,OAAOF,gBAAgBG,eAAe,CACpCF,eACAG,WACAV;oBAEJ,OAAO;wBACL,IAAIG,cAAcQ,cAAc,EAAE;4BAChC,OAAOhB,0BACLQ,cAAcS,YAAY,EAC1BX,UAAUY,KAAK,EACf;wBAEJ,OAAO;4BACL,OAAOC,qBAAqBd;wBAC9B;oBACF;gBACF;YACA,KAAK;gBACH,wEAAwE;gBACxE,OAAOc,qBAAqBd;YAC9B;gBACEG;QACJ;IACF;IACAV;AACF;AAEA,SAASY,wBACPL,kBAA0B,EAC1BC,SAAoB,EACpBc,cAAiE;IAEjE,OAAQA,eAAeX,IAAI;QACzB,KAAK;YAAa;gBAChB,MAAMY,iBAAiBD,eAAeE,mBAAmB;gBACzD,IAAID,kBAAkBA,eAAeE,IAAI,GAAG,GAAG;oBAC7C,gEAAgE;oBAChE,oEAAoE;oBACpE,oDAAoD;oBACpD,OAAOtB,iCACLmB,eAAeH,YAAY,EAC3BX,UAAUY,KAAK,EACf,cACAE;gBAEJ;gBACA;YACF;QACA,KAAK;YACH;QACF;YACEA;IACJ;IAEA,qFAAqF;IACrF,OAAOI,QAAQC,OAAO,CAACpB;AACzB;AAEA,SAASc,qBAAqBd,kBAA0B;IACtD,OAAOmB,QAAQC,OAAO,CAACpB;AACzB","ignoreList":[0]}
import { InvariantError } from '../../shared/lib/invariant-error';
import { postponeWithTracking, throwToInterruptStaticGeneration } from '../app-render/dynamic-rendering';
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';
import { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils';
import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils';
import { actionAsyncStorage } from '../app-render/action-async-storage.external';

@@ -74,3 +72,2 @@ import { accumulateRootVaryParam } from '../app-render/vary-params';

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -138,3 +135,2 @@ {

case 'prerender-legacy':
case 'prerender-ppr':
default:

@@ -153,11 +149,2 @@ }

}
case 'prerender-ppr':
{
// We aren't in a cacheComponents prerender, but the param is a fallback,
// so we need to make an erroring params object which will postpone/error if you access it
if (prerenderStore.fallbackRouteParams && prerenderStore.fallbackRouteParams.has(paramName)) {
return makeErroringRootParamPromise(paramName, workStore, prerenderStore, apiName);
}
break;
}
case 'prerender-legacy':

@@ -176,24 +163,3 @@ {

}
/** Deliberately async -- we want to create a rejected promise, not error synchronously. */ async function makeErroringRootParamPromise(paramName, workStore, prerenderStore, apiName) {
const expression = describeStringPropertyAccess(apiName, paramName);
// In most dynamic APIs, we also throw if `dynamic = "error"`.
// However, root params are only dynamic when we're generating a fallback shell,
// and even with `dynamic = "error"` we still support generating dynamic fallback shells.
// TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = "error"`
switch(prerenderStore.type){
case 'prerender-ppr':
{
return postponeWithTracking(workStore.route, expression, prerenderStore.dynamicTracking);
}
case 'prerender-legacy':
{
return throwToInterruptStaticGeneration(expression, workStore, prerenderStore);
}
default:
{
prerenderStore;
}
}
}
//# sourceMappingURL=root-params.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStorePPR\n | PrerenderStoreLegacy\n | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-ppr':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n // We aren't in a cacheComponents prerender, but the param is a fallback,\n // so we need to make an erroring params object which will postpone/error if you access it\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeErroringRootParamPromise(\n paramName,\n workStore,\n prerenderStore,\n apiName\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n\n/** Deliberately async -- we want to create a rejected promise, not error synchronously. */\nasync function makeErroringRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,\n apiName: string\n): Promise<ParamValue> {\n const expression = describeStringPropertyAccess(apiName, paramName)\n // In most dynamic APIs, we also throw if `dynamic = \"error\"`.\n // However, root params are only dynamic when we're generating a fallback shell,\n // and even with `dynamic = \"error\"` we still support generating dynamic fallback shells.\n // TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = \"error\"`\n switch (prerenderStore.type) {\n case 'prerender-ppr': {\n return postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n }\n case 'prerender-legacy': {\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n default: {\n prerenderStore satisfies never\n }\n }\n}\n"],"names":["InvariantError","postponeWithTracking","throwToInterruptStaticGeneration","workAsyncStorage","workUnitAsyncStorage","makeFallbackParamsHangingPromise","describeStringPropertyAccess","actionAsyncStorage","accumulateRootVaryParam","getRootParam","paramName","apiName","workStore","getStore","workUnitStore","Error","route","actionStore","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","prerenderStore","underlyingParams","fallb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F;IACF;IAEA,uFAAuF;IACvF7B,wBAAwBE;IACxB,OAAOe,QAAQC,OAAO,CAACY,gBAAgB,CAAC5B,UAAU;AACpD;AAEA,yFAAyF,GACzF,eAAegC,6BACbhC,SAAiB,EACjBE,SAAoB,EACpByB,cAAwD,EACxD1B,OAAe;IAEf,MAAMgC,aAAarC,6BAA6BK,SAASD;IACzD,8DAA8D;IAC9D,gFAAgF;IAChF,yFAAyF;IACzF,2GAA2G;IAC3G,OAAQ2B,eAAehB,IAAI;QACzB,KAAK;YAAiB;gBACpB,OAAOpB,qBACLW,UAAUI,KAAK,EACf2B,YACAN,eAAeO,eAAe;YAElC;QACA,KAAK;YAAoB;gBACvB,OAAO1C,iCACLyC,YACA/B,WACAyB;YAEJ;QACA;YAAS;gBACPA;YACF;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n"],"names":["InvariantError","workAsyncStorage","workUnitAsyncStorage","makeFallbackParamsHangingPromise","actionAsyncStorage","accumulateRootVaryParam","getRootParam","paramName","apiName","workStore","getStore","workUnitStore","Error","route","actionStore","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","prerenderStore","underlyingParams","fallbackRouteParams","has","renderSignal"],"mappings":"AAAA,SAAS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BACxB;YACF;QACA,KAAK;YAA0B;gBAC7B,IAAI,CAAEA,CAAAA,aAAaI,cAAcQ,UAAU,AAAD,GAAI;oBAC5C,MAAM,qBAEL,CAFK,IAAIP,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,MAAM,EAAEL,QAAQ,4CAA4C,EAAED,UAAU,yLAAyL,CAAC,GADvR,qBAAA;+BAAA;oCAAA;sCAAA;oBAEN;gBACF;gBACA;YACF;QACA;YAAS;gBACPI;YACF;IACF;IAEAN,wBAAwBE;IACxB,OAAOe,QAAQC,OAAO,CAACZ,cAAcQ,UAAU,CAACZ,UAAU;AAC5D;AAEA,SAASiB,gCACPjB,SAAiB,EACjBE,SAAoB,EACpByB,cAAiE,EACjE1B,OAAe;IAEf,OAAQ0B,eAAehB,IAAI;QACzB,KAAK;QACL,KAAK;QACL;IACF;IAEA,MAAMiB,mBAAmBD,eAAef,UAAU;IAElD,OAAQe,eAAehB,IAAI;QACzB,KAAK;YAAa;gBAChB,yCAAyC;gBACzC,+DAA+D;gBAC/D,IACEgB,eAAeE,mBAAmB,IAClCF,eAAeE,mBAAmB,CAACC,GAAG,CAAC9B,YACvC;oBACA,OAAOJ,iCACL+B,eAAeI,YAAY,EAC3B7B,UAAUI,KAAK,EACfL,SACA0B;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBAEvB;YACF;QACA;YAAS;gBACPA;YACF;IACF;IAEA,uFAAuF;IACvF7B,wBAAwBE;IACxB,OAAOe,QAAQC,OAAO,CAACY,gBAAgB,CAAC5B,UAAU;AACpD","ignoreList":[0]}
import { workAsyncStorage } from '../app-render/work-async-storage.external';
import { createVaryingSearchParams, getMetadataVaryParamsAccumulator } from '../app-render/vary-params';
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect';
import { throwToInterruptStaticGeneration, postponeWithTracking, annotateDynamicAccess } from '../app-render/dynamic-rendering';
import { throwToInterruptStaticGeneration, annotateDynamicAccess } from '../app-render/dynamic-rendering';
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external';

@@ -26,3 +26,2 @@ import { workUnitAsyncStorage, throwInvariantForMissingStore } from '../app-render/work-unit-async-storage.external';

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -84,3 +83,2 @@ return createStaticPrerenderSearchParams(workStore, workUnitStore);

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -166,3 +164,2 @@ return createStaticPrerenderSearchParams(workStore, workUnitStore);

});
case 'prerender-ppr':
case 'prerender-legacy':

@@ -188,3 +185,2 @@ case 'request':

return makeHangingSearchParams(workStore, prerenderStore);
case 'prerender-ppr':
case 'prerender-legacy':

@@ -366,5 +362,2 @@ // We are in a legacy static generation and need to interrupt the

throwWithStaticGenerationBailoutErrorWithDynamicError(workStore.route, expression);
} else if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
postponeWithTracking(workStore.route, expression, prerenderStore.dynamicTracking);
} else {

@@ -371,0 +364,0 @@ // Legacy Prerender

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStorePPR,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n makePromiseFromTrigger,\n trackRuntimeDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeRuntimeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeRuntimeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // This promise is created for every page whether or not it reads search\n // params, so recording the access at creation would mark every render.\n // The access is tracked in the proxy traps below instead.\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)\n }\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["workAsyncStorage","createVaryingSearchParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","annotateDynamicAccess","dynamicAccessAsyncStorage","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","makePromiseFromTrigger","trackRuntimeDataAccessed","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","describeStringPropertyAccess","describeHasCheckingStringProperty","wellKnownProperties","throwWithStaticGenerationBailoutErrorWithDynamicError","throwForSearchParamsAccessInUseCache","createSearchParamsFromClient","underlyingSearchParams","workStore","getStore","workUnitStore","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","createServerSearchParamsForMetadata","metadataVaryParamsAccumulator","createServerSearchParamsForServerPage","varyParamsAccumulator","createRuntimePrerenderSearchParams","createPrerenderSearchParamsForClientPage","forceStatic","Promise","resolve","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","proxyHandler","target","prop","receiver","hasOwn","originalMethod","args","expression","dynamicAccessStore","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","dynamicTracking","makeErroringSearchParamsForUseCache","has","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createSearchAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,EACpBC,qBAAqB,QAChB,kCAAiC;AACxC,SAASC,yBAAyB,QAAQ,sDAAqD;AAE/F,SACEC,oBAAoB,EAMpBC,6BAA6B,QAGxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,sBAAsB,EACtBC,wBAAwB,EACxBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SACEC,4BAA4B,EAC5BC,iCAAiC,EACjCC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,qDAAqD,EACrDC,oCAAoC,QAC/B,UAAS;AAIhB,OAAO,SAASC,6BACdC,sBAAoC;IAEpC,MAAMC,YAAYxB,iBAAiByB,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAId,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMgB,gBAAgBlB,qBAAqBiB,QAAQ;IACnD,IAAIC,eAAe;QACjB,OAAQA,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOC,kCAAkCJ,WAAWE;YACtD,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIhB,eACR,8EADI,qBAAA;2BAAA;gCAAA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AU;gBAC5B,IACE,CAACnE,oBAAoBoF,GAAG,CAACjB,SACxByB,CAAAA,kBAAkBR,GAAG,CAACjB,SACrB,oEAAoE;gBACpE,+BAA+B;gBAC/BuB,QAAQN,GAAG,CAAClB,QAAQC,UAAU,KAAI,GACpC;oBACA,MAAMK,aAAazE,kCACjB,gBACAoE;oBAEF4B,kBAAkB1F,UAAUmB,KAAK,EAAEgD;gBACrC;YACF;YACA,OAAOkB,QAAQN,GAAG,CAAClB,QAAQC;QAC7B;QACAwB,SAAQzB,MAAM;YACZ,MAAMM,aAAa;YACnBuB,kBAAkB1F,UAAUmB,KAAK,EAAEgD;YACnC,OAAOkB,QAAQC,OAAO,CAACzB;QACzB;IACF;AACF;AAEA,MAAM6B,oBAAoBlG,4CACxBqG;AAGF,SAASA,wBACP1E,KAAyB,EACzBgD,UAAkB;IAElB,MAAM2B,SAAS3E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIoD,MACT,GAAGuB,OAAO,KAAK,EAAE3B,WAAW,EAAE,CAAC,GAC7B,CAAC,uHAAuH,CAAC,GACzH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF;AAEA,SAAS7D,qCACPP,sBAAoC,EACpCC,SAAoB,EACpBE,aAAoC;QAKtBA;IAHd,MAAM,EAAE6C,iCAAiC,EAAE,GACzCC,QAAQ;IACV,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAAClD,EAAAA,mCAAAA,cAAcG,iBAAiB,qBAA/BH,iCAAiCmD,YAAY,KAAI,CAAC;IAEhEtD,yBAAyBgD,kCACvBhD,wBACAkD,cACAjD,UAAUmB,KAAK;IAEjB,OAAOH,QAAQC,OAAO,CAAClB;AACzB","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n makePromiseFromTrigger,\n trackRuntimeDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeRuntimeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeRuntimeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // This promise is created for every page whether or not it reads search\n // params, so recording the access at creation would mark every render.\n // The access is tracked in the proxy traps below instead.\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)\n }\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["workAsyncStorage","createVaryingSearchParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","annotateDynamicAccess","dynamicAccessAsyncStorage","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","makePromiseFromTrigger","trackRuntimeDataAccessed","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","describeStringPropertyAccess","describeHasCheckingStringProperty","wellKnownProperties","throwWithStaticGenerationBailoutErrorWithDynamicError","throwForSearchParamsAccessInUseCache","createSearchParamsFromClient","underlyingSearchParams","workStore","getStore","workUnitStore","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","createServerSearchParamsForMetadata","metadataVaryParamsAccumulator","createServerSearchParamsForServerPage","varyParamsAccumulator","createRuntimePrerenderSearchParams","createPrerenderSearchParamsForClientPage","forceStatic","Promise","resolve","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","proxyHandler","target","prop","receiver","hasOwn","originalMethod","args","expression","dynamicAccessStore","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","makeErroringSearchParamsForUseCache","has","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createSearchAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,qBAAqB,QAChB,kCAAiC;AACxC,SAASC,yBAAyB,QAAQ,sDAAqD;AAE/F,SACEC,oBAAoB,EAKpBC,6BAA6B,QAGxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,sBAAsB,EACtBC,wBAAwB,EACxBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SACEC,4BAA4B,EAC5BC,iCAAiC,EACjCC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,qDAAqD,EACrDC,oCAAoC,QAC/B,UAAS;AAIhB,OAAO,SAASC,6BACdC,sBAAoC;IAEpC,MAAMC,YAAYvB,iBAAiBwB,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAId,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;I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 import { RouteModule } from '../route-module';

import { isStaticGenEnabled } from './helpers/is-static-gen-enabled';
import { abortAndThrowOnSynchronousRequestDataAccess, postponeWithTracking, createDynamicTrackingState, getFirstDynamicReason } from '../../app-render/dynamic-rendering';
import { abortAndThrowOnSynchronousRequestDataAccess, createDynamicTrackingState, getFirstDynamicReason } from '../../app-render/dynamic-rendering';
import { ReflectAdapter } from '../../web/spec-extension/adapters/reflect';

@@ -909,4 +909,2 @@ import { CacheSignal } from '../../app-render/cache-signal';

});
case 'prerender-ppr':
return postponeWithTracking(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -913,0 +911,0 @@ workUnitStore.revalidate = 0;

@@ -79,3 +79,3 @@ export const ENCODED_TAGS = {

META: {
// Only the match the prefix cause the suffix can be different wether it's xml compatible or not ">" or "/>"
// Only the match the prefix cause the suffix can be different whether it's xml compatible or not ">" or "/>"
// <meta name="«nxt-icon»"

@@ -82,0 +82,0 @@ // This is a special mark that will be replaced by the icon insertion script tag.

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/stream-utils/encoded-tags.ts"],"sourcesContent":["export const ENCODED_TAGS = {\n // opening tags do not have the closing `>` since they can contain other attributes such as `<body className=''>`\n OPENING: {\n // <html\n HTML: new Uint8Array([60, 104, 116, 109, 108]),\n // <head\n HEAD: new Uint8Array([60, 104, 101, 97, 100]),\n // <body\n BODY: new Uint8Array([60, 98, 111, 100, 121]),\n },\n CLOSED: {\n // </head>\n HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n // </body>\n BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n // </html>\n HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n // </body></html>\n BODY_AND_HTML: new Uint8Array([\n 60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,\n ]),\n },\n META: {\n // Only the match the prefix cause the suffix can be different wether it's xml compatible or not \">\" or \"/>\"\n // <meta name=\"«nxt-icon»\"\n // This is a special mark that will be replaced by the icon insertion script tag.\n ICON_MARK: new Uint8Array([\n 60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,\n 116, 45, 105, 99, 111, 110, 194, 187, 34,\n ]),\n },\n} as const\n"],"names":["ENCODED_TAGS","OPENING","HTML","Uint8Array","HEAD","BODY","CLOSED","BODY_AND_HTML","META","ICON_MARK"],"mappings":"AAAA,OAAO,MAAMA,eAAe;IAC1B,iHAAiH;IACjHC,SAAS;QACP,QAAQ;QACRC,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAK;YAAK;YAAK;SAAI;QAC7C,QAAQ;QACRC,MAAM,IAAID,WAAW;YAAC;YAAI;YAAK;YAAK;YAAI;SAAI;QAC5C,QAAQ;QACRE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;SAAI;IAC9C;IACAG,QAAQ;QACN,UAAU;QACVF,MAAM,IAAID,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAI;YAAK;SAAG;QACpD,UAAU;QACVE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;SAAG;QACpD,UAAU;QACVD,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAAG;QACrD,iBAAiB;QACjBI,eAAe,IAAIJ,WAAW;YAC5B;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAC5D;IACH;IACAK,MAAM;QACJ,4GAA4G;QAC5G,0BAA0B;QAC1B,iFAAiF;QACjFC,WAAW,IAAIN,WAAW;YACxB;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAK;YAAI;YAAK;YAAK;YAAI;YAAI;YAAK;YAAK;YAAK;YACrE;YAAK;YAAI;YAAK;YAAI;YAAK;YAAK;YAAK;YAAK;SACvC;IACH;AACF,EAAU","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/stream-utils/encoded-tags.ts"],"sourcesContent":["export const ENCODED_TAGS = {\n // opening tags do not have the closing `>` since they can contain other attributes such as `<body className=''>`\n OPENING: {\n // <html\n HTML: new Uint8Array([60, 104, 116, 109, 108]),\n // <head\n HEAD: new Uint8Array([60, 104, 101, 97, 100]),\n // <body\n BODY: new Uint8Array([60, 98, 111, 100, 121]),\n },\n CLOSED: {\n // </head>\n HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n // </body>\n BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n // </html>\n HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n // </body></html>\n BODY_AND_HTML: new Uint8Array([\n 60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,\n ]),\n },\n META: {\n // Only the match the prefix cause the suffix can be different whether it's xml compatible or not \">\" or \"/>\"\n // <meta name=\"«nxt-icon»\"\n // This is a special mark that will be replaced by the icon insertion script tag.\n ICON_MARK: new Uint8Array([\n 60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,\n 116, 45, 105, 99, 111, 110, 194, 187, 34,\n ]),\n },\n} as const\n"],"names":["ENCODED_TAGS","OPENING","HTML","Uint8Array","HEAD","BODY","CLOSED","BODY_AND_HTML","META","ICON_MARK"],"mappings":"AAAA,OAAO,MAAMA,eAAe;IAC1B,iHAAiH;IACjHC,SAAS;QACP,QAAQ;QACRC,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAK;YAAK;YAAK;SAAI;QAC7C,QAAQ;QACRC,MAAM,IAAID,WAAW;YAAC;YAAI;YAAK;YAAK;YAAI;SAAI;QAC5C,QAAQ;QACRE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;SAAI;IAC9C;IACAG,QAAQ;QACN,UAAU;QACVF,MAAM,IAAID,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAI;YAAK;SAAG;QACpD,UAAU;QACVE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;SAAG;QACpD,UAAU;QACVD,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAAG;QACrD,iBAAiB;QACjBI,eAAe,IAAIJ,WAAW;YAC5B;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAC5D;IACH;IACAK,MAAM;QACJ,6GAA6G;QAC7G,0BAA0B;QAC1B,iFAAiF;QACjFC,WAAW,IAAIN,WAAW;YACxB;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAK;YAAI;YAAK;YAAK;YAAI;YAAI;YAAK;YAAK;YAAK;YACrE;YAAK;YAAI;YAAK;YAAI;YAAK;YAAK;YAAK;YAAK;SACvC;IACH;AACF,EAAU","ignoreList":[0]}

@@ -18,3 +18,2 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external';

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -21,0 +20,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/use-cache/cache-life.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateAndNormalizeCacheLifeProfile } from './cache-life-profile'\nimport type { CacheLife } from './cache-life-profile'\n\nexport type { CacheLife }\n\n// The equivalent header is kind of like:\n// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]\n// Except that stale-while-revalidate/stale-if-error only applies to shared caches - not private caches.\n\n// The default revalidates relatively frequently but doesn't expire to ensure it's always\n// able to serve fast results but by default doesn't hang.\n\n// This gets overridden by the next-types-plugin\ntype CacheLifeProfiles =\n | 'default'\n | 'seconds'\n | 'minutes'\n | 'hours'\n | 'days'\n | 'weeks'\n | 'max'\n | (string & {})\n\nexport function cacheLife(profile: CacheLifeProfiles | CacheLife): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheLife()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheLife()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n if (typeof profile === 'string') {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new Error(\n '`cacheLife()` can only be called during App Router rendering at the moment.'\n )\n }\n\n // TODO: This should be globally available and not require an AsyncLocalStorage.\n const configuredProfile = workStore.cacheLifeProfiles[profile]\n if (configuredProfile === undefined) {\n if (workStore.cacheLifeProfiles[profile.trim()]) {\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n `Did you mean \"${profile.trim()}\" without the spaces?`\n )\n }\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n 'module.exports = {\\n' +\n ' cacheLife: {\\n' +\n ` \"${profile}\": ...\\n` +\n ' }\\n' +\n '}'\n )\n }\n profile = configuredProfile\n } else if (\n typeof profile !== 'object' ||\n profile === null ||\n Array.isArray(profile)\n ) {\n throw new Error(\n 'Invalid `cacheLife()` option. Either pass a profile name or object.'\n )\n } else {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n\n if (profile.revalidate !== undefined) {\n // Track the explicit revalidate time.\n if (\n workUnitStore.explicitRevalidate === undefined ||\n workUnitStore.explicitRevalidate > profile.revalidate\n ) {\n workUnitStore.explicitRevalidate = profile.revalidate\n }\n }\n if (profile.expire !== undefined) {\n // Track the explicit expire time.\n if (\n workUnitStore.explicitExpire === undefined ||\n workUnitStore.explicitExpire > profile.expire\n ) {\n workUnitStore.explicitExpire = profile.expire\n }\n }\n if (profile.stale !== undefined) {\n // Track the explicit stale time.\n if (\n workUnitStore.explicitStale === undefined ||\n workUnitStore.explicitStale > profile.stale\n ) {\n workUnitStore.explicitStale = profile.stale\n }\n }\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","validateAndNormalizeCacheLifeProfile","cacheLife","profile","process","env","__NEXT_USE_CACHE","Error","workUnitStore","getStore","type","undefined","workStore","configuredProfile","cacheLifeProfiles","trim","Array","isArray","kind","revalidate","explicitRevalidate","expire","explicitExpire","stale","explicitStale"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,oCAAoC,QAAQ,uBAAsB;AAuB3E,OAAO,SAASC,UAAUC,OAAsC;IAC9D,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,uEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBR,qBAAqBS,QAAQ;IAEnD,OAAQD,iCAAAA,cAAeE,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;YACH,MAAM,qBAEL,CAFK,IAAIJ,MACR,oEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;QACL,KAAK;YACH;QACF;YACEC;IACJ;IAEA,IAAI,OAAOL,YAAY,UAAU;QAC/B,MAAMS,YAAYb,iBAAiBU,QAAQ;QAC3C,IAAI,CAACG,WAAW;YACd,MAAM,qBAEL,CAFK,IAAIL,MACR,gFADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,gFAAgF;QAChF,MAAMM,oBAA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B,aAAa,GAAGrB,QAAQoB,KAAK,EAC3C;YACAf,cAAcgB,aAAa,GAAGrB,QAAQoB,KAAK;QAC7C;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/use-cache/cache-life.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateAndNormalizeCacheLifeProfile } from './cache-life-profile'\nimport type { CacheLife } from './cache-life-profile'\n\nexport type { CacheLife }\n\n// The equivalent header is kind of like:\n// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]\n// Except that stale-while-revalidate/stale-if-error only applies to shared caches - not private caches.\n\n// The default revalidates relatively frequently but doesn't expire to ensure it's always\n// able to serve fast results but by default doesn't hang.\n\n// This gets overridden by the next-types-plugin\ntype CacheLifeProfiles =\n | 'default'\n | 'seconds'\n | 'minutes'\n | 'hours'\n | 'days'\n | 'weeks'\n | 'max'\n | (string & {})\n\nexport function cacheLife(profile: CacheLifeProfiles | CacheLife): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheLife()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheLife()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n if (typeof profile === 'string') {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new Error(\n '`cacheLife()` can only be called during App Router rendering at the moment.'\n )\n }\n\n // TODO: This should be globally available and not require an AsyncLocalStorage.\n const configuredProfile = workStore.cacheLifeProfiles[profile]\n if (configuredProfile === undefined) {\n if (workStore.cacheLifeProfiles[profile.trim()]) {\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n `Did you mean \"${profile.trim()}\" without the spaces?`\n )\n }\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n 'module.exports = {\\n' +\n ' cacheLife: {\\n' +\n ` \"${profile}\": ...\\n` +\n ' }\\n' +\n '}'\n )\n }\n profile = configuredProfile\n } else if (\n typeof profile !== 'object' ||\n profile === null ||\n Array.isArray(profile)\n ) {\n throw new Error(\n 'Invalid `cacheLife()` option. Either pass a profile name or object.'\n )\n } else {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n\n if (profile.revalidate !== undefined) {\n // Track the explicit revalidate time.\n if (\n workUnitStore.explicitRevalidate === undefined ||\n workUnitStore.explicitRevalidate > profile.revalidate\n ) {\n workUnitStore.explicitRevalidate = profile.revalidate\n }\n }\n if (profile.expire !== undefined) {\n // Track the explicit expire time.\n if (\n workUnitStore.explicitExpire === undefined ||\n workUnitStore.explicitExpire > profile.expire\n ) {\n workUnitStore.explicitExpire = profile.expire\n }\n }\n if (profile.stale !== undefined) {\n // Track the explicit stale time.\n if (\n workUnitStore.explicitStale === undefined ||\n workUnitStore.explicitStale > profile.stale\n ) {\n workUnitStore.explicitStale = profile.stale\n }\n }\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","validateAndNormalizeCacheLifeProfile","cacheLife","profile","process","env","__NEXT_USE_CACHE","Error","workUnitStore","getStore","type","undefined","workStore","configuredProfile","cacheLifeProfiles","trim","Array","isArray","kind","revalidate","explicitRevalidate","expire","explicitExpire","stale","explicitStale"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,oCAAoC,QAAQ,uBAAsB;AAuB3E,OAAO,SAASC,UAAUC,OAAsC;IAC9D,IAAI,CAACC,QAAQC,G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,IAAII,MACR,wEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF,OAAO;QACLJ,UAAUF,qCAAqCE,SAAS;YAAEe,MAAM;QAAS;IAC3E;IAEA,IAAIf,QAAQgB,UAAU,KAAKR,WAAW;QACpC,sCAAsC;QACtC,IACEH,cAAcY,kBAAkB,KAAKT,aACrCH,cAAcY,kBAAkB,GAAGjB,QAAQgB,UAAU,EACrD;YACAX,cAAcY,kBAAkB,GAAGjB,QAAQgB,UAAU;QACvD;IACF;IACA,IAAIhB,QAAQkB,MAAM,KAAKV,WAAW;QAChC,kCAAkC;QAClC,IACEH,cAAcc,cAAc,KAAKX,aACjCH,cAAcc,cAAc,GAAGnB,QAAQkB,MAAM,EAC7C;YACAb,cAAcc,cAAc,GAAGnB,QAAQkB,MAAM;QAC/C;IACF;IACA,IAAIlB,QAAQoB,KAAK,KAAKZ,WAAW;QAC/B,iCAAiC;QACjC,IACEH,cAAcgB,aAAa,KAAKb,aAChCH,cAAcgB,aAAa,GAAGrB,QAAQoB,KAAK,EAC3C;YACAf,cAAcgB,aAAa,GAAGrB,QAAQoB,KAAK;QAC7C;IACF;AACF","ignoreList":[0]}

@@ -17,3 +17,2 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -20,0 +19,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/use-cache/cache-tag.ts"],"sourcesContent":["import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateTags } from '../lib/patch-fetch'\n\nexport function cacheTag(...tags: string[]): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheTag()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheTag()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n const validTags = validateTags(tags, '`cacheTag()`')\n\n if (!workUnitStore.tags) {\n workUnitStore.tags = validTags\n } else {\n workUnitStore.tags.push(...validTags)\n }\n}\n"],"names":["workUnitAsyncStorage","validateTags","cacheTag","tags","process","env","__NEXT_USE_CACHE","Error","workUnitStore","getStore","type","undefined","validTags","push"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,YAAY,QAAQ,qBAAoB;AAEjD,OAAO,SAASC,SAAS,GAAGC,IAAc;IACxC,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,sEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBR,qBAAqBS,QAAQ;IAEnD,OAAQD,iCAAAA,cAAeE,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;YACH,MAAM,qBAEL,CAFK,IAAIJ,MACR,mEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;QACL,KAAK;YACH;QACF;YACEC;IACJ;IAEA,MAAMI,YAAYX,aAAaE,MAAM;IAErC,IAAI,CAACK,cAAcL,IAAI,EAAE;QACvBK,cAAcL,IAAI,GAAGS;IACvB,OAAO;QACLJ,cAAcL,IAAI,CAACU,IAAI,IAAID;IAC7B;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/use-cache/cache-tag.ts"],"sourcesContent":["import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateTags } from '../lib/patch-fetch'\n\nexport function cacheTag(...tags: string[]): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheTag()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheTag()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n const validTags = validateTags(tags, '`cacheTag()`')\n\n if (!workUnitStore.tags) {\n workUnitStore.tags = validTags\n } else {\n workUnitStore.tags.push(...validTags)\n }\n}\n"],"names":["workUnitAsyncStorage","validateTags","cacheTag","tags","process","env","__NEXT_USE_CACHE","Error","workUnitStore","getStore","type","undefined","validTags","push"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,YAAY,QAAQ,qBAAoB;AAEjD,OAAO,SAASC,SAAS,GAAGC,IAAc;IACxC,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,sEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBR,qBAAqBS,QAAQ;IAEnD,OAAQD,iCAAAA,cAAeE,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;YACH,MAAM,qBAEL,CAFK,IAAIJ,MACR,mEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;QACL,KAAK;YACH;QACF;YACEC;IACJ;IAEA,MAAMI,YAAYX,aAAaE,MAAM;IAErC,IAAI,CAACK,cAAcL,IAAI,EAAE;QACvBK,cAAcL,IAAI,GAAGS;IACvB,OAAO;QACLJ,cAAcL,IAAI,CAACU,IAAI,IAAID;IAC7B;AACF","ignoreList":[0]}

@@ -1,2 +0,2 @@

import { abortAndThrowOnSynchronousRequestDataAccess, postponeWithTracking } from '../../app-render/dynamic-rendering';
import { abortAndThrowOnSynchronousRequestDataAccess } from '../../app-render/dynamic-rendering';
import { isDynamicRoute } from '../../../shared/lib/router/utils';

@@ -152,4 +152,2 @@ import { NEXT_CACHE_IMPLICIT_TAG_ID, NEXT_CACHE_SOFT_TAG_MAX_LENGTH } from '../../../lib/constants';

});
case 'prerender-ppr':
return postponeWithTracking(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -156,0 +154,0 @@ workUnitStore.revalidate = 0;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n} from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["abortAndThrowOnSynchronousRequestDataAccess","postponeWithTracking","isDynamicRoute","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","workAsyncStorage","workUnitAsyncStorage","DynamicServerError","InvariantError","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic","ActionDidRevalidate","removeTrailingSlash","encodeHeaderSafe","validateAndNormalizeCacheLifeProfile","revalidateTag","tag","profile","console","warn","kind","revalidate","updateTag","workStore","getStore","page","endsWith","Error","undefined","refresh","workUnitStore","phase","pathWasRevalidated","revalidatePath","originalPath","type","length","normalizedPath","tags","push","expression","store","incrementalCache","route","error","dynamicTracking","err","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire"],"mappings":"AAAA,SACEA,2CAA2C,EAC3CC,oBAAoB,QACf,qCAAoC;AAC3C,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,8BAA8B,QACzB,yBAAwB;AAC/B,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,oBAAoB,QAAQ,oDAAmD;AACxF,SAASC,kBAAkB,QAAQ,kDAAiD;AACpF,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SACEC,8BAA8B,EAC9BC,uCAAuCC,mBAAmB,QACrD,+CAA8C;AACrD,SAASC,mBAAmB,QAAQ,yDAAwD;AAC5F,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,oCAAoC,QAAQ,qCAAoC;AAMzF;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAcC,GAAW,EAAEC,OAAiC;IAC1E,IAAI,CAACA,SAAS;QACZC,QAAQC,IAAI,CACV;IAEJ,OAAO,IAAI,OAAOF,YAAY,UAAU;QACtCA,UAAUH,qCAAqCG,SAAS;YAAEG,MAAM;QAAS;IAC3E;IACA,OAAOC,WAAW;QAACR,iBAAiBG;KAAK,EAAE,CAAC,cAAc,EAAEA,KAAK,EAAEC;AACrE;AAEA;;;;;CAKC,GACD,OAAO,SAASK,UAAUN,GAAW;IACnC,MAAMO,YAAYlB,iBAAiBmB,QAAQ;IAE3C,+DAA+D;IAC/D,yBAAyB;IACzB,IAAI,CAACD,aAAaA,UAAUE,IAAI,CAACC,QAA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,KAAK7C,GAAG,KAAKA,KAAK,OAAO;YAC7B,kEAAkE;YAClE,IAAI,OAAO6C,KAAK5C,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAO4C,KAAK5C,OAAO,KAAKA;YAC1B;YACA,IAAI,OAAO4C,KAAK5C,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAO6C,KAAKC,SAAS,CAACF,KAAK5C,OAAO,MAAM6C,KAAKC,SAAS,CAAC9C;YACzD;YACA,OAAO4C,KAAK5C,OAAO,KAAKA;QAC1B;QACA,IAAI0C,kBAAkB,CAAC,GAAG;YACxBlB,MAAMa,sBAAsB,CAACf,IAAI,CAAC;gBAChCvB;gBACAC;gBACAsC;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACTd,MAAMa,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJ/C,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnBwB,yBAAAA,MAAOwB,iBAAiB,CAAChD,QAAQ,IACjCwB,MAAMwB,iBAAiB,CAAChD,QAAQ,GAChCW;IAER,IAAI,CAACX,WAAW+C,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5CzB,MAAMT,kBAAkB,GAAGrB;IAC7B;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import { abortAndThrowOnSynchronousRequestDataAccess } from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["abortAndThrowOnSynchronousRequestDataAccess","isDynamicRoute","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","workAsyncStorage","workUnitAsyncStorage","DynamicServerError","InvariantError","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic","ActionDidRevalidate","removeTrailingSlash","encodeHeaderSafe","validateAndNormalizeCacheLifeProfile","revalidateTag","tag","profile","console","warn","kind","revalidate","updateTag","workStore","getStore","page","endsWith","Error","undefined","refresh","workUnitStore","phase","pathWasRevalidated","revalidatePath","originalPath","type","length","normalizedPath","tags","push","expression","store","incrementalCache","route","error","err","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire"],"mappings":"AAAA,SAASA,2CAA2C,QAAQ,qCAAoC;AAChG,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,8BAA8B,QACzB,yBAAwB;AAC/B,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,oBAAoB,QAAQ,oDAAmD;AACxF,SAASC,kBAAkB,QAAQ,kDAAiD;AACpF,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SACEC,8BAA8B,EAC9BC,uCAAuCC,mBAAmB,QACrD,+CAA8C;AACrD,SAASC,mBAAmB,QAAQ,yDAAwD;AAC5F,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,oCAAoC,QAAQ,qCAAoC;AAMzF;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAcC,GAAW,EAAEC,OAAiC;IAC1E,IAAI,CAACA,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]}

@@ -116,3 +116,2 @@ import { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants';

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -292,3 +291,2 @@ // We update the store's revalidate property if the revalidate option is a higher precedence

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -295,0 +293,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["CACHE_ONE_YEAR_SECONDS","validateRevalidate","validateTags","encodeHeaderSafe","workAsyncStorage","getCacheSignal","getDraftModeProviderForCacheScope","willConsumerServerCache","workUnitAsyncStorage","CachedRouteKind","IncrementalCacheKind","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","FETCH","data","headers","body","JSON","stringify","status","url","fetchCache","unstable_cache","cb","keyParts","options","Error","toString","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","getStore","workUnitStore","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":"AAEA,SAASA,sBAAsB,QAAQ,yBAAwB;AAC/D,SAASC,kBAAkB,EAAEC,YAAY,QAAQ,wBAAuB;AACxE,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SACEC,gBAAgB,QAEX,+CAA8C;AACrD,SACEC,cAAc,EACdC,iCAAiC,EACjCC,uBAAuB,EACvBC,oBAAoB,QACf,oDAAmD;AAC1D,SACEC,eAAe,EACfC,oBAAoB,QAEf,uBAAsB;AAQ7B,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB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,CAACoB,WAAWQ,OAAO,EAAE;4BAC9B,8DAA8D;4BAC9D,OAAOR,WAAWG,KAAK,CAACtD,IAAI,CAACE,IAAI,KAAKwC,YAClCvC,KAAKuD,KAAK,CAACP,WAAWG,KAAK,CAACtD,IAAI,CAACE,IAAI,IACrCwC;wBACN;oBACF;gBACF;gBAEA,uFAAuF;gBACvF,MAAMpD,SAAS,MAAML,qBAAqB6E,GAAG,CAC3C1B,iBACA3B,OACGW;gBAGL,uDAAuD;gBACvD,oDAAoD;gBACpD,+CAA+C;gBAC/C,MAAM/B,eACJC,QACAC,kBACAC,UACAC,MACAC,YACAC,UACAC;gBAEF,OAAON;YACT;QACF,SAAU;YACR,IAAIqC,aAAa;gBACfA,YAAYuC,OAAO;YACrB;QACF;IACF;IACA,yGAAyG;IACzG,OAAO/C;AACT;AAEA,SAASW,kBACPT,SAAoB,EACpBE,aAA4B;IAE5B,OAAQA,cAAcc,IAAI;QACxB,KAAK;YACH,MAAM8B,WAAW5C,cAAcjB,GAAG,CAAC6D,QAAQ;YAC3C,MAAMC,eAAe,IAAIC,gBAAgB9C,cAAcjB,GAAG,CAACgE,MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAahB,GAAG,CAAC0B,MAAM,EAC9C5D,IAAI,CAAC;YAER,OAAO,GAAGiD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOlD,UAAU2D,KAAK;QACxB;YACE,OAAOzD;IACX;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["CACHE_ONE_YEAR_SECONDS","validateRevalidate","validateTags","encodeHeaderSafe","workAsyncStorage","getCacheSignal","getDraftModeProviderForCacheScope","willConsumerServerCache","workUnitAsyncStorage","CachedRouteKind","IncrementalCacheKind","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","FETCH","data","headers","body","JSON","stringify","status","url","fetchCache","unstable_cache","cb","keyParts","options","Error","toString","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","getStore","workUnitStore","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":"AAEA,SAASA,sBAAsB,QAAQ,yBAAwB;AAC/D,SAASC,kBAAkB,EAAEC,YAAY,QAAQ,wBAAuB;AACxE,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SACEC,gBAAgB,QAEX,+CAA8C;AACrD,SACEC,cAAc,EACdC,iCAAiC,EACjCC,uBAAuB,EACvBC,oBAAoB,QACf,oDAAmD;AAC1D,SACEC,eAAe,EACfC,oBAAoB,QAEf,uBAAsB;AAQ7B,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMZ,gBAAgBa,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACd;YACrBe,QAAQ;YACRC,KAAK;QACP;QACAZ,YACE,OAAOA,eAAe,WAAWjB,yBAAyBiB;IAC9D,GACA;QAAEa,YAAY;QAAMd;QAAME;QAAUC;IAAS;IAE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eACJC,QACAC,kBACAC,UACAC,MACAC,YACAC,UACAC;gBAEF,OAAON;YACT;QACF,SAAU;YACR,IAAIqC,aAAa;gBACfA,YAAYuC,OAAO;YACrB;QACF;IACF;IACA,yGAAyG;IACzG,OAAO/C;AACT;AAEA,SAASW,kBACPT,SAAoB,EACpBE,aAA4B;IAE5B,OAAQA,cAAcc,IAAI;QACxB,KAAK;YACH,MAAM8B,WAAW5C,cAAcjB,GAAG,CAAC6D,QAAQ;YAC3C,MAAMC,eAAe,IAAIC,gBAAgB9C,cAAcjB,GAAG,CAACgE,MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAahB,GAAG,CAAC0B,MAAM,EAC9C5D,IAAI,CAAC;YAER,OAAO,GAAGiD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOlD,UAAU2D,KAAK;QACxB;YACE,OAAOzD;IACX;AACF","ignoreList":[0]}

@@ -39,3 +39,2 @@ import { workAsyncStorage } from '../../app-render/work-async-storage.external';

return;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -42,0 +41,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../../src/server/web/spec-extension/unstable-no-store.ts"],"sourcesContent":["import { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'\n\n/**\n * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.\n *\n * It marks the current scope as dynamic.\n *\n * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render\n * halt and mark the page as dynamic.\n * - In PPR cases this will postpone the render at this location.\n *\n * If we are inside a cache scope then this function does nothing.\n *\n * @note It expects to be called within App Router and will error otherwise.\n *\n * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)\n */\nexport function unstable_noStore() {\n const callingExpression = 'unstable_noStore()'\n const store = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!store) {\n // This generally implies we are being called in Pages router. We should probably not support\n // unstable_noStore in contexts outside of `react-server` condition but since we historically\n // have not errored here previously, we maintain that behavior for now.\n return\n } else if (store.forceStatic) {\n return\n } else {\n store.isUnstableNoStore = true\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n // unstable_noStore() is a noop in Dynamic I/O.\n return\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)\n }\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","markCurrentScopeAsDynamic","unstable_noStore","callingExpression","store","getStore","workUnitStore","forceStatic","isUnstableNoStore","type"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,oBAAoB,QAAQ,oDAAmD;AACxF,SAASC,yBAAyB,QAAQ,qCAAoC;AAE9E;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,QAAQL,iBAAiBM,QAAQ;IACvC,MAAMC,gBAAgBN,qBAAqBK,QAAQ;IACnD,IAAI,CAACD,OAAO;QACV,6FAA6F;QAC7F,6FAA6F;QAC7F,uEAAuE;QACvE;IACF,OAAO,IAAIA,MAAMG,WAAW,EAAE;QAC5B;IACF,OAAO;QACLH,MAAMI,iBAAiB,GAAG;QAC1B,IAAIF,eAAe;YACjB,OAAQA,cAAcG,IAAI;gBACxB,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH,+CAA+C;oBAC/C;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH;gBACF;oBACEH;YACJ;QACF;QACAL,0BAA0BG,OAAOE,eAAeH;IAClD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../../src/server/web/spec-extension/unstable-no-store.ts"],"sourcesContent":["import { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'\n\n/**\n * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.\n *\n * It marks the current scope as dynamic.\n *\n * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render\n * halt and mark the page as dynamic.\n * - In PPR cases this will postpone the render at this location.\n *\n * If we are inside a cache scope then this function does nothing.\n *\n * @note It expects to be called within App Router and will error otherwise.\n *\n * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)\n */\nexport function unstable_noStore() {\n const callingExpression = 'unstable_noStore()'\n const store = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!store) {\n // This generally implies we are being called in Pages router. We should probably not support\n // unstable_noStore in contexts outside of `react-server` condition but since we historically\n // have not errored here previously, we maintain that behavior for now.\n return\n } else if (store.forceStatic) {\n return\n } else {\n store.isUnstableNoStore = true\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n // unstable_noStore() is a noop in Dynamic I/O.\n return\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)\n }\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","markCurrentScopeAsDynamic","unstable_noStore","callingExpression","store","getStore","workUnitStore","forceStatic","isUnstableNoStore","type"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,oBAAoB,QAAQ,oDAAmD;AACxF,SAASC,yBAAyB,QAAQ,qCAAoC;AAE9E;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,QAAQL,iBAAiBM,QAAQ;IACvC,MAAMC,gBAAgBN,qBAAqBK,QAAQ;IACnD,IAAI,CAACD,OAAO;QACV,6FAA6F;QAC7F,6FAA6F;QAC7F,uEAAuE;QACvE;IACF,OAAO,IAAIA,MAAMG,WAAW,EAAE;QAC5B;IACF,OAAO;QACLH,MAAMI,iBAAiB,GAAG;QAC1B,IAAIF,eAAe;YACjB,OAAQA,cAAcG,IAAI;gBACxB,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH,+CAA+C;oBAC/C;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH;gBACF;oBACEH;YACJ;QACF;QACAL,0BAA0BG,OAAOE,eAAeH;IAClD;AACF","ignoreList":[0]}
export function isStableBuild() {
return !"16.3.1-canary.11"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV;
return !"16.3.1-canary.12"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV;
}

@@ -4,0 +4,0 @@ export class CanaryOnlyConfigError extends Error {

@@ -1,1 +0,1 @@

export declare const isDynamicUsageError: (err: unknown) => boolean;
export declare const isDynamicUsageError: (err: unknown) => err is import("../../client/components/hooks-server-context").DynamicServerError | import("../../shared/lib/lazy-dynamic/bailout-to-csr").BailoutToCSRError | import("../../client/components/http-access-fallback/http-access-fallback").HTTPAccessFallbackError | import("../../client/components/redirect-error").RedirectError;

@@ -14,5 +14,4 @@ "use strict";

const _isnextroutererror = require("../../client/components/is-next-router-error");
const _dynamicrendering = require("../../server/app-render/dynamic-rendering");
const isDynamicUsageError = (err)=>(0, _hooksservercontext.isDynamicServerError)(err) || (0, _bailouttocsr.isBailoutToCSRError)(err) || (0, _isnextroutererror.isNextRouterError)(err) || (0, _dynamicrendering.isDynamicPostpone)(err);
const isDynamicUsageError = (err)=>(0, _hooksservercontext.isDynamicServerError)(err) || (0, _bailouttocsr.isBailoutToCSRError)(err) || (0, _isnextroutererror.isNextRouterError)(err);
//# sourceMappingURL=is-dynamic-usage-error.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/export/helpers/is-dynamic-usage-error.ts"],"sourcesContent":["import { isDynamicServerError } from '../../client/components/hooks-server-context'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\nimport { isDynamicPostpone } from '../../server/app-render/dynamic-rendering'\n\nexport const isDynamicUsageError = (err: unknown) =>\n isDynamicServerError(err) ||\n isBailoutToCSRError(err) ||\n isNextRouterError(err) ||\n isDynamicPostpone(err)\n"],"names":["isDynamicUsageError","err","isDynamicServerError","isBailoutToCSRError","isNextRouterError","isDynamicPostpone"],"mappings":";;;;+BAKaA;;;eAAAA;;;oCALwB;8BACD;mCACF;kCACA;AAE3B,MAAMA,sBAAsB,CAACC,MAClCC,IAAAA,wCAAoB,EAACD,QACrBE,IAAAA,iCAAmB,EAACF,QACpBG,IAAAA,oCAAiB,EAACH,QAClBI,IAAAA,mCAAiB,EAACJ","ignoreList":[0]}
{"version":3,"sources":["../../../src/export/helpers/is-dynamic-usage-error.ts"],"sourcesContent":["import { isDynamicServerError } from '../../client/components/hooks-server-context'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from '../../client/components/is-next-router-error'\n\nexport const isDynamicUsageError = (err: unknown) =>\n isDynamicServerError(err) ||\n isBailoutToCSRError(err) ||\n isNextRouterError(err)\n"],"names":["isDynamicUsageError","err","isDynamicServerError","isBailoutToCSRError","isNextRouterError"],"mappings":";;;;+BAIaA;;;eAAAA;;;oCAJwB;8BACD;mCACF;AAE3B,MAAMA,sBAAsB,CAACC,MAClCC,IAAAA,wCAAoB,EAACD,QACrBE,IAAAA,iCAAmB,EAACF,QACpBG,IAAAA,oCAAiB,EAACH","ignoreList":[0]}

@@ -684,3 +684,3 @@ "use strict";

// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
if (!options.buildExport && nextConfig.cacheComponents) {
// TODO: add message

@@ -687,0 +687,0 @@ throw Object.defineProperty(new Error('Invariant: PPR cannot be enabled in export mode'), "__NEXT_ERROR_CODE", {

@@ -33,3 +33,2 @@ "use strict";

const _createincrementalcache = require("./helpers/create-incremental-cache");
const _ispostpone = require("../server/lib/router-utils/is-postpone");
const _isdynamicusageerror = require("./helpers/is-dynamic-usage-error");

@@ -422,7 +421,2 @@ const _bailouttocsr = require("../shared/lib/lazy-dynamic/bailout-to-csr");

process.on('unhandledRejection', (err)=>{
// if it's a postpone error, it'll be handled later
// when the postponed promise is actually awaited.
if ((0, _ispostpone.isPostpone)(err)) {
return;
}
// we don't want to log these errors

@@ -429,0 +423,0 @@ if ((0, _isdynamicusageerror.isDynamicUsageError)(err)) {

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../src/export/worker.ts"],"sourcesContent":["import type {\n ExportPagesInput,\n ExportPageInput,\n ExportPageResult,\n ExportRouteResult,\n WorkerRenderOpts,\n ExportPagesResult,\n ExportPathEntry,\n} from './types'\nimport type { AppPageModule } from '../server/route-modules/app-page/module'\nimport type { PagesModule } from '../server/route-modules/pages/module.compiled'\n\nimport '../server/node-environment'\nimport { installBindings } from '../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../server/lib/install-code-frame'\n\nprocess.env.NEXT_IS_EXPORT_WORKER = 'true'\n\nimport { extname, join, dirname, sep } from 'path'\nimport fs from 'fs/promises'\nimport { loadComponents } from '../server/load-components'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { trace } from '../trace'\nimport { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'\nimport { addRequestMeta } from '../server/request-meta'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\n\nimport { createRequestResponseMocks } from '../server/lib/mock-request'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { hasNextSupport } from '../server/ci-info'\nimport { exportAppRoute } from './routes/app-route'\nimport { exportAppPage } from './routes/app-page'\nimport { exportPagesPage } from './routes/pages'\nimport { getParams } from './helpers/get-params'\nimport { createIncrementalCache } from './helpers/create-incremental-cache'\nimport { isPostpone } from '../server/lib/router-utils/is-postpone'\nimport { isDynamicUsageError } from './helpers/is-dynamic-usage-error'\nimport { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'\nimport {\n turborepoTraceAccess,\n TurborepoAccessTraceResult,\n} from '../build/turborepo-access-trace'\nimport type { Params } from '../server/request/params'\nimport {\n createOpaqueFallbackRouteParams,\n type OpaqueFallbackRouteParams,\n} from '../server/request/fallback-params'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'\nimport { isStaticGenBailoutError } from '../client/components/static-generation-bailout'\nimport type { PagesRenderContext, PagesSharedContext } from '../server/render'\nimport type { AppSharedContext } from '../server/app-render/app-render'\nimport { MultiFileWriter } from '../lib/multi-file-writer'\nimport { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'\nimport { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'\n;(globalThis as any).__NEXT_DATA__ = {\n nextExport: true,\n}\n\nclass TimeoutError extends Error {\n code = 'NEXT_EXPORT_TIMEOUT_ERROR'\n}\n\nclass ExportPageError extends Error {\n code = 'NEXT_EXPORT_PAGE_ERROR'\n}\n\nasync function exportPageImpl(\n input: ExportPageInput,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const {\n exportPath,\n distDir,\n pagesDataDir,\n buildExport = false,\n subFolders = false,\n optimizeCss,\n disableOptimizedLoading,\n debugOutput = false,\n enableExperimentalReact,\n trailingSlash,\n sriEnabled,\n renderOpts: commonRenderOpts,\n outDir: commonOutDir,\n buildId,\n deploymentId,\n clientAssetToken,\n renderResumeDataCache,\n } = input\n\n if (enableExperimentalReact) {\n process.env.__NEXT_EXPERIMENTAL_REACT = 'true'\n }\n\n const {\n path,\n page,\n\n // The parameters that are currently unknown.\n _fallbackRouteParams = [],\n\n // Check if this is an `app/` page.\n _isAppDir: isAppDir = false,\n\n // Check if this should error when dynamic usage is detected.\n _isDynamicError: isDynamicError = false,\n\n // If this page supports partial prerendering, then we need to pass that to\n // the renderOpts.\n _isRoutePPREnabled: isRoutePPREnabled,\n\n // Configure the rendering of the page to allow that an empty static shell\n // is generated while rendering using PPR and Cache Components.\n _allowEmptyStaticShell: allowEmptyStaticShell = false,\n\n // When true, attempt to run build-time instant validation for this export path.\n _runInstantValidation: runInstantValidation = false,\n\n // When true, a fallback shell for this path could later be upgraded to a\n // concrete version (it has a `generateStaticParams` candidate param).\n _isFallbackUpgradeable: isFallbackUpgradeable = false,\n\n // Pull the original query out.\n query: originalQuery = {},\n } = exportPath\n\n const fallbackRouteParams: OpaqueFallbackRouteParams | null =\n createOpaqueFallbackRouteParams(_fallbackRouteParams)\n\n let query = { ...originalQuery }\n const pathname = normalizeAppPath(page)\n const isDynamic = isDynamicRoute(page)\n const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir\n\n const filePath = normalizePagePath(path)\n\n let updatedPath = exportPath._ssgPath || path\n let locale = exportPath._locale || commonRenderOpts.locale\n\n if (commonRenderOpts.locale) {\n const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales)\n\n if (localePathResult.detectedLocale) {\n updatedPath = localePathResult.pathname\n locale = localePathResult.detectedLocale\n }\n }\n\n // We need to show a warning if they try to provide query values\n // for an auto-exported page since they won't be available\n const hasOrigQueryValues = Object.keys(originalQuery).length > 0\n\n // Check if the page is a specified dynamic route\n const { pathname: nonLocalizedPath } = normalizeLocalePath(\n path,\n commonRenderOpts.locales\n )\n\n let params: Params | undefined\n\n if (isDynamic && page !== nonLocalizedPath) {\n const normalizedPage = isAppDir ? normalizeAppPath(page) : page\n\n params = getParams(normalizedPage, updatedPath)\n }\n\n const { req, res } = createRequestResponseMocks({ url: updatedPath })\n\n // If this is a status code page, then set the response code.\n for (const statusCode of [404, 500]) {\n if (\n [\n `/${statusCode}`,\n `/${statusCode}.html`,\n `/${statusCode}/index.html`,\n ].some((p) => p === updatedPath || `/${locale}${p}` === updatedPath)\n ) {\n res.statusCode = statusCode\n }\n }\n\n // Ensure that the URL has a trailing slash if it's configured.\n if (trailingSlash && !req.url?.endsWith('/')) {\n req.url += '/'\n }\n\n // Set the resolved pathname without trailing slash as request metadata.\n addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath))\n\n if (\n locale &&\n buildExport &&\n commonRenderOpts.domainLocales &&\n commonRenderOpts.domainLocales.some(\n (dl) => dl.defaultLocale === locale || dl.locales?.includes(locale || '')\n )\n ) {\n addRequestMeta(req, 'isLocaleDomain', true)\n }\n\n const getHtmlFilename = (p: string) =>\n subFolders ? `${p}${sep}index.html` : `${p}.html`\n\n let htmlFilename = getHtmlFilename(filePath)\n\n // dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an\n // extension of `.slug]`\n const pageExt = isDynamic || isAppDir ? '' : extname(page)\n const pathExt = isDynamic || isAppDir ? '' : extname(path)\n\n // force output 404.html for backwards compat\n if (path === '/404.html') {\n htmlFilename = path\n }\n // Make sure page isn't a folder with a dot in the name e.g. `v1.2`\n else if (pageExt !== pathExt && pathExt !== '') {\n const isBuiltinPaths = ['/500', '/404'].some(\n (p) => p === path || p === path + '.html'\n )\n // If the ssg path has .html extension, and it's not builtin paths, use it directly\n // Otherwise, use that as the filename instead\n const isHtmlExtPath = !isBuiltinPaths && path.endsWith('.html')\n htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path\n } else if (path === '/') {\n // If the path is the root, just use index.html\n htmlFilename = 'index.html'\n }\n\n const baseDir = join(outDir, dirname(htmlFilename))\n let htmlFilepath = join(outDir, htmlFilename)\n\n await fs.mkdir(baseDir, { recursive: true })\n\n const components = await loadComponents({\n distDir,\n page,\n isAppPath: isAppDir,\n isDev: false,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n // Handle App Routes.\n if (isAppDir && isAppRouteRoute(page)) {\n return exportAppRoute(\n req,\n res,\n params,\n page,\n components.routeModule as AppRouteRouteModule,\n commonRenderOpts.incrementalCache,\n commonRenderOpts.cacheLifeProfiles,\n htmlFilepath,\n fileWriter,\n commonRenderOpts.cacheComponents,\n commonRenderOpts.staticPageGenerationTimeout,\n commonRenderOpts.experimental,\n buildId,\n deploymentId\n )\n }\n\n const renderOpts: WorkerRenderOpts = {\n ...components,\n ...commonRenderOpts,\n params,\n optimizeCss,\n disableOptimizedLoading,\n locale,\n supportsDynamicResponse: false,\n // During the export phase in next build, we always enable the streaming metadata since if there's\n // any dynamic access in metadata we can determine it in the build phase.\n // If it's static, then it won't affect anything.\n // If it's dynamic, then it can be handled when request hits the route.\n serveStreamingMetadata: true,\n allowEmptyStaticShell,\n runInstantValidation,\n isFallbackUpgradeable,\n experimental: {\n ...commonRenderOpts.experimental,\n isRoutePPREnabled,\n },\n renderResumeDataCache,\n }\n\n // Handle App Pages\n if (isAppDir) {\n const sharedContext: AppSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n }\n\n return exportAppPage(\n req,\n res,\n page,\n path,\n pathname,\n query,\n fallbackRouteParams,\n renderOpts as WorkerRenderOpts<AppPageModule>,\n htmlFilepath,\n debugOutput,\n isDynamicError,\n fileWriter,\n sharedContext\n )\n } else {\n const sharedContext: PagesSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n customServer: undefined,\n }\n\n const renderContext: PagesRenderContext = {\n isFallback: exportPath._pagesFallback ?? false,\n isDraftMode: false,\n developmentNotFoundSourcePage: undefined,\n }\n\n return exportPagesPage(\n req,\n res,\n path,\n page,\n query,\n params,\n htmlFilepath,\n htmlFilename,\n pagesDataDir,\n buildExport,\n isDynamic,\n sharedContext,\n renderContext,\n hasOrigQueryValues,\n renderOpts as WorkerRenderOpts<PagesModule>,\n components,\n fileWriter\n )\n }\n}\n\nexport async function exportPages(\n input: ExportPagesInput\n): Promise<ExportPagesResult> {\n // Load native bindings in the worker process so that code frame rendering\n // (which uses the native codeFrameColumns function) works during prerendering.\n await installBindings()\n installCodeFrameSupport()\n\n const {\n exportPaths,\n dir,\n distDir,\n outDir,\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n pagesDataDir,\n renderOpts,\n nextConfig,\n options,\n renderResumeDataCachesByPage = {},\n } = input\n\n installGlobalBehaviors(nextConfig)\n\n if (nextConfig.enablePrerenderSourceMaps) {\n try {\n // Same as `next dev`\n // Limiting the stack trace to a useful amount of frames is handled by ignore-listing.\n // TODO: How high can we go without severely impacting CPU/memory?\n Error.stackTraceLimit = 50\n } catch {}\n }\n\n // If the fetch cache was enabled, we need to create an incremental\n // cache instance for this page.\n const incrementalCache = await createIncrementalCache({\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n distDir,\n dir,\n // skip writing to disk in minimal mode for now, pending some\n // changes to better support it\n flushToDisk: !hasNextSupport,\n cacheHandlers: nextConfig.cacheHandlers,\n })\n\n renderOpts.incrementalCache = incrementalCache\n\n const maxConcurrency =\n nextConfig.experimental.staticGenerationMaxConcurrency ?? 8\n const results: ExportPagesResult = []\n\n const exportPageWithRetry = async (\n exportPath: ExportPathEntry,\n maxAttempts: number\n ) => {\n const { page, path } = exportPath\n const pageKey = page !== path ? `${page}: ${path}` : path\n let attempt = 0\n let result\n\n const hasDebuggerAttached =\n // Also tests for `inspect-brk`\n process.env.NODE_OPTIONS?.includes('--inspect')\n\n const renderResumeDataCache = renderResumeDataCachesByPage[pageKey]\n ? createRenderResumeDataCache(\n renderResumeDataCachesByPage[pageKey],\n renderOpts.experimental.maxPostponedStateSizeBytes\n )\n : undefined\n\n while (attempt < maxAttempts) {\n try {\n result = await Promise.race<ExportPageResult | undefined>([\n exportPage({\n exportPath,\n distDir,\n outDir,\n pagesDataDir,\n renderOpts,\n trailingSlash: nextConfig.trailingSlash,\n subFolders: nextConfig.trailingSlash && !options.buildExport,\n buildExport: options.buildExport,\n optimizeCss: nextConfig.experimental.optimizeCss,\n disableOptimizedLoading:\n nextConfig.experimental.disableOptimizedLoading,\n parentSpanId: input.parentSpanId,\n httpAgentOptions: nextConfig.httpAgentOptions,\n debugOutput: options.debugOutput,\n enableExperimentalReact: needsExperimentalReact(nextConfig),\n sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),\n buildId: input.buildId,\n deploymentId: input.deploymentId,\n clientAssetToken: input.clientAssetToken,\n renderResumeDataCache,\n }),\n hasDebuggerAttached\n ? // With a debugger attached, exporting can take infinitely if we paused script execution.\n new Promise(() => {})\n : // If exporting the page takes longer than the timeout, reject the promise.\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError())\n }, nextConfig.staticPageGenerationTimeout * 1000)\n }),\n ])\n\n // If there was an error in the export, throw it immediately. In the catch block, we might retry the export,\n // or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.\n if (result && 'error' in result) {\n throw new ExportPageError()\n }\n\n // If the export succeeds, break out of the retry loop\n break\n } catch (err) {\n // The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.\n // This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.\n if (!(err instanceof ExportPageError || err instanceof TimeoutError)) {\n throw err\n }\n\n if (err instanceof TimeoutError) {\n // If the export times out, we will restart the worker up to 3 times.\n maxAttempts = 3\n }\n\n // We've reached the maximum number of attempts\n if (attempt >= maxAttempts - 1) {\n // Log a message if we've reached the maximum number of attempts.\n // We only care to do this if maxAttempts was configured.\n if (maxAttempts > 1) {\n console.info(\n `Failed to build ${pageKey} after ${maxAttempts} attempts.`\n )\n }\n // If prerenderEarlyExit is enabled, we'll exit the build immediately.\n if (nextConfig.experimental.prerenderEarlyExit) {\n console.error(\n `Export encountered an error on ${pageKey}, exiting the build.`\n )\n process.exit(1)\n } else {\n // Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.\n }\n } else {\n // Otherwise, we have more attempts to make. Wait before retrying\n if (err instanceof TimeoutError) {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}) because it took more than ${nextConfig.staticPageGenerationTimeout} seconds. Retrying again shortly.`\n )\n } else {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`\n )\n }\n\n // Exponential backoff with random jitter to avoid thundering herd on retries\n const baseDelay = 500 // 500ms\n const maxDelay = 2000 // 2 seconds\n const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)\n const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter\n await new Promise((r) => setTimeout(r, delay + jitter))\n }\n }\n\n attempt++\n }\n\n return { result, path, page, pageKey }\n }\n\n for (let i = 0; i < exportPaths.length; i += maxConcurrency) {\n const subset = exportPaths.slice(i, i + maxConcurrency)\n\n const subsetResults = await Promise.all(\n subset.map((exportPath) =>\n exportPageWithRetry(\n exportPath,\n nextConfig.experimental.staticGenerationRetryCount ?? 1\n )\n )\n )\n\n results.push(...subsetResults)\n }\n\n return results\n}\n\nasync function exportPage(\n input: ExportPageInput\n): Promise<ExportPageResult | undefined> {\n trace('export-page', input.parentSpanId).setAttribute(\n 'path',\n input.exportPath.path\n )\n\n // Configure the http agent.\n setHttpClientAndAgentOptions({\n httpAgentOptions: input.httpAgentOptions,\n })\n\n const fileWriter = new MultiFileWriter({\n writeFile: (filePath, data) => fs.writeFile(filePath, data),\n mkdir: (dir) => fs.mkdir(dir, { recursive: true }),\n })\n\n const exportPageSpan = trace('export-page-worker', input.parentSpanId)\n\n const start = Date.now()\n\n const turborepoAccessTraceResult = new TurborepoAccessTraceResult()\n\n // Export the page.\n let result: ExportRouteResult | undefined\n try {\n result = await exportPageSpan.traceAsyncFn(() =>\n turborepoTraceAccess(\n () => exportPageImpl(input, fileWriter),\n turborepoAccessTraceResult\n )\n )\n\n // Wait for all the files to flush to disk.\n await fileWriter.wait()\n\n // If there was no result, then we can exit early.\n if (!result) return\n\n // If there was an error, then we can exit early.\n if ('error' in result) {\n return { error: result.error, duration: Date.now() - start }\n }\n } catch (err) {\n console.error(\n `Error occurred prerendering page \"${input.exportPath.path}\". Read more: https://nextjs.org/docs/messages/prerender-error`\n )\n\n // bailoutToCSRError errors should not leak to the user as they are not actionable; they're\n // a framework signal\n if (!isBailoutToCSRError(err)) {\n // A static generation bailout error is a framework signal to fail static generation but\n // and will encode a reason in the error message. If there is a message, we'll print it.\n // Otherwise there's nothing to show as we don't want to leak an error internal error stack to the user.\n // TODO: Always log the full error. ignore-listing will take care of hiding internal stacks.\n if (isStaticGenBailoutError(err)) {\n if (err.message) {\n console.error(`Error: ${err.message}`)\n }\n } else {\n console.error(err)\n }\n }\n\n return { error: true, duration: Date.now() - start }\n }\n\n // Notify the parent process that we processed a page (used by the progress activity indicator)\n process.send?.([3, { type: 'activity' }])\n\n // Otherwise we can return the result.\n return {\n ...result,\n duration: Date.now() - start,\n turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),\n }\n}\n\nprocess.on('unhandledRejection', (err: unknown) => {\n // if it's a postpone error, it'll be handled later\n // when the postponed promise is actually awaited.\n if (isPostpone(err)) {\n return\n }\n\n // we don't want to log these errors\n if (isDynamicUsageError(err)) {\n return\n }\n\n console.error(err)\n})\n\nprocess.on('rejectionHandled', () => {\n // It is ok to await a Promise late in Next.js as it allows for better\n // prefetching patterns to avoid waterfalls. We ignore logging these.\n // We should've already errored in anyway unhandledRejection.\n})\n\nconst FATAL_UNHANDLED_NEXT_API_EXIT_CODE = 78\n\nprocess.on('uncaughtException', (err) => {\n if (isDynamicUsageError(err)) {\n console.error(\n 'A Next.js API that uses exceptions to signal framework behavior was uncaught. This suggests improper usage of a Next.js API. The original error is printed below and the build will now exit.'\n )\n console.error(err)\n process.exit(FATAL_UNHANDLED_NEXT_API_EXIT_CODE)\n } else {\n console.error(err)\n }\n})\n"],"names":["exportPages","process","env","NEXT_IS_EXPORT_WORKER","globalThis","__NEXT_DATA__","nextExport","TimeoutError","Error","code","ExportPageError","exportPageImpl","input","fileWriter","req","exportPath","distDir","pagesDataDir","buildExport","subFolders","optimizeCss","disableOptimizedLoading","debugOutput","enableExperimentalReact","trailingSlash","sriEnabled","renderOpts","commonRenderOpts","outDir","commonOutDir","buildId","deploymentId","clientAssetToken","renderResumeDataCache","__NEXT_EXPERIMENTAL_REACT","path","page","_fallbackRouteParams","_isAppDir","isAppDir","_isDynamicError","isDynamicError","_isRoutePPREnabled","isRoutePPREnabled","_allowEmptyStaticShell","allowEmptyStaticShell","_runInstantValidation","runInstantValidation","_isFallbackUpgradeable","isFallbackUpgradeable","query","originalQuery","fallbackRouteParams","createOpaqueFallbackRouteParams","pathname","normalizeAppPath","isDynamic","isDynamicRoute","join","filePath","normalizePagePath","updatedPath","_ssgPath","locale","_locale","localePathResult","normalizeLocalePath","locales","detectedLocale","hasOrigQueryValues","Object","keys","length","nonLocalizedPath","params","normalizedPage","getParams","res","createRequestResponseMocks","url","statusCode","some","p","endsWith","addRequestMeta","removeTrailingSlash","domainLocales","dl","defaultLocale","includes","getHtmlFilename","sep","htmlFilename","pageExt","extname","pathExt","isBuiltinPaths","isHtmlExtPath","baseDir","dirname","htmlFilepath","fs","mkdir","recursive","components","loadComponents","isAppPath","isDev","needsManifestsForLegacyReasons","isAppRouteRoute","exportAppRoute","routeModule","incrementalCache","cacheLifeProfiles","cacheComponents","staticPageGenerationTimeout","experimental","supportsDynamicResponse","serveStreamingMetadata","sharedContext","exportAppPage","customServer","undefined","renderContext","isFallback","_pagesFallback","isDraftMode","developmentNotFoundSourcePage","exportPagesPage","installBindings","installCodeFrameSupport","exportPaths","dir","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","nextConfig","options","renderResumeDataCachesByPage","installGlobalBehaviors","enablePrerenderSourceMaps","stackTraceLimit","createIncrementalCache","flushToDisk","hasNextSupport","cacheHandlers","maxConcurrency","staticGenerationMaxConcurrency","results","exportPageWithRetry","maxAttempts","pageKey","attempt","result","hasDebuggerAttached","NODE_OPTIONS","createRenderResumeDataCache","maxPostponedStateSizeBytes","Promise","race","exportPage","parentSpanId","httpAgentOptions","needsExperimentalReact","Boolean","sri","algorithm","_","reject","setTimeout","err","console","info","prerenderEarlyExit","error","exit","baseDelay","maxDelay","delay","Math","min","pow","jitter","random","r","i","subset","slice","subsetResults","all","map","staticGenerationRetryCount","push","trace","setAttribute","setHttpClientAndAgentOptions","MultiFileWriter","writeFile","data","exportPageSpan","start","Date","now","turborepoAccessTraceResult","TurborepoAccessTraceResult","traceAsyncFn","turborepoTraceAccess","wait","duration","isBailoutToCSRError","isStaticGenBailoutError","message","send","type","serialize","on","isPostpone","isDynamicUsageError","FATAL_UNHANDLED_NEXT_API_EXIT_CODE"],"mappings":";;;;+BA4VsBA;;;eAAAA;;;QAhVf;iCACyB;kCACQ;sBAII;iEAC7B;gCACgB;2BACA;mCACG;qCACE;uBACd;mCACuB;6BACd;0BACE;qCACG;6BAEO;iCACX;wBACD;0BACA;yBACD;uBACE;2BACN;wCACa;4BACZ;qCACS;8BACA;sCAI7B;gCAKA;wCACg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sEAAsE;AACtE,qEAAqE;AACrE,6DAA6D;AAC/D;AAEA,MAAMG,qCAAqC;AAE3CzN,QAAQsN,EAAE,CAAC,qBAAqB,CAAC7C;IAC/B,IAAI+C,IAAAA,wCAAmB,EAAC/C,MAAM;QAC5BC,QAAQG,KAAK,CACX;QAEFH,QAAQG,KAAK,CAACJ;QACdzK,QAAQ8K,IAAI,CAAC2C;IACf,OAAO;QACL/C,QAAQG,KAAK,CAACJ;IAChB;AACF","ignoreList":[0]}
{"version":3,"sources":["../../src/export/worker.ts"],"sourcesContent":["import type {\n ExportPagesInput,\n ExportPageInput,\n ExportPageResult,\n ExportRouteResult,\n WorkerRenderOpts,\n ExportPagesResult,\n ExportPathEntry,\n} from './types'\nimport type { AppPageModule } from '../server/route-modules/app-page/module'\nimport type { PagesModule } from '../server/route-modules/pages/module.compiled'\n\nimport '../server/node-environment'\nimport { installBindings } from '../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../server/lib/install-code-frame'\n\nprocess.env.NEXT_IS_EXPORT_WORKER = 'true'\n\nimport { extname, join, dirname, sep } from 'path'\nimport fs from 'fs/promises'\nimport { loadComponents } from '../server/load-components'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { trace } from '../trace'\nimport { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'\nimport { addRequestMeta } from '../server/request-meta'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\n\nimport { createRequestResponseMocks } from '../server/lib/mock-request'\nimport { isAppRouteRoute } from '../lib/is-app-route-route'\nimport { hasNextSupport } from '../server/ci-info'\nimport { exportAppRoute } from './routes/app-route'\nimport { exportAppPage } from './routes/app-page'\nimport { exportPagesPage } from './routes/pages'\nimport { getParams } from './helpers/get-params'\nimport { createIncrementalCache } from './helpers/create-incremental-cache'\nimport { isDynamicUsageError } from './helpers/is-dynamic-usage-error'\nimport { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'\nimport {\n turborepoTraceAccess,\n TurborepoAccessTraceResult,\n} from '../build/turborepo-access-trace'\nimport type { Params } from '../server/request/params'\nimport {\n createOpaqueFallbackRouteParams,\n type OpaqueFallbackRouteParams,\n} from '../server/request/fallback-params'\nimport { needsExperimentalReact } from '../lib/needs-experimental-react'\nimport type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'\nimport { isStaticGenBailoutError } from '../client/components/static-generation-bailout'\nimport type { PagesRenderContext, PagesSharedContext } from '../server/render'\nimport type { AppSharedContext } from '../server/app-render/app-render'\nimport { MultiFileWriter } from '../lib/multi-file-writer'\nimport { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'\nimport { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'\n;(globalThis as any).__NEXT_DATA__ = {\n nextExport: true,\n}\n\nclass TimeoutError extends Error {\n code = 'NEXT_EXPORT_TIMEOUT_ERROR'\n}\n\nclass ExportPageError extends Error {\n code = 'NEXT_EXPORT_PAGE_ERROR'\n}\n\nasync function exportPageImpl(\n input: ExportPageInput,\n fileWriter: MultiFileWriter\n): Promise<ExportRouteResult | undefined> {\n const {\n exportPath,\n distDir,\n pagesDataDir,\n buildExport = false,\n subFolders = false,\n optimizeCss,\n disableOptimizedLoading,\n debugOutput = false,\n enableExperimentalReact,\n trailingSlash,\n sriEnabled,\n renderOpts: commonRenderOpts,\n outDir: commonOutDir,\n buildId,\n deploymentId,\n clientAssetToken,\n renderResumeDataCache,\n } = input\n\n if (enableExperimentalReact) {\n process.env.__NEXT_EXPERIMENTAL_REACT = 'true'\n }\n\n const {\n path,\n page,\n\n // The parameters that are currently unknown.\n _fallbackRouteParams = [],\n\n // Check if this is an `app/` page.\n _isAppDir: isAppDir = false,\n\n // Check if this should error when dynamic usage is detected.\n _isDynamicError: isDynamicError = false,\n\n // If this page supports partial prerendering, then we need to pass that to\n // the renderOpts.\n _isRoutePPREnabled: isRoutePPREnabled,\n\n // Configure the rendering of the page to allow that an empty static shell\n // is generated while rendering using PPR and Cache Components.\n _allowEmptyStaticShell: allowEmptyStaticShell = false,\n\n // When true, attempt to run build-time instant validation for this export path.\n _runInstantValidation: runInstantValidation = false,\n\n // When true, a fallback shell for this path could later be upgraded to a\n // concrete version (it has a `generateStaticParams` candidate param).\n _isFallbackUpgradeable: isFallbackUpgradeable = false,\n\n // Pull the original query out.\n query: originalQuery = {},\n } = exportPath\n\n const fallbackRouteParams: OpaqueFallbackRouteParams | null =\n createOpaqueFallbackRouteParams(_fallbackRouteParams)\n\n let query = { ...originalQuery }\n const pathname = normalizeAppPath(page)\n const isDynamic = isDynamicRoute(page)\n const outDir = isAppDir ? join(distDir, 'server/app') : commonOutDir\n\n const filePath = normalizePagePath(path)\n\n let updatedPath = exportPath._ssgPath || path\n let locale = exportPath._locale || commonRenderOpts.locale\n\n if (commonRenderOpts.locale) {\n const localePathResult = normalizeLocalePath(path, commonRenderOpts.locales)\n\n if (localePathResult.detectedLocale) {\n updatedPath = localePathResult.pathname\n locale = localePathResult.detectedLocale\n }\n }\n\n // We need to show a warning if they try to provide query values\n // for an auto-exported page since they won't be available\n const hasOrigQueryValues = Object.keys(originalQuery).length > 0\n\n // Check if the page is a specified dynamic route\n const { pathname: nonLocalizedPath } = normalizeLocalePath(\n path,\n commonRenderOpts.locales\n )\n\n let params: Params | undefined\n\n if (isDynamic && page !== nonLocalizedPath) {\n const normalizedPage = isAppDir ? normalizeAppPath(page) : page\n\n params = getParams(normalizedPage, updatedPath)\n }\n\n const { req, res } = createRequestResponseMocks({ url: updatedPath })\n\n // If this is a status code page, then set the response code.\n for (const statusCode of [404, 500]) {\n if (\n [\n `/${statusCode}`,\n `/${statusCode}.html`,\n `/${statusCode}/index.html`,\n ].some((p) => p === updatedPath || `/${locale}${p}` === updatedPath)\n ) {\n res.statusCode = statusCode\n }\n }\n\n // Ensure that the URL has a trailing slash if it's configured.\n if (trailingSlash && !req.url?.endsWith('/')) {\n req.url += '/'\n }\n\n // Set the resolved pathname without trailing slash as request metadata.\n addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath))\n\n if (\n locale &&\n buildExport &&\n commonRenderOpts.domainLocales &&\n commonRenderOpts.domainLocales.some(\n (dl) => dl.defaultLocale === locale || dl.locales?.includes(locale || '')\n )\n ) {\n addRequestMeta(req, 'isLocaleDomain', true)\n }\n\n const getHtmlFilename = (p: string) =>\n subFolders ? `${p}${sep}index.html` : `${p}.html`\n\n let htmlFilename = getHtmlFilename(filePath)\n\n // dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an\n // extension of `.slug]`\n const pageExt = isDynamic || isAppDir ? '' : extname(page)\n const pathExt = isDynamic || isAppDir ? '' : extname(path)\n\n // force output 404.html for backwards compat\n if (path === '/404.html') {\n htmlFilename = path\n }\n // Make sure page isn't a folder with a dot in the name e.g. `v1.2`\n else if (pageExt !== pathExt && pathExt !== '') {\n const isBuiltinPaths = ['/500', '/404'].some(\n (p) => p === path || p === path + '.html'\n )\n // If the ssg path has .html extension, and it's not builtin paths, use it directly\n // Otherwise, use that as the filename instead\n const isHtmlExtPath = !isBuiltinPaths && path.endsWith('.html')\n htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path\n } else if (path === '/') {\n // If the path is the root, just use index.html\n htmlFilename = 'index.html'\n }\n\n const baseDir = join(outDir, dirname(htmlFilename))\n let htmlFilepath = join(outDir, htmlFilename)\n\n await fs.mkdir(baseDir, { recursive: true })\n\n const components = await loadComponents({\n distDir,\n page,\n isAppPath: isAppDir,\n isDev: false,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n // Handle App Routes.\n if (isAppDir && isAppRouteRoute(page)) {\n return exportAppRoute(\n req,\n res,\n params,\n page,\n components.routeModule as AppRouteRouteModule,\n commonRenderOpts.incrementalCache,\n commonRenderOpts.cacheLifeProfiles,\n htmlFilepath,\n fileWriter,\n commonRenderOpts.cacheComponents,\n commonRenderOpts.staticPageGenerationTimeout,\n commonRenderOpts.experimental,\n buildId,\n deploymentId\n )\n }\n\n const renderOpts: WorkerRenderOpts = {\n ...components,\n ...commonRenderOpts,\n params,\n optimizeCss,\n disableOptimizedLoading,\n locale,\n supportsDynamicResponse: false,\n // During the export phase in next build, we always enable the streaming metadata since if there's\n // any dynamic access in metadata we can determine it in the build phase.\n // If it's static, then it won't affect anything.\n // If it's dynamic, then it can be handled when request hits the route.\n serveStreamingMetadata: true,\n allowEmptyStaticShell,\n runInstantValidation,\n isFallbackUpgradeable,\n experimental: {\n ...commonRenderOpts.experimental,\n isRoutePPREnabled,\n },\n renderResumeDataCache,\n }\n\n // Handle App Pages\n if (isAppDir) {\n const sharedContext: AppSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n }\n\n return exportAppPage(\n req,\n res,\n page,\n path,\n pathname,\n query,\n fallbackRouteParams,\n renderOpts as WorkerRenderOpts<AppPageModule>,\n htmlFilepath,\n debugOutput,\n isDynamicError,\n fileWriter,\n sharedContext\n )\n } else {\n const sharedContext: PagesSharedContext = {\n buildId,\n deploymentId,\n clientAssetToken,\n customServer: undefined,\n }\n\n const renderContext: PagesRenderContext = {\n isFallback: exportPath._pagesFallback ?? false,\n isDraftMode: false,\n developmentNotFoundSourcePage: undefined,\n }\n\n return exportPagesPage(\n req,\n res,\n path,\n page,\n query,\n params,\n htmlFilepath,\n htmlFilename,\n pagesDataDir,\n buildExport,\n isDynamic,\n sharedContext,\n renderContext,\n hasOrigQueryValues,\n renderOpts as WorkerRenderOpts<PagesModule>,\n components,\n fileWriter\n )\n }\n}\n\nexport async function exportPages(\n input: ExportPagesInput\n): Promise<ExportPagesResult> {\n // Load native bindings in the worker process so that code frame rendering\n // (which uses the native codeFrameColumns function) works during prerendering.\n await installBindings()\n installCodeFrameSupport()\n\n const {\n exportPaths,\n dir,\n distDir,\n outDir,\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n pagesDataDir,\n renderOpts,\n nextConfig,\n options,\n renderResumeDataCachesByPage = {},\n } = input\n\n installGlobalBehaviors(nextConfig)\n\n if (nextConfig.enablePrerenderSourceMaps) {\n try {\n // Same as `next dev`\n // Limiting the stack trace to a useful amount of frames is handled by ignore-listing.\n // TODO: How high can we go without severely impacting CPU/memory?\n Error.stackTraceLimit = 50\n } catch {}\n }\n\n // If the fetch cache was enabled, we need to create an incremental\n // cache instance for this page.\n const incrementalCache = await createIncrementalCache({\n cacheHandler,\n cacheMaxMemorySize,\n fetchCacheKeyPrefix,\n distDir,\n dir,\n // skip writing to disk in minimal mode for now, pending some\n // changes to better support it\n flushToDisk: !hasNextSupport,\n cacheHandlers: nextConfig.cacheHandlers,\n })\n\n renderOpts.incrementalCache = incrementalCache\n\n const maxConcurrency =\n nextConfig.experimental.staticGenerationMaxConcurrency ?? 8\n const results: ExportPagesResult = []\n\n const exportPageWithRetry = async (\n exportPath: ExportPathEntry,\n maxAttempts: number\n ) => {\n const { page, path } = exportPath\n const pageKey = page !== path ? `${page}: ${path}` : path\n let attempt = 0\n let result\n\n const hasDebuggerAttached =\n // Also tests for `inspect-brk`\n process.env.NODE_OPTIONS?.includes('--inspect')\n\n const renderResumeDataCache = renderResumeDataCachesByPage[pageKey]\n ? createRenderResumeDataCache(\n renderResumeDataCachesByPage[pageKey],\n renderOpts.experimental.maxPostponedStateSizeBytes\n )\n : undefined\n\n while (attempt < maxAttempts) {\n try {\n result = await Promise.race<ExportPageResult | undefined>([\n exportPage({\n exportPath,\n distDir,\n outDir,\n pagesDataDir,\n renderOpts,\n trailingSlash: nextConfig.trailingSlash,\n subFolders: nextConfig.trailingSlash && !options.buildExport,\n buildExport: options.buildExport,\n optimizeCss: nextConfig.experimental.optimizeCss,\n disableOptimizedLoading:\n nextConfig.experimental.disableOptimizedLoading,\n parentSpanId: input.parentSpanId,\n httpAgentOptions: nextConfig.httpAgentOptions,\n debugOutput: options.debugOutput,\n enableExperimentalReact: needsExperimentalReact(nextConfig),\n sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),\n buildId: input.buildId,\n deploymentId: input.deploymentId,\n clientAssetToken: input.clientAssetToken,\n renderResumeDataCache,\n }),\n hasDebuggerAttached\n ? // With a debugger attached, exporting can take infinitely if we paused script execution.\n new Promise(() => {})\n : // If exporting the page takes longer than the timeout, reject the promise.\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError())\n }, nextConfig.staticPageGenerationTimeout * 1000)\n }),\n ])\n\n // If there was an error in the export, throw it immediately. In the catch block, we might retry the export,\n // or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.\n if (result && 'error' in result) {\n throw new ExportPageError()\n }\n\n // If the export succeeds, break out of the retry loop\n break\n } catch (err) {\n // The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.\n // This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.\n if (!(err instanceof ExportPageError || err instanceof TimeoutError)) {\n throw err\n }\n\n if (err instanceof TimeoutError) {\n // If the export times out, we will restart the worker up to 3 times.\n maxAttempts = 3\n }\n\n // We've reached the maximum number of attempts\n if (attempt >= maxAttempts - 1) {\n // Log a message if we've reached the maximum number of attempts.\n // We only care to do this if maxAttempts was configured.\n if (maxAttempts > 1) {\n console.info(\n `Failed to build ${pageKey} after ${maxAttempts} attempts.`\n )\n }\n // If prerenderEarlyExit is enabled, we'll exit the build immediately.\n if (nextConfig.experimental.prerenderEarlyExit) {\n console.error(\n `Export encountered an error on ${pageKey}, exiting the build.`\n )\n process.exit(1)\n } else {\n // Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.\n }\n } else {\n // Otherwise, we have more attempts to make. Wait before retrying\n if (err instanceof TimeoutError) {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}) because it took more than ${nextConfig.staticPageGenerationTimeout} seconds. Retrying again shortly.`\n )\n } else {\n console.info(\n `Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`\n )\n }\n\n // Exponential backoff with random jitter to avoid thundering herd on retries\n const baseDelay = 500 // 500ms\n const maxDelay = 2000 // 2 seconds\n const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)\n const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter\n await new Promise((r) => setTimeout(r, delay + jitter))\n }\n }\n\n attempt++\n }\n\n return { result, path, page, pageKey }\n }\n\n for (let i = 0; i < exportPaths.length; i += maxConcurrency) {\n const subset = exportPaths.slice(i, i + maxConcurrency)\n\n const subsetResults = await Promise.all(\n subset.map((exportPath) =>\n exportPageWithRetry(\n exportPath,\n nextConfig.experimental.staticGenerationRetryCount ?? 1\n )\n )\n )\n\n results.push(...subsetResults)\n }\n\n return results\n}\n\nasync function exportPage(\n input: ExportPageInput\n): Promise<ExportPageResult | undefined> {\n trace('export-page', input.parentSpanId).setAttribute(\n 'path',\n input.exportPath.path\n )\n\n // Configure the http agent.\n setHttpClientAndAgentOptions({\n httpAgentOptions: input.httpAgentOptions,\n })\n\n const fileWriter = new MultiFileWriter({\n writeFile: (filePath, data) => fs.writeFile(filePath, data),\n mkdir: (dir) => fs.mkdir(dir, { recursive: true }),\n })\n\n const exportPageSpan = trace('export-page-worker', input.parentSpanId)\n\n const start = Date.now()\n\n const turborepoAccessTraceResult = new TurborepoAccessTraceResult()\n\n // Export the page.\n let result: ExportRouteResult | undefined\n try {\n result = await exportPageSpan.traceAsyncFn(() =>\n turborepoTraceAccess(\n () => exportPageImpl(input, fileWriter),\n turborepoAccessTraceResult\n )\n )\n\n // Wait for all the files to flush to disk.\n await fileWriter.wait()\n\n // If there was no result, then we can exit early.\n if (!result) return\n\n // If there was an error, then we can exit early.\n if ('error' in result) {\n return { error: result.error, duration: Date.now() - start }\n }\n } catch (err) {\n console.error(\n `Error occurred prerendering page \"${input.exportPath.path}\". Read more: https://nextjs.org/docs/messages/prerender-error`\n )\n\n // bailoutToCSRError errors should not leak to the user as they are not actionable; they're\n // a framework signal\n if (!isBailoutToCSRError(err)) {\n // A static generation bailout error is a framework signal to fail static generation but\n // and will encode a reason in the error message. If there is a message, we'll print it.\n // Otherwise there's nothing to show as we don't want to leak an error internal error stack to the user.\n // TODO: Always log the full error. ignore-listing will take care of hiding internal stacks.\n if (isStaticGenBailoutError(err)) {\n if (err.message) {\n console.error(`Error: ${err.message}`)\n }\n } else {\n console.error(err)\n }\n }\n\n return { error: true, duration: Date.now() - start }\n }\n\n // Notify the parent process that we processed a page (used by the progress activity indicator)\n process.send?.([3, { type: 'activity' }])\n\n // Otherwise we can return the result.\n return {\n ...result,\n duration: Date.now() - start,\n turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),\n }\n}\n\nprocess.on('unhandledRejection', (err: unknown) => {\n // we don't want to log these errors\n if (isDynamicUsageError(err)) {\n return\n }\n\n console.error(err)\n})\n\nprocess.on('rejectionHandled', () => {\n // It is ok to await a Promise late in Next.js as it allows for better\n // prefetching patterns to avoid waterfalls. We ignore logging these.\n // We should've already errored in anyway unhandledRejection.\n})\n\nconst FATAL_UNHANDLED_NEXT_API_EXIT_CODE = 78\n\nprocess.on('uncaughtException', (err) => {\n if (isDynamicUsageError(err)) {\n console.error(\n 'A Next.js API that uses exceptions to signal framework behavior was uncaught. This suggests improper usage of a Next.js API. The original error is printed below and the build will now exit.'\n )\n console.error(err)\n process.exit(FATAL_UNHANDLED_NEXT_API_EXIT_CODE)\n } else {\n console.error(err)\n }\n})\n"],"names":["exportPages","process","env","NEXT_IS_EXPORT_WORKER","globalThis","__NEXT_DATA__","nextExport","TimeoutError","Error","code","ExportPageError","exportPageImpl","input","fileWriter","req","exportPath","distDir","pagesDataDir","buildExport","subFolders","optimizeCss","disableOptimizedLoading","debugOutput","enableExperimentalReact","trailingSlash","sriEnabled","renderOpts","commonRenderOpts","outDir","commonOutDir","buildId","deploymentId","clientAssetToken","renderResumeDataCache","__NEXT_EXPERIMENTAL_REACT","path","page","_fallbackRouteParams","_isAppDir","isAppDir","_isDynamicError","isDynamicError","_isRoutePPREnabled","isRoutePPREnabled","_allowEmptyStaticShell","allowEmptyStaticShell","_runInstantValidation","runInstantValidation","_isFallbackUpgradeable","isFallbackUpgradeable","query","originalQuery","fallbackRouteParams","createOpaqueFallbackRouteParams","pathname","normalizeAppPath","isDynamic","isDynamicRoute","join","filePath","normalizePagePath","updatedPath","_ssgPath","locale","_locale","localePathResult","normalizeLocalePath","locales","detectedLocale","hasOrigQueryValues","Object","keys","length","nonLocalizedPath","params","normalizedPage","getParams","res","createRequestResponseMocks","url","statusCode","some","p","endsWith","addRequestMeta","removeTrailingSlash","domainLocales","dl","defaultLocale","includes","getHtmlFilename","sep","htmlFilename","pageExt","extname","pathExt","isBuiltinPaths","isHtmlExtPath","baseDir","dirname","htmlFilepath","fs","mkdir","recursive","components","loadComponents","isAppPath","isDev","needsManifestsForLegacyReasons","isAppRouteRoute","exportAppRoute","routeModule","incrementalCache","cacheLifeProfiles","cacheComponents","staticPageGenerationTimeout","experimental","supportsDynamicResponse","serveStreamingMetadata","sharedContext","exportAppPage","customServer","undefined","renderContext","isFallback","_pagesFallback","isDraftMode","developmentNotFoundSourcePage","exportPagesPage","installBindings","installCodeFrameSupport","exportPaths","dir","cacheHandler","cacheMaxMemorySize","fetchCacheKeyPrefix","nextConfig","options","renderResumeDataCachesByPage","installGlobalBehaviors","enablePrerenderSourceMaps","stackTraceLimit","createIncrementalCache","flushToDisk","hasNextSupport","cacheHandlers","maxConcurrency","staticGenerationMaxConcurrency","results","exportPageWithRetry","maxAttempts","pageKey","attempt","result","hasDebuggerAttached","NODE_OPTIONS","createRenderResumeDataCache","maxPostponedStateSizeBytes","Promise","race","exportPage","parentSpanId","httpAgentOptions","needsExperimentalReact","Boolean","sri","algorithm","_","reject","setTimeout","err","console","info","prerenderEarlyExit","error","exit","baseDelay","maxDelay","delay","Math","min","pow","jitter","random","r","i","subset","slice","subsetResults","all","map","staticGenerationRetryCount","push","trace","setAttribute","setHttpClientAndAgentOptions","MultiFileWriter","writeFile","data","exportPageSpan","start","Date","now","turborepoAccessTraceResult","TurborepoAccessTraceResult","traceAsyncFn","turborepoTraceAccess","wait","duration","isBailoutToCSRError","isStaticGenBailoutError","message","send","type","serialize","on","isDynamicUsageError","FATAL_UNHANDLED_NEXT_API_EXIT_CODE"],"mappings":";;;;+BA2VsBA;;;eAAAA;;;QA/Uf;iCACyB;kCACQ;sBAII;iEAC7B;gCACgB;2BACA;mCACG;qCACE;uBACd;mCACuB;6BACd;0BACE;qCACG;6BAEO;iCACX;wBACD;0BACA;yBACD;uBACE;2BACN;wCACa;qCACH;8BACA;sCAI7B;gCAKA;wCACgC;yCAEC;iCAGR;iCACY;iCACL;;;;;;AAxCvCC,QAAQC,GAAG,CAACC,qBAAqB,GAAG;AAyClCC,WAAmBC,aAAa,GAAG;IACnCC,YAAY;AACd;AAEA,MAAMC,qBAAqBC;;QAA3B,qBACEC,OAAO;;AACT;AAEA,MAAMC,wBAAwBF;;QAA9B,qBACEC,OAAO;;AACT;AAEA,eAAeE,eACbC,KAAsB,EACtBC,UAA2B;QAkHLC;IAhHtB,MAAM,EACJC,UAAU,EACVC,OAAO,EACPC,YAAY,EACZC,cAAc,KAAK,EACnBC,aAAa,KAAK,EAClBC,WAAW,EACXC,uBAAuB,EACvBC,cAAc,KAAK,EACnBC,uBAAuB,EACvBC,aAAa,EACbC,UAAU,EACVC,YAAYC,gBAAgB,EAC5BC,QAAQC,YAAY,EACpBC,OAAO,EACPC,YAAY,EACZC,gBAAgB,EAChBC,qBAAqB,EACtB,GAAGrB;IAEJ,IAAIW,yBAAyB;QAC3BtB,QAAQC,GAAG,CAACgC,yBAAyB,GAAG;IAC1C;IAEA,MAAM,EACJC,IAAI,EACJC,IAAI,EAEJ,6CAA6C;IAC7CC,uBAAuB,EAAE,EAEzB,mCAAmC;IACnCC,WAAWC,WAAW,KAAK,EAE3B,6DAA6D;IAC7DC,iBAAiBC,iBAAiB,KAAK,EAEvC,2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MAAM;QAAW;KAAE;IAExC,sCAAsC;IACtC,OAAO;QACL,GAAG5D,MAAM;QACTuD,UAAUP,KAAKC,GAAG,KAAKF;QACvBG,4BAA4BA,2BAA2BW,SAAS;IAClE;AACF;AAEArN,QAAQsN,EAAE,CAAC,sBAAsB,CAAC7C;IAChC,oCAAoC;IACpC,IAAI8C,IAAAA,wCAAmB,EAAC9C,MAAM;QAC5B;IACF;IAEAC,QAAQG,KAAK,CAACJ;AAChB;AAEAzK,QAAQsN,EAAE,CAAC,oBAAoB;AAC7B,sEAAsE;AACtE,qEAAqE;AACrE,6DAA6D;AAC/D;AAEA,MAAME,qCAAqC;AAE3CxN,QAAQsN,EAAE,CAAC,qBAAqB,CAAC7C;IAC/B,IAAI8C,IAAAA,wCAAmB,EAAC9C,MAAM;QAC5BC,QAAQG,KAAK,CACX;QAEFH,QAAQG,KAAK,CAACJ;QACdzK,QAAQ8K,IAAI,CAAC0C;IACf,OAAO;QACL9C,QAAQG,KAAK,CAACJ;IAChB;AACF","ignoreList":[0]}

@@ -75,3 +75,3 @@ "use strict";

const data = await res.json();
const versionData = data.versions["16.3.1-canary.11"];
const versionData = data.versions["16.3.1-canary.12"];
return {

@@ -104,3 +104,3 @@ os: versionData.os,

lockfileParsed.dependencies[pkg] = {
version: "16.3.1-canary.11",
version: "16.3.1-canary.12",
resolved: pkgData.tarball,

@@ -113,3 +113,3 @@ integrity: pkgData.integrity,

lockfileParsed.packages[pkg] = {
version: "16.3.1-canary.11",
version: "16.3.1-canary.12",
resolved: pkgData.tarball,

@@ -116,0 +116,0 @@ integrity: pkgData.integrity,

@@ -34,4 +34,2 @@ import type { RenderOpts, PreloadCallbacks } from './types';

type AppRenderCapabilities = {
/** Whether this render may postpone dynamic subtrees. */
canPostpone: boolean;
/**

@@ -38,0 +36,0 @@ * Whether the response may contain postponed holes. This is conservatively

@@ -73,4 +73,4 @@ "use strict";

async function createComponentTreeInternal({ loaderTree: tree, parentParams, parentOptionalCatchAllParamName, rootLayoutIncluded, injectedCSS, injectedJS, injectedFontPreloadTags, ctx, missingSlots, preloadCallbacks, authInterrupts, MetadataOutlet, isPrerendering, hintTree }, isRoot, workUnitStore) {
const { renderOpts: { nextConfigOutput, experimental, cacheComponents }, workStore, componentMod: { createElement, Fragment, SegmentViewNode, HTTPAccessFallbackBoundary, LayoutRouter, RenderFromTemplateContext, ClientPageRoot, ClientSegmentRoot, createServerSearchParamsForServerPage, createPrerenderSearchParamsForClientPage, createServerParamsForServerSegment, createPrerenderParamsForClientSegment, serverHooks: { DynamicServerError }, Postpone }, pagePath, getDynamicParamFromSegment, isPrefetch, renderCapabilities, query } = ctx;
const { canPostpone, isPossiblyPartialResponse } = renderCapabilities;
const { renderOpts: { nextConfigOutput, experimental, cacheComponents }, workStore, componentMod: { createElement, Fragment, SegmentViewNode, HTTPAccessFallbackBoundary, LayoutRouter, RenderFromTemplateContext, ClientPageRoot, ClientSegmentRoot, createServerSearchParamsForServerPage, createPrerenderSearchParamsForClientPage, createServerParamsForServerSegment, createPrerenderParamsForClientSegment, serverHooks: { DynamicServerError } }, pagePath, getDynamicParamFromSegment, isPrefetch, renderCapabilities, query } = ctx;
const { isPossiblyPartialResponse } = renderCapabilities;
const { page, conventionPath, segment, modules, parallelRoutes } = (0, _parseloadertree.parseLoaderTree)(tree);

@@ -171,6 +171,3 @@ const prefetchInliningEnabled = Boolean(experimental.prefetchInlining);

workStore.forceDynamic = true;
// TODO: (PPR) remove this bailout once PPR is the default
if (isPrerendering && !canPostpone) {
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
if (isPrerendering) {
const err = Object.defineProperty(new DynamicServerError(`Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`), "__NEXT_ERROR_CODE", {

@@ -202,3 +199,2 @@ value: "E585",

case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.revalidate > defaultRevalidate) {

@@ -221,5 +217,3 @@ workUnitStore.revalidate = defaultRevalidate;

}
if (!workStore.forceStatic && isPrerendering && defaultRevalidate === 0 && // If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
!canPostpone) {
if (!workStore.forceStatic && isPrerendering && defaultRevalidate === 0) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}`;

@@ -243,3 +237,2 @@ workStore.dynamicUsageDescription = dynamicUsageDescription;

case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.stale > pageStaleTime) {

@@ -506,23 +499,2 @@ workUnitStore.stale = pageStaleTime;

const Component = MaybeComponent;
// If force-dynamic is used and the current render supports postponing, we
// replace it with a node that will postpone the render. This ensures that the
// postpone is invoked during the react render phase and not during the next
// render phase.
// @TODO this does not actually do what it seems like it would or should do. The idea is that
// if we are rendering in a force-dynamic mode and we can postpone we should only make the segments
// that ask for force-dynamic to be dynamic, allowing other segments to still prerender. However
// because this comes after the children traversal and the static generation store is mutated every segment
// along the parent path of a force-dynamic segment will hit this condition effectively making the entire
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if (canPostpone && workStore.forceDynamic) {
return createTransportNode(ctx, transportSegment, prefetchHints, createElement(Fragment, {
key: cacheNodeKey
}, createElement(Postpone, {
reason: 'dynamic = "force-dynamic" was used',
route: workStore.route
}), layerAssets), parallelRouteNodes, loadingData, true, // force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
_varyparams.emptyVaryParamsAccumulator);
}
const isClientComponent = (0, _clientandserverreferences.isClientReference)(layoutOrPageMod);

@@ -529,0 +501,0 @@ const varyParamsAccumulator = isClientComponent && cacheComponents ? // from the server, so they have an empty vary params set.

@@ -70,12 +70,2 @@ /**

export declare function abortOnSynchronousPlatformIOAccess(route: string, expression: string, errorWithStack: Error, prerenderStore: PrerenderStoreModern): void;
/**
* This component will call `React.postpone` that throws the postponed error.
*/
type PostponeProps = {
reason: string;
route: string;
};
export declare function Postpone({ reason, route }: PostponeProps): never;
export declare function postponeWithTracking(route: string, expression: string, dynamicTracking: null | DynamicTrackingState): never;
export declare function isDynamicPostpone(err: unknown): boolean;
type DigestError = Error & {

@@ -88,6 +78,2 @@ digest: string;

export declare function formatDynamicAPIAccesses(dynamicAccesses: Array<DynamicAccess>): string[];
/**
* This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's
* abort semantics slightly.
*/
export declare function createRenderInBrowserAbortSignal(): AbortSignal;

@@ -102,3 +88,3 @@ /**

export declare function annotateDynamicAccess(expression: string, prerenderStore: PrerenderStoreModern | ValidationStoreClient): void;
export declare function useDynamicRouteParams(expression: string): undefined;
export declare function useDynamicRouteParams(expression: string): void;
export declare function useDynamicSearchParams(expression: string): void;

@@ -105,0 +91,0 @@ export declare function trackAllowedDynamicAccess(dynamicReason: unknown, workStore: WorkStore, componentStack: string, dynamicValidation: DynamicValidationState, clientDynamic: DynamicTrackingState): void;

@@ -27,3 +27,2 @@ /**

DynamicHoleKind: null,
Postpone: null,
PreludeState: null,

@@ -44,7 +43,5 @@ abortAndThrowOnSynchronousRequestDataAccess: null,

getStaticShellDisallowedDynamicReasons: null,
isDynamicPostpone: null,
isPrerenderInterruptedError: null,
logDisallowedDynamicError: null,
markCurrentScopeAsDynamic: null,
postponeWithTracking: null,
throwIfDisallowedDynamic: null,

@@ -72,5 +69,2 @@ throwIfSyncIOUsed: null,

},
Postpone: function() {
return Postpone;
},
PreludeState: function() {

@@ -121,5 +115,2 @@ return PreludeState;

},
isDynamicPostpone: function() {
return isDynamicPostpone;
},
isPrerenderInterruptedError: function() {

@@ -134,5 +125,2 @@ return isPrerenderInterruptedError;

},
postponeWithTracking: function() {
return postponeWithTracking;
},
throwIfDisallowedDynamic: function() {

@@ -191,3 +179,2 @@ return throwIfDisallowedDynamic;

}
const hasPostpone = typeof _react.default.unstable_postpone === 'function';
function createDynamicTrackingState(isDebugDynamicAccesses) {

@@ -232,3 +219,2 @@ return {

case 'prerender-legacy':
case 'prerender-ppr':
case 'request':

@@ -254,4 +240,2 @@ case 'generate-static-params':

switch(workUnitStore.type){
case 'prerender-ppr':
return postponeWithTracking(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -308,3 +292,2 @@ workUnitStore.revalidate = 0;

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':

@@ -378,38 +361,2 @@ case 'validation-client':

}
function Postpone({ reason, route }) {
const prerenderStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
const dynamicTracking = prerenderStore && prerenderStore.type === 'prerender-ppr' ? prerenderStore.dynamicTracking : null;
postponeWithTracking(route, reason, dynamicTracking);
}
function postponeWithTracking(route, expression, dynamicTracking) {
assertPostpone();
if (dynamicTracking) {
dynamicTracking.dynamicAccesses.push({
// When we aren't debugging, we don't need to create another error for the
// stack trace.
stack: dynamicTracking.isDebugDynamicAccesses ? new Error().stack : undefined,
expression
});
}
_react.default.unstable_postpone(createPostponeReason(route, expression));
}
function createPostponeReason(route, expression) {
return `Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` + `React throws this special object to indicate where. It should not be caught by ` + `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;
}
function isDynamicPostpone(err) {
if (typeof err === 'object' && err !== null && typeof err.message === 'string') {
return isDynamicPostponeReason(err.message);
}
return false;
}
function isDynamicPostponeReason(reason) {
return reason.includes('needs to bail out of prerendering at this point because it used') && reason.includes('Learn more: https://nextjs.org/docs/messages/ppr-caught-error');
}
if (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {
throw Object.defineProperty(new Error('Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'), "__NEXT_ERROR_CODE", {
value: "E296",
enumerable: false,
configurable: true
});
}
const NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED';

@@ -461,11 +408,2 @@ function createPrerenderInterruptedError(message) {

}
function assertPostpone() {
if (!hasPostpone) {
throw Object.defineProperty(new Error(`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`), "__NEXT_ERROR_CODE", {
value: "E224",
enumerable: false,
configurable: true
});
}
}
function createRenderInBrowserAbortSignal() {

@@ -513,3 +451,2 @@ const controller = new AbortController();

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -558,10 +495,2 @@ case 'request':

});
case 'prerender-ppr':
{
const fallbackParams = workUnitStore.fallbackRouteParams;
if (fallbackParams && fallbackParams.size > 0) {
return postponeWithTracking(workStore.route, expression, workUnitStore.dynamicTracking);
}
break;
}
case 'validation-client':

@@ -620,3 +549,2 @@ {

case 'prerender-legacy':
case 'prerender-ppr':
{

@@ -623,0 +551,0 @@ if (workStore.forceStatic) {

@@ -228,3 +228,2 @@ /* eslint-disable import/no-extraneous-dependencies */ "use strict";

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -231,0 +230,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/app-render/encryption.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport 'server-only'\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport { renderToReadableStream } from 'react-server-dom-webpack/server'\n/* eslint-disable import/no-extraneous-dependencies */\nimport { createFromReadableStream } from 'react-server-dom-webpack/client'\n\nimport { streamToString } from '../stream-utils/node-web-streams-helper'\nimport {\n arrayBufferToString,\n decrypt,\n encrypt,\n getActionEncryptionKey,\n stringToUint8Array,\n} from './encryption-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from './manifests-singleton'\nimport {\n getCacheSignal,\n getResumeDataCache,\n workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from './dynamic-rendering'\nimport React from 'react'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Decrypt the serialized string with the action id as the salt.\n */\nasync function decodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (typeof key === 'undefined') {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get the iv (16 bytes) and the payload from the arg.\n const originalPayload = atob(arg)\n const ivValue = originalPayload.slice(0, 16)\n const payload = originalPayload.slice(16)\n\n const decrypted = textDecoder.decode(\n await decrypt(key, stringToUint8Array(ivValue), stringToUint8Array(payload))\n )\n\n if (!decrypted.startsWith(actionId)) {\n throw new Error('Invalid Server Action payload: failed to decrypt.')\n }\n\n return decrypted.slice(actionId.length)\n}\n\n/**\n * Encrypt the serialized string with the action id as the salt. Add a prefix to\n * later ensure that the payload is correctly decrypted, similar to a checksum.\n */\nasync function encodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (key === undefined) {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get 16 random bytes as iv.\n const randomBytes = new Uint8Array(16)\n workUnitAsyncStorage.exit(() => crypto.getRandomValues(randomBytes))\n const ivValue = arrayBufferToString(randomBytes.buffer)\n\n const encrypted = await encrypt(\n key,\n randomBytes,\n textEncoder.encode(actionId + arg)\n )\n\n return btoa(ivValue + arrayBufferToString(encrypted))\n}\n\nenum ReadStatus {\n Ready,\n Pending,\n Complete,\n}\n\n// Encrypts the action's bound args into a string. For the same combination of\n// actionId and args the same cached promise is returned. This ensures reference\n// equality for returned objects from \"use cache\" functions when they're invoked\n// multiple times within one render pass using the same bound args.\nexport const encryptActionBoundArgs = React.cache(\n async function encryptActionBoundArgs(actionId: string, ...args: any[]) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const cacheSignal = workUnitStore\n ? getCacheSignal(workUnitStore)\n : undefined\n\n const { clientModules } = getClientReferenceManifest()\n\n // Create an error before any asynchronous calls, to capture the original\n // call stack in case we need it when the serialization errors.\n const error = new Error()\n Error.captureStackTrace(error, encryptActionBoundArgs)\n\n let didCatchError = false\n\n const hangingInputAbortSignal = workUnitStore\n ? createHangingInputAbortSignal(workUnitStore)\n : undefined\n\n let readStatus = ReadStatus.Ready\n function startReadOnce() {\n if (readStatus === ReadStatus.Ready) {\n readStatus = ReadStatus.Pending\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readStatus === ReadStatus.Pending) {\n cacheSignal?.endRead()\n }\n readStatus = ReadStatus.Complete\n }\n\n // streamToString might take longer than a microtask to resolve and then other things\n // waiting on the cache signal might not realize there is another cache to fill so if\n // we are no longer waiting on the bound args serialization via the hangingInputAbortSignal\n // we should eagerly start the cache read to prevent other readers of the cache signal from\n // missing this cache fill. We use a idempotent function to only start reading once because\n // it's also possible that streamToString finishes before the hangingInputAbortSignal aborts.\n if (hangingInputAbortSignal && cacheSignal) {\n hangingInputAbortSignal.addEventListener('abort', startReadOnce, {\n once: true,\n })\n }\n\n const resumeDataCache = workUnitStore\n ? getResumeDataCache(workUnitStore)\n : null\n\n // Using Flight to serialize the args into a string.\n const serialized = await streamToString(\n renderToReadableStream(args, clientModules, {\n filterStackFrame,\n signal: hangingInputAbortSignal,\n debugChannel:\n // In Cache Components, we want to cache the encrypted result,\n // and we use the unencrypted bound args as a cache key.\n // In order to do that we need to strip debug info, because it\n // contains timing information and thus changes each time we serialize the args.\n // We can do this by piping debug info into a debug channel that throws it away.\n //\n // Note that this can result in dangling debug info references when we decode the bound args,\n // but React ignores those as long as no debug channel is passed on the decode side, so it's fine:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n process.env.NODE_ENV === 'development' && resumeDataCache\n ? {\n writable: new WritableStream(),\n }\n : undefined,\n onError(err) {\n if (hangingInputAbortSignal?.aborted) {\n return\n }\n\n // We're only reporting one error at a time, starting with the first.\n if (didCatchError) {\n return\n }\n\n didCatchError = true\n\n // Use the original error message together with the previously created\n // stack, because err.stack is a useless Flight Server call stack.\n error.message = err instanceof Error ? err.message : String(err)\n },\n }),\n // We pass the abort signal to `streamToString` so that no chunks are\n // included that are emitted after the signal was already aborted. This\n // ensures that we can encode hanging promises.\n hangingInputAbortSignal\n )\n\n if (didCatchError) {\n if (process.env.NODE_ENV === 'development') {\n // Logging the error is needed for server functions that are passed to the\n // client where the decryption is not done during rendering. Console\n // replaying allows us to still show the error dev overlay in this case.\n console.error(error)\n }\n\n endReadIfStarted()\n throw error\n }\n\n if (!workUnitStore) {\n // We don't need to call cacheSignal.endRead here because we can't have a cacheSignal\n // if we do not have a workUnitStore.\n return encodeActionBoundArg(actionId, serialized)\n }\n\n startReadOnce()\n\n const cacheKey = actionId + serialized\n\n const cachedEncrypted = resumeDataCache?.encryptedBoundArgs.get(cacheKey)\n\n if (cachedEncrypted) {\n return cachedEncrypted\n }\n\n const encrypted = await encodeActionBoundArg(actionId, serialized)\n\n endReadIfStarted()\n if (resumeDataCache?.mutable) {\n resumeDataCache.encryptedBoundArgs.set(cacheKey, encrypted)\n }\n\n return encrypted\n }\n)\n\n// Decrypts the action's bound args from the encrypted string.\nexport async function decryptActionBoundArgs(\n actionId: string,\n encryptedPromise: Promise<string>\n) {\n const encrypted = await encryptedPromise\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n let decrypted: string | undefined\n\n if (workUnitStore) {\n const cacheSignal = getCacheSignal(workUnitStore)\n const resumeDataCache = getResumeDataCache(workUnitStore)\n\n decrypted = resumeDataCache?.decryptedBoundArgs.get(encrypted)\n\n if (!decrypted) {\n cacheSignal?.beginRead()\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n cacheSignal?.endRead()\n if (resumeDataCache?.mutable) {\n resumeDataCache.decryptedBoundArgs.set(encrypted, decrypted)\n }\n }\n } else {\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n }\n\n const { edgeRscModuleMapping, rscModuleMapping } =\n getClientReferenceManifest()\n\n // Using Flight to deserialize the args from the string.\n const deserialized = await createFromReadableStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue(textEncoder.encode(decrypted))\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // Explicitly don't close the stream here (until prerendering is\n // complete) so that hanging promises are not rejected.\n if (workUnitStore.renderSignal.aborted) {\n controller.close()\n } else {\n workUnitStore.renderSignal.addEventListener(\n 'abort',\n () => controller.close(),\n { once: true }\n )\n }\n break\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return controller.close()\n default:\n workUnitStore satisfies never\n }\n },\n }),\n {\n findSourceMapURL,\n // NOTE: When we serialized the bound args, we may have used a dummy debug channel to strip debug info.\n // In that case, it's important that we also *don't* pass a debug channel here, because that will make\n // the Flight Client ignore the dangling references:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n debugChannel: undefined,\n serverConsumerManifest: {\n // moduleLoading must be null because we don't want to trigger preloads of ClientReferences\n // to be added to the current execution. Instead, we'll wait for any ClientReference\n // to be emitted which themselves will handle the preloading.\n moduleLoading: null,\n moduleMap: isEdgeRuntime ? edgeRscModuleMapping : rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n }\n )\n\n return deserialized\n}\n"],"names":["decryptActionBoundArgs","encryptActionBoundArgs","isEdgeRuntime","process","env","NEXT_RUNTIME","textEncoder","TextEncoder","textDecoder","TextDecoder","filterStackFrame","NODE_ENV","require","filterStackFrameDEV","undefined","findSourceMapURL","findSourceMapURLDEV","decodeActionBoundArg","actionId","arg","key","getActionEncryptionKey","Error","originalPayload","atob","ivValue","slice","payload","decrypted","decode","decrypt","stringToUint8Array","startsWith","length","encodeActionBoundArg","randomBytes","Uint8Array","workUnitAsyncStorage","exit","crypto","getRandomValues","arrayBufferToString","buffer","encrypted","encrypt","encode","btoa","ReadStatus","React","cache","args","workUnitStore","getStore","cacheSignal","getCacheSignal","clientModules","getClientReferenceManifest","error","captureStackTrace","didCatchError","hangingInputAbortSignal","createHangingInputAbortSignal","readStatus","startReadOnce","beginRead","endReadIfStarted","endRead","addEventListener","once","resumeDataCache","getResumeDataCache","serialized","streamToString","renderToReadableStream","signal","debugChannel","writable","WritableStream","onError","err","aborted","message","String","console","cacheKey","cachedEncrypted","encryptedBoundArgs","get","mutable","set","encryptedPromise","decryptedBoundArgs","edgeRscModuleMapping","rscModuleMapping","deserialized","createFromReadableStream","ReadableStream","start","controller","enqueue","type","renderSignal","close","serverConsumerManifest","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap"],"mappings":"AAAA,oDAAoD;;;;;;;;;;;;;;;IAkP9BA,sBAAsB;eAAtBA;;IAvITC,sBAAsB;eAAtBA;;;QA1GN;wBAGgC;wBAEE;sCAEV;iCAOxB;oCAIA;8CAKA;kCACuC;8DAC5B;;;;;;AAElB,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD,MAAMC,cAAc,IAAIC;AACxB,MAAMC,cAAc,IAAIC;AAExB,MAAMC,mBACJP,QAAQC,GAAG,CAACO,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AACN,MAAMC,mBACJZ,QAAQC,GAAG,CAACO,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNI,mBAAmB,GACtBF;AAEN;;CAEC,GACD,eAAeG,qBAAqBC,QAAgB,EAAEC,GAAW;IAC/D,MAA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T","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/app-render/encryption.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport 'server-only'\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport { renderToReadableStream } from 'react-server-dom-webpack/server'\n/* eslint-disable import/no-extraneous-dependencies */\nimport { createFromReadableStream } from 'react-server-dom-webpack/client'\n\nimport { streamToString } from '../stream-utils/node-web-streams-helper'\nimport {\n arrayBufferToString,\n decrypt,\n encrypt,\n getActionEncryptionKey,\n stringToUint8Array,\n} from './encryption-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from './manifests-singleton'\nimport {\n getCacheSignal,\n getResumeDataCache,\n workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from './dynamic-rendering'\nimport React from 'react'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Decrypt the serialized string with the action id as the salt.\n */\nasync function decodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (typeof key === 'undefined') {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get the iv (16 bytes) and the payload from the arg.\n const originalPayload = atob(arg)\n const ivValue = originalPayload.slice(0, 16)\n const payload = originalPayload.slice(16)\n\n const decrypted = textDecoder.decode(\n await decrypt(key, stringToUint8Array(ivValue), stringToUint8Array(payload))\n )\n\n if (!decrypted.startsWith(actionId)) {\n throw new Error('Invalid Server Action payload: failed to decrypt.')\n }\n\n return decrypted.slice(actionId.length)\n}\n\n/**\n * Encrypt the serialized string with the action id as the salt. Add a prefix to\n * later ensure that the payload is correctly decrypted, similar to a checksum.\n */\nasync function encodeActionBoundArg(actionId: string, arg: string) {\n const key = await getActionEncryptionKey()\n if (key === undefined) {\n throw new Error(\n `Missing encryption key for Server Action. This is a bug in Next.js`\n )\n }\n\n // Get 16 random bytes as iv.\n const randomBytes = new Uint8Array(16)\n workUnitAsyncStorage.exit(() => crypto.getRandomValues(randomBytes))\n const ivValue = arrayBufferToString(randomBytes.buffer)\n\n const encrypted = await encrypt(\n key,\n randomBytes,\n textEncoder.encode(actionId + arg)\n )\n\n return btoa(ivValue + arrayBufferToString(encrypted))\n}\n\nenum ReadStatus {\n Ready,\n Pending,\n Complete,\n}\n\n// Encrypts the action's bound args into a string. For the same combination of\n// actionId and args the same cached promise is returned. This ensures reference\n// equality for returned objects from \"use cache\" functions when they're invoked\n// multiple times within one render pass using the same bound args.\nexport const encryptActionBoundArgs = React.cache(\n async function encryptActionBoundArgs(actionId: string, ...args: any[]) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const cacheSignal = workUnitStore\n ? getCacheSignal(workUnitStore)\n : undefined\n\n const { clientModules } = getClientReferenceManifest()\n\n // Create an error before any asynchronous calls, to capture the original\n // call stack in case we need it when the serialization errors.\n const error = new Error()\n Error.captureStackTrace(error, encryptActionBoundArgs)\n\n let didCatchError = false\n\n const hangingInputAbortSignal = workUnitStore\n ? createHangingInputAbortSignal(workUnitStore)\n : undefined\n\n let readStatus = ReadStatus.Ready\n function startReadOnce() {\n if (readStatus === ReadStatus.Ready) {\n readStatus = ReadStatus.Pending\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readStatus === ReadStatus.Pending) {\n cacheSignal?.endRead()\n }\n readStatus = ReadStatus.Complete\n }\n\n // streamToString might take longer than a microtask to resolve and then other things\n // waiting on the cache signal might not realize there is another cache to fill so if\n // we are no longer waiting on the bound args serialization via the hangingInputAbortSignal\n // we should eagerly start the cache read to prevent other readers of the cache signal from\n // missing this cache fill. We use a idempotent function to only start reading once because\n // it's also possible that streamToString finishes before the hangingInputAbortSignal aborts.\n if (hangingInputAbortSignal && cacheSignal) {\n hangingInputAbortSignal.addEventListener('abort', startReadOnce, {\n once: true,\n })\n }\n\n const resumeDataCache = workUnitStore\n ? getResumeDataCache(workUnitStore)\n : null\n\n // Using Flight to serialize the args into a string.\n const serialized = await streamToString(\n renderToReadableStream(args, clientModules, {\n filterStackFrame,\n signal: hangingInputAbortSignal,\n debugChannel:\n // In Cache Components, we want to cache the encrypted result,\n // and we use the unencrypted bound args as a cache key.\n // In order to do that we need to strip debug info, because it\n // contains timing information and thus changes each time we serialize the args.\n // We can do this by piping debug info into a debug channel that throws it away.\n //\n // Note that this can result in dangling debug info references when we decode the bound args,\n // but React ignores those as long as no debug channel is passed on the decode side, so it's fine:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n process.env.NODE_ENV === 'development' && resumeDataCache\n ? {\n writable: new WritableStream(),\n }\n : undefined,\n onError(err) {\n if (hangingInputAbortSignal?.aborted) {\n return\n }\n\n // We're only reporting one error at a time, starting with the first.\n if (didCatchError) {\n return\n }\n\n didCatchError = true\n\n // Use the original error message together with the previously created\n // stack, because err.stack is a useless Flight Server call stack.\n error.message = err instanceof Error ? err.message : String(err)\n },\n }),\n // We pass the abort signal to `streamToString` so that no chunks are\n // included that are emitted after the signal was already aborted. This\n // ensures that we can encode hanging promises.\n hangingInputAbortSignal\n )\n\n if (didCatchError) {\n if (process.env.NODE_ENV === 'development') {\n // Logging the error is needed for server functions that are passed to the\n // client where the decryption is not done during rendering. Console\n // replaying allows us to still show the error dev overlay in this case.\n console.error(error)\n }\n\n endReadIfStarted()\n throw error\n }\n\n if (!workUnitStore) {\n // We don't need to call cacheSignal.endRead here because we can't have a cacheSignal\n // if we do not have a workUnitStore.\n return encodeActionBoundArg(actionId, serialized)\n }\n\n startReadOnce()\n\n const cacheKey = actionId + serialized\n\n const cachedEncrypted = resumeDataCache?.encryptedBoundArgs.get(cacheKey)\n\n if (cachedEncrypted) {\n return cachedEncrypted\n }\n\n const encrypted = await encodeActionBoundArg(actionId, serialized)\n\n endReadIfStarted()\n if (resumeDataCache?.mutable) {\n resumeDataCache.encryptedBoundArgs.set(cacheKey, encrypted)\n }\n\n return encrypted\n }\n)\n\n// Decrypts the action's bound args from the encrypted string.\nexport async function decryptActionBoundArgs(\n actionId: string,\n encryptedPromise: Promise<string>\n) {\n const encrypted = await encryptedPromise\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n let decrypted: string | undefined\n\n if (workUnitStore) {\n const cacheSignal = getCacheSignal(workUnitStore)\n const resumeDataCache = getResumeDataCache(workUnitStore)\n\n decrypted = resumeDataCache?.decryptedBoundArgs.get(encrypted)\n\n if (!decrypted) {\n cacheSignal?.beginRead()\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n cacheSignal?.endRead()\n if (resumeDataCache?.mutable) {\n resumeDataCache.decryptedBoundArgs.set(encrypted, decrypted)\n }\n }\n } else {\n decrypted = await decodeActionBoundArg(actionId, encrypted)\n }\n\n const { edgeRscModuleMapping, rscModuleMapping } =\n getClientReferenceManifest()\n\n // Using Flight to deserialize the args from the string.\n const deserialized = await createFromReadableStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue(textEncoder.encode(decrypted))\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // Explicitly don't close the stream here (until prerendering is\n // complete) so that hanging promises are not rejected.\n if (workUnitStore.renderSignal.aborted) {\n controller.close()\n } else {\n workUnitStore.renderSignal.addEventListener(\n 'abort',\n () => controller.close(),\n { once: true }\n )\n }\n break\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n return controller.close()\n default:\n workUnitStore satisfies never\n }\n },\n }),\n {\n findSourceMapURL,\n // NOTE: When we serialized the bound args, we may have used a dummy debug channel to strip debug info.\n // In that case, it's important that we also *don't* pass a debug channel here, because that will make\n // the Flight Client ignore the dangling references:\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729\n // https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025\n debugChannel: undefined,\n serverConsumerManifest: {\n // moduleLoading must be null because we don't want to trigger preloads of ClientReferences\n // to be added to the current execution. Instead, we'll wait for any ClientReference\n // to be emitted which themselves will handle the preloading.\n moduleLoading: null,\n moduleMap: isEdgeRuntime ? edgeRscModuleMapping : rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n }\n )\n\n return deserialized\n}\n"],"names":["decryptActionBoundArgs","encryptActionBoundArgs","isEdgeRuntime","process","env","NEXT_RUNTIME","textEncoder","TextEncoder","textDecoder","TextDecoder","filterStackFrame","NODE_ENV","require","filterStackFrameDEV","undefined","findSourceMapURL","findSourceMapURLDEV","decodeActionBoundArg","actionId","arg","key","getActionEncryptionKey","Error","originalPayload","atob","ivValue","slice","payload","decrypted","decode","decrypt","stringToUint8Array","startsWith","length","encodeActionBoundArg","randomBytes","Uint8Array","workUnitAsyncStorage","exit","crypto","getRandomValues","arrayBufferToString","buffer","encrypted","encrypt","encode","btoa","ReadStatus","React","cache","args","workUnitStore","getStore","cacheSignal","getCacheSignal","clientModules","getClientReferenceManifest","error","captureStackTrace","didCatchError","hangingInputAbortSignal","createHangingInputAbortSignal","readStatus","startReadOnce","beginRead","endReadIfStarted","endRead","addEventListener","once","resumeDataCache","getResumeDataCache","serialized","streamToString","renderToReadableStream","signal","debugChannel","writable","WritableStream","onError","err","aborted","message","String","console","cacheKey","cachedEncrypted","encryptedBoundArgs","get","mutable","set","encryptedPromise","decryptedBoundArgs","edgeRscModuleMapping","rscModuleMapping","deserialized","createFromReadableStream","ReadableStream","start","controller","enqueue","type","renderSignal","close","serverConsumerManifest","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap"],"mappings":"AAAA,oDAAoD;;;;;;;;;;;;;;;IAkP9BA,sBAAsB;eAAtBA;;IAvITC,sBAAsB;eAAtBA;;;QA1GN;wBAGgC;wBAEE;sCAEV;iCAOxB;oCAIA;8CAKA;kCACuC;8DAC5B;;;;;;AAElB,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD,MAAMC,cAAc,IAAIC;AACxB,MAAMC,cAAc,IAAIC;AAExB,MAAMC,mBACJP,QAAQC,GAAG,CAACO,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AACN,MAAMC,mBACJZ,QAAQC,GAAG,CAACO,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNI,mBAAmB,GACtBF;AAEN;;CAEC,GACD,eAAeG,qBAAqBC,QAAgB,EAAEC,GAAW;IAC/D,MAAMC,MAAM,MAAMC,IAAAA,uCAAsB;IACxC,IAAI,OAAOD,QAAQ,aAAa;QAC9B,MAAM,qBAEL,CAFK,IAAIE,MACR,CAAC,kEAAkE,CAAC,GADhE,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,sDAAsD;IACtD,MAAMC,kBAAkBC,KAAKL;IAC7B,MAAMM,UAAUF,gBAAgBG,KAAK,CAAC,GAAG;IACzC,MAAMC,UAAUJ,gBAAgBG,KAAK,CAAC;IAEtC,MAAME,YAAYpB,YAAYqB,MAAM,CAClC,MAAMC,IAAAA,wBAAO,EAACV,KAAKW,IAAAA,mCAAkB,EAACN,UAAUM,IAAAA,mCAAkB,EAACJ;IAGrE,IAAI,CAACC,UAAUI,UAAU,CAACd,WAAW;QACnC,MAAM,qBAA8D,CAA9D,IAAII,MAAM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iD,IAAI;gBACzB,KAAK;gBACL,KAAK;oBACH,gEAAgE;oBAChE,uDAAuD;oBACvD,IAAIjD,cAAckD,YAAY,CAACrB,OAAO,EAAE;wBACtCkB,WAAWI,KAAK;oBAClB,OAAO;wBACLnD,cAAckD,YAAY,CAAClC,gBAAgB,CACzC,SACA,IAAM+B,WAAWI,KAAK,IACtB;4BAAElC,MAAM;wBAAK;oBAEjB;oBACA;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAKtD;oBACH,OAAOoF,WAAWI,KAAK;gBACzB;oBACEnD;YACJ;QACF;IACF,IACA;QACEpC;QACA,uGAAuG;QACvG,sGAAsG;QACtG,oDAAoD;QACpD,6IAA6I;QAC7I,6IAA6I;QAC7I4D,cAAc7D;QACdyF,wBAAwB;YACtB,2FAA2F;YAC3F,oFAAoF;YACpF,6DAA6D;YAC7DC,eAAe;YACfC,WAAWvG,gBAAgB0F,uBAAuBC;YAClDa,iBAAiBC,IAAAA,sCAAkB;QACrC;IACF;IAGF,OAAOb;AACT","ignoreList":[0]}

@@ -25,3 +25,2 @@ export { createTemporaryReferenceSet, renderToReadableStream, decodeReply, decodeAction, decodeFormState, } from 'react-server-dom-webpack/server';

export { isEmptyHTMLPrelude } from './postponed-state';
export { Postpone } from './rsc/postpone';
export { taintObjectReference } from './rsc/taint';

@@ -28,0 +27,0 @@ export { collectSegmentData, collectPrefetchHints, } from './collect-segment-data';

@@ -14,3 +14,2 @@ // eslint-disable-next-line import/no-extraneous-dependencies

LoadingBoundaryProvider: null,
Postpone: null,
RenderFromTemplateContext: null,

@@ -73,5 +72,2 @@ RootLayoutBoundary: null,

},
Postpone: function() {
return _postpone.Postpone;
},
RenderFromTemplateContext: function() {

@@ -177,3 +173,2 @@ return _renderfromtemplatecontext.default;

const _postponedstate = require("./postponed-state");
const _postpone = require("./rsc/postpone");
const _taint = require("./rsc/taint");

@@ -180,0 +175,0 @@ const _collectsegmentdata = require("./collect-segment-data");

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/app-render/entry-base.ts"],"sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nexport {\n createTemporaryReferenceSet,\n renderToReadableStream,\n decodeReply,\n decodeAction,\n decodeFormState,\n} from 'react-server-dom-webpack/server'\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nexport { prerender } from 'react-server-dom-webpack/static'\n\n// Node.js-specific Flight APIs, needed by stream-ops.node.ts via ComponentMod.\n// These must be exported from entry-base (react-server layer) because direct\n// imports from react-server-dom-webpack/* fail outside this layer.\ntype FlightRenderToPipeableStream = (...args: any[]) => {\n pipe<Writable extends NodeJS.WritableStream>(destination: Writable): Writable\n abort: (reason?: unknown) => void\n}\n\ntype FlightPrerenderToNodeStream = (...args: any[]) => Promise<{\n prelude: import('node:stream').Readable\n}>\n\n/* eslint-disable import/no-extraneous-dependencies */\nexport let renderToPipeableStream: FlightRenderToPipeableStream | undefined\nexport let prerenderToNodeStream: FlightPrerenderToNodeStream | undefined\nif (process.env.__NEXT_USE_NODE_STREAMS) {\n renderToPipeableStream = (\n require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')\n ).renderToPipeableStream\n prerenderToNodeStream = (\n require('react-server-dom-webpack/static') as typeof import('react-server-dom-webpack/static')\n ).prerenderToNodeStream\n} else {\n renderToPipeableStream = undefined\n prerenderToNodeStream = undefined\n}\n/* eslint-enable import/no-extraneous-dependencies */\n\n// TODO: Just re-export `* as ReactServer`\nexport { captureOwnerStack, createElement, Fragment } from 'react'\n\nexport {\n default as LayoutRouter,\n LoadingBoundaryProvider,\n} from '../../client/components/layout-router'\nexport { default as RenderFromTemplateContext } from '../../client/components/render-from-template-context'\nexport { ClientPageRoot } from '../../client/components/client-page'\nexport { ClientSegmentRoot } from '../../client/components/client-segment'\nexport {\n createServerSearchParamsForServerPage,\n createPrerenderSearchParamsForClientPage,\n} from '../request/search-params'\nexport {\n createServerParamsForServerSegment,\n createPrerenderParamsForClientSegment,\n} from '../request/params'\nexport * as serverHooks from '../../client/components/hooks-server-context'\nexport { HTTPAccessFallbackBoundary } from '../../client/components/http-access-fallback/error-boundary'\nexport { createMetadataComponents } from '../../lib/metadata/metadata'\nexport { RootLayoutBoundary } from '../../lib/framework/boundary-components'\n\nexport { preloadStyle, preloadFont, preconnect } from './rsc/preloads'\nexport { isEmptyHTMLPrelude } from './postponed-state'\nexport { Postpone } from './rsc/postpone'\nexport { taintObjectReference } from './rsc/taint'\nexport {\n collectSegmentData,\n collectPrefetchHints,\n} from './collect-segment-data'\n\nexport const InstantValidation = () => {\n if (\n process.env.NEXT_RUNTIME !== 'edge' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n return require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation')\n } else {\n return undefined\n }\n}\n\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { patchFetch as _patchFetch } from '../lib/patch-fetch'\n\nlet SegmentViewNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewNode =\n () => null\nlet SegmentViewStateNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewStateNode =\n () => null\nif (process.env.NODE_ENV === 'development') {\n const mod =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n SegmentViewNode = mod.SegmentViewNode\n SegmentViewStateNode = mod.SegmentViewStateNode\n}\n\n// For hot-reloader\ndeclare global {\n var __next__clear_chunk_cache__: (() => void) | null | undefined\n var __turbopack_clear_chunk_cache__: () => void | null | undefined\n var __turbopack_server_hmr_apply__:\n | ((update: NodeJsPartialHmrUpdate) => void)\n | undefined\n}\n\n// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`\n// into globalThis from this file which is bundled.\nif (process.env.TURBOPACK) {\n globalThis.__next__clear_chunk_cache__ = __turbopack_clear_chunk_cache__\n} else {\n // Webpack does not have chunks on the server\n globalThis.__next__clear_chunk_cache__ = null\n}\n\n// patchFetch makes use of APIs such as `React.unstable_postpone` which are only available\n// in the experimental channel of React, so export it from here so that it comes from the bundled runtime\nexport function patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\n// Development only\nexport { SegmentViewNode, SegmentViewStateNode }\n"],"names":["ClientPageRoot","ClientSegmentRoot","Fragment","HTTPAccessFallbackBoundary","InstantValidation","LayoutRouter","LoadingBoundaryProvider","Postpone","RenderFromTemplateContext","RootLayoutBoundary","SegmentViewNode","SegmentViewStateNode","captureOwnerStack","collectPrefetchHints","collectSegmentData","createElement","createMetadataComponents","createPrerenderParamsForClientSegment","createPrerenderSearchParamsForClientPage","createServerParamsForServerSegment","createServerSearchParamsForServerPage","createTemporaryReferenceSet","decodeAction","decodeFormState","decodeReply","isEmptyHTMLPrelude","patchFetch","preconnect","preloadFont","preloadStyle","prerender","prerenderToNodeStream","renderToPipeableStream","renderToReadableStream","serverHooks","taintObjectReference","process","env","__NEXT_USE_NODE_STREAMS","require","undefined","NEXT_RUNTIME","__NEXT_CACHE_COMPONENTS","NODE_ENV","mod","TURBOPACK","globalThis","__next__clear_chunk_cache__","__turbopack_clear_chunk_cache__","_patchFetch","workAsyncStorage","workUnitAsyncStorage"],"mappings":"AAAA,6DAA6D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAgDpDA,cAAc;eAAdA,0BAAc;;IACdC,iBAAiB;eAAjBA,gCAAiB;;IARiBC,QAAQ;eAARA,eAAQ;;IAkB1CC,0BAA0B;eAA1BA,yCAA0B;;IAatBC,iBAAiB;eAAjBA;;IA5BAC,YAAY;eAAZA,qBAAY;;IACvBC,uBAAuB;eAAvBA,qCAAuB;;IAoBhBC,QAAQ;eAARA,kBAAQ;;IAlBGC,yBAAy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AO;IACLC,yBAAyBQ;IACzBT,wBAAwBS;AAC1B;AAmCO,MAAMpC,oBAAoB;IAC/B,IACEgC,QAAQC,GAAG,CAACI,YAAY,KAAK,UAC7BL,QAAQC,GAAG,CAACK,uBAAuB,EACnC;QACA,OAAOH,QAAQ;IACjB,OAAO;QACL,OAAOC;IACT;AACF;AAOA,IAAI9B,kBACF,IAAM;AACR,IAAIC,uBACF,IAAM;AACR,IAAIyB,QAAQC,GAAG,CAACM,QAAQ,KAAK,eAAe;IAC1C,MAAMC,MACJL,QAAQ;IACV7B,kBAAkBkC,IAAIlC,eAAe;IACrCC,uBAAuBiC,IAAIjC,oBAAoB;AACjD;AAWA,0FAA0F;AAC1F,mDAAmD;AACnD,IAAIyB,QAAQC,GAAG,CAACQ,SAAS,EAAE;IACzBC,WAAWC,2BAA2B,GAAGC;AAC3C,OAAO;IACL,6CAA6C;IAC7CF,WAAWC,2BAA2B,GAAG;AAC3C;AAIO,SAASrB;IACd,OAAOuB,IAAAA,sBAAW,EAAC;QACjBC,kBAAAA,0CAAgB;QAChBC,sBAAAA,kDAAoB;IACtB;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/app-render/entry-base.ts"],"sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nexport {\n createTemporaryReferenceSet,\n renderToReadableStream,\n decodeReply,\n decodeAction,\n decodeFormState,\n} from 'react-server-dom-webpack/server'\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nexport { prerender } from 'react-server-dom-webpack/static'\n\n// Node.js-specific Flight APIs, needed by stream-ops.node.ts via ComponentMod.\n// These must be exported from entry-base (react-server layer) because direct\n// imports from react-server-dom-webpack/* fail outside this layer.\ntype FlightRenderToPipeableStream = (...args: any[]) => {\n pipe<Writable extends NodeJS.WritableStream>(destination: Writable): Writable\n abort: (reason?: unknown) => void\n}\n\ntype FlightPrerenderToNodeStream = (...args: any[]) => Promise<{\n prelude: import('node:stream').Readable\n}>\n\n/* eslint-disable import/no-extraneous-dependencies */\nexport let renderToPipeableStream: FlightRenderToPipeableStream | undefined\nexport let prerenderToNodeStream: FlightPrerenderToNodeStream | undefined\nif (process.env.__NEXT_USE_NODE_STREAMS) {\n renderToPipeableStream = (\n require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')\n ).renderToPipeableStream\n prerenderToNodeStream = (\n require('react-server-dom-webpack/static') as typeof import('react-server-dom-webpack/static')\n ).prerenderToNodeStream\n} else {\n renderToPipeableStream = undefined\n prerenderToNodeStream = undefined\n}\n/* eslint-enable import/no-extraneous-dependencies */\n\n// TODO: Just re-export `* as ReactServer`\nexport { captureOwnerStack, createElement, Fragment } from 'react'\n\nexport {\n default as LayoutRouter,\n LoadingBoundaryProvider,\n} from '../../client/components/layout-router'\nexport { default as RenderFromTemplateContext } from '../../client/components/render-from-template-context'\nexport { ClientPageRoot } from '../../client/components/client-page'\nexport { ClientSegmentRoot } from '../../client/components/client-segment'\nexport {\n createServerSearchParamsForServerPage,\n createPrerenderSearchParamsForClientPage,\n} from '../request/search-params'\nexport {\n createServerParamsForServerSegment,\n createPrerenderParamsForClientSegment,\n} from '../request/params'\nexport * as serverHooks from '../../client/components/hooks-server-context'\nexport { HTTPAccessFallbackBoundary } from '../../client/components/http-access-fallback/error-boundary'\nexport { createMetadataComponents } from '../../lib/metadata/metadata'\nexport { RootLayoutBoundary } from '../../lib/framework/boundary-components'\n\nexport { preloadStyle, preloadFont, preconnect } from './rsc/preloads'\nexport { isEmptyHTMLPrelude } from './postponed-state'\nexport { taintObjectReference } from './rsc/taint'\nexport {\n collectSegmentData,\n collectPrefetchHints,\n} from './collect-segment-data'\n\nexport const InstantValidation = () => {\n if (\n process.env.NEXT_RUNTIME !== 'edge' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n return require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation')\n } else {\n return undefined\n }\n}\n\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { patchFetch as _patchFetch } from '../lib/patch-fetch'\n\nlet SegmentViewNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewNode =\n () => null\nlet SegmentViewStateNode: typeof import('../../next-devtools/userspace/app/segment-explorer-node').SegmentViewStateNode =\n () => null\nif (process.env.NODE_ENV === 'development') {\n const mod =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n SegmentViewNode = mod.SegmentViewNode\n SegmentViewStateNode = mod.SegmentViewStateNode\n}\n\n// For hot-reloader\ndeclare global {\n var __next__clear_chunk_cache__: (() => void) | null | undefined\n var __turbopack_clear_chunk_cache__: () => void | null | undefined\n var __turbopack_server_hmr_apply__:\n | ((update: NodeJsPartialHmrUpdate) => void)\n | undefined\n}\n\n// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`\n// into globalThis from this file which is bundled.\nif (process.env.TURBOPACK) {\n globalThis.__next__clear_chunk_cache__ = __turbopack_clear_chunk_cache__\n} else {\n // Webpack does not have chunks on the server\n globalThis.__next__clear_chunk_cache__ = null\n}\n\nexport function patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\n// Development only\nexport { SegmentViewNode, SegmentViewStateNode }\n"],"names":["ClientPageRoot","ClientSegmentRoot","Fragment","HTTPAccessFallbackBoundary","InstantValidation","LayoutRouter","LoadingBoundaryProvider","RenderFromTemplateContext","RootLayoutBoundary","SegmentViewNode","SegmentViewStateNode","captureOwnerStack","collectPrefetchHints","collectSegmentData","createElement","createMetadataComponents","createPrerenderParamsForClientSegment","createPrerenderSearchParamsForClientPage","createServerParamsForServerSegment","createServerSearchParamsForServerPage","createTemporaryReferenceSet","decodeAction","decodeFormState","decodeReply","isEmptyHTMLPrelude","patchFetch","preconnect","preloadFont","preloadStyle","prerender","prerenderToNodeStream","renderToPipeableStream","renderToReadableStream","serverHooks","taintObjectReference","process","env","__NEXT_USE_NODE_STREAMS","require","undefined","NEXT_RUNTIME","__NEXT_CACHE_COMPONENTS","NODE_ENV","mod","TURBOPACK","globalThis","__next__clear_chunk_cache__","__turbopack_clear_chunk_cache__","_patchFetch","workAsyncStorage","workUnitAsyncStorage"],"mappings":"AAAA,6DAA6D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAgDpDA,cAAc;eAAdA,0BAAc;;IACdC,iBAAiB;eAAjBA,gCAAiB;;IARiBC,QAAQ;eAARA,eAAQ;;IAkB1CC,0BAA0B;eAA1BA,yCAA0B;;IAYtBC,iBAAiB;eAAjBA;;IA3BAC,YAAY;eAAZA,qBAAY;;IACvBC,uBAAuB;eAAvBA,qCAAuB;;IAELC,yBAAyB;eAAzBA,kCAAyB;;IAcpCC,kBAAkB;eAAlBA,sCAAkB;;IA+DlBC,eAAe;eAAfA;;IAAiBC,oBAAoB;eAApBA;;IAnFjBC,iBAAiB;eAAjBA,wBAAiB;;IA2BxBC,oBAAoB;eAApBA,wCAAoB;;IADpBC,kBAAkB;eAAlBA,sCAAkB;;IA1BQC,aAAa;eAAbA,oBAAa;;IAmBhCC,wBAAwB;eAAxBA,kCAAwB;;IAJ/BC,qCAAqC;eAArCA,6CAAqC;;IAJrCC,wCAAwC;eAAxCA,sDAAwC;;IAGxCC,kCAAkC;eAAlCA,0CAAkC;;IAJlCC,qCAAqC;eAArCA,mDAAqC;;IAjDrCC,2BAA2B;eAA3BA,mCAA2B;;IAG3BC,YAAY;eAAZA,oBAAY;;IACZC,eAAe;eAAfA,uBAAe;;IAFfC,WAAW;eAAXA,mBAAW;;IA4DJC,kBAAkB;eAAlBA,kCAAkB;;IAoDXC,UAAU;eAAVA;;IArDoBC,UAAU;eAAVA,oBAAU;;IAAvBC,WAAW;eAAXA,qBAAW;;IAAzBC,YAAY;eAAZA,sBAAY;;IArDZC,SAAS;eAATA,iBAAS;;IAgBPC,qBAAqB;eA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/no-ambiguous-jsx -- React Client */ // Do not put a "use client" directive here. Import this module via the shim in

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -57,0 +56,0 @@ case 'prerender-runtime':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/app-render/instant-validation/boundary-impl.tsx"],"sourcesContent":["/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */\n\n// Do not put a \"use client\" directive here. Import this module via the shim in\n// `packages/next/src/client/components/instant-validation/boundary.tsx` instead.\n// 'use client'\n\nimport { createContext, type ReactNode } from 'react'\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type { ValidationBoundaryTracking } from './boundary-tracking'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\n\nif (typeof window !== 'undefined') {\n throw new InvariantError(\n 'Instant validation boundaries should never appear in browser bundles.'\n )\n}\n\nfunction getValidationBoundaryTracking(): ValidationBoundaryTracking | null {\n const store = workUnitAsyncStorage.getStore()\n if (!store) return null\n switch (store.type) {\n case 'validation-client':\n return store.boundaryState\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n store satisfies never\n }\n return null\n}\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [INSTANT_VALIDATION_BOUNDARY_NAME]: function ({\n id,\n children,\n }: {\n id: string\n children: ReactNode\n }) {\n // Track which boundaries we actually managed to render.\n const state = getValidationBoundaryTracking()\n if (state === null) {\n throw new InvariantError('Missing boundary tracking state')\n }\n state.renderedIds.add(id)\n\n return children\n },\n}\n\ntype BoundaryPlacement =\n | null // do not place here\n | string // boundaryId -- place here\n\nexport const InstantValidationBoundaryContext =\n createContext<BoundaryPlacement>(null)\n\nexport function PlaceValidationBoundaryBelowThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n return (\n // OuterLayoutRouter will see this and render a `RenderValidationBoundaryAtThisLevel`.\n <InstantValidationBoundaryContext value={id}>\n {children}\n </InstantValidationBoundaryContext>\n )\n}\n\nexport function RenderValidationBoundaryAtThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n // We got a boundaryId from the context. Clear the context so that the children don't render another boundary.\n return (\n <InstantValidationBoundary id={id}>\n <InstantValidationBoundaryContext value={null}>\n {children}\n </InstantValidationBoundaryContext>\n </InstantValidationBoundary>\n )\n}\n\nconst InstantValidationBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n INSTANT_VALIDATION_BOUNDARY_NAME.slice(\n 0\n ) as typeof INSTANT_VALIDATION_BOUNDARY_NAME\n ]\n\n// Slot marker component for attributing validation errors to the\n// correct config when a boundary spans multiple parallel slots.\n// Renders a dynamically-named inner component so the slot index\n// appears in the SSR component stack (__next_instant_slot_N__).\nconst slotMarkerCache = new Map<\n string,\n (props: { children: ReactNode }) => ReactNode\n>()\n\nexport function SlotMarker({\n name,\n children,\n}: {\n name: string\n children: ReactNode\n}) {\n let Marker = slotMarkerCache.get(name)\n if (!Marker) {\n const ns = {\n [name]: function ({ children: c }: { children: ReactNode }) {\n return c\n },\n }\n Marker = ns[name]\n slotMarkerCache.set(name, Marker)\n }\n return <Marker>{children}</Marker>\n}\n"],"names":["InstantValidationBoundaryContext","PlaceValidationBoundaryBelowThisLevel","RenderValidationBoundaryAtThisLevel","SlotMarker","window","InvariantError","getValidationBoundaryTracking","store","workUnitAsyncStorage","getStore","type","boundaryState","NameSpace","INSTANT_VALIDATION_BOUNDARY_NAME","id","children","state","renderedIds","add","createContext","value","InstantValidationBoundary","slice","slotMarkerCache","Map","name","Marker","get","ns","c","set"],"mappings":"AAAA,kEAAkE,GAElE,+EAA+E;AAC/E,iFAAiF;AACjF,eAAe;;;;;;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AMM,4BACJ,gFAAgF;AAChF,4DAA4D;AAC5DT,SAAS,CACPC,mDAAgC,CAACS,KAAK,CACpC,GAEH;AAEH,iEAAiE;AACjE,gEAAgE;AAChE,gEAAgE;AAChE,gEAAgE;AAChE,MAAMC,kBAAkB,IAAIC;AAKrB,SAASrB,WAAW,EACzBsB,IAAI,EACJV,QAAQ,EAIT;IACC,IAAIW,SAASH,gBAAgBI,GAAG,CAACF;IACjC,IAAI,CAACC,QAAQ;QACX,MAAME,KAAK;YACT,CAACH,KAAK,EAAE,SAAU,EAAEV,UAAUc,CAAC,EAA2B;gBACxD,OAAOA;YACT;QACF;QACAH,SAASE,EAAE,CAACH,KAAK;QACjBF,gBAAgBO,GAAG,CAACL,MAAMC;IAC5B;IACA,qBAAO,qBAACA;kBAAQX;;AAClB","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/app-render/instant-validation/boundary-impl.tsx"],"sourcesContent":["/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */\n\n// Do not put a \"use client\" directive here. Import this module via the shim in\n// `packages/next/src/client/components/instant-validation/boundary.tsx` instead.\n// 'use client'\n\nimport { createContext, type ReactNode } from 'react'\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type { ValidationBoundaryTracking } from './boundary-tracking'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\n\nif (typeof window !== 'undefined') {\n throw new InvariantError(\n 'Instant validation boundaries should never appear in browser bundles.'\n )\n}\n\nfunction getValidationBoundaryTracking(): ValidationBoundaryTracking | null {\n const store = workUnitAsyncStorage.getStore()\n if (!store) return null\n switch (store.type) {\n case 'validation-client':\n return store.boundaryState\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n store satisfies never\n }\n return null\n}\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [INSTANT_VALIDATION_BOUNDARY_NAME]: function ({\n id,\n children,\n }: {\n id: string\n children: ReactNode\n }) {\n // Track which boundaries we actually managed to render.\n const state = getValidationBoundaryTracking()\n if (state === null) {\n throw new InvariantError('Missing boundary tracking state')\n }\n state.renderedIds.add(id)\n\n return children\n },\n}\n\ntype BoundaryPlacement =\n | null // do not place here\n | string // boundaryId -- place here\n\nexport const InstantValidationBoundaryContext =\n createContext<BoundaryPlacement>(null)\n\nexport function PlaceValidationBoundaryBelowThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n return (\n // OuterLayoutRouter will see this and render a `RenderValidationBoundaryAtThisLevel`.\n <InstantValidationBoundaryContext value={id}>\n {children}\n </InstantValidationBoundaryContext>\n )\n}\n\nexport function RenderValidationBoundaryAtThisLevel({\n id,\n children,\n}: {\n id: string\n children: ReactNode\n}) {\n // We got a boundaryId from the context. Clear the context so that the children don't render another boundary.\n return (\n <InstantValidationBoundary id={id}>\n <InstantValidationBoundaryContext value={null}>\n {children}\n </InstantValidationBoundaryContext>\n </InstantValidationBoundary>\n )\n}\n\nconst InstantValidationBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n INSTANT_VALIDATION_BOUNDARY_NAME.slice(\n 0\n ) as typeof INSTANT_VALIDATION_BOUNDARY_NAME\n ]\n\n// Slot marker component for attributing validation errors to the\n// correct config when a boundary spans multiple parallel slots.\n// Renders a dynamically-named inner component so the slot index\n// appears in the SSR component stack (__next_instant_slot_N__).\nconst slotMarkerCache = new Map<\n string,\n (props: { children: ReactNode }) => ReactNode\n>()\n\nexport function SlotMarker({\n name,\n children,\n}: {\n name: string\n children: ReactNode\n}) {\n let Marker = slotMarkerCache.get(name)\n if (!Marker) {\n const ns = {\n [name]: function ({ children: c }: { children: ReactNode }) {\n return c\n },\n }\n Marker = ns[name]\n slotMarkerCache.set(name, Marker)\n }\n return <Marker>{children}</Marker>\n}\n"],"names":["InstantValidationBoundaryContext","PlaceValidationBoundaryBelowThisLevel","RenderValidationBoundaryAtThisLevel","SlotMarker","window","InvariantError","getValidationBoundaryTracking","store","workUnitAsyncStorage","getStore","type","boundaryState","NameSpace","INSTANT_VALIDATION_BOUNDARY_NAME","id","children","state","renderedIds","add","createContext","value","InstantValidationBoundary","slice","slotMarkerCache","Map","name","Marker","get","ns","c","set"],"mappings":"AAAA,kEAAkE,GAElE,+EAA+E;AAC/E,iFAAiF;AACjF,eAAe;;;;;;;;;;;;;;;;;;IA6DFA,gCAAgC;eAAhCA;;IAGGC,qCAAqC;eAArCA;;IAeAC,mCAAmC;eAAnCA;;IAmCAC,UAAU;eAAVA;;;;uBAhH8B;mCACG;gCAClB;8CAEM;AAErC,IAAI,OAAOC,WAAW,aAAa;IACjC,MAAM,qBAEL,CAFK,IAAIC,8BAAc,CACtB,0EADI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,SAASC;IACP,MAAMC,QAAQC,kDAAoB,CAACC,QAAQ;IAC3C,IAAI,CAACF,OAAO,OAAO;IACnB,OAAQA,MAAMG,IAAI;QAChB,KAAK;YACH,OAAOH,MAAMI,aAAa;QAC5B,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEJ;IACJ;IACA,OAAO;AACT;AAEA,4EAA4E;AAC5E,iEAAiE;AACjE,MAAMK,YAAY;IAChB,CAACC,mDAAgC,CAAC,EAAE,SAAU,EAC5CC,EAAE,EACFC,QAAQ,EAIT;QACC,wDAAwD;QACxD,MAAMC,QAAQV;QACd,IAAIU,UAAU,MAAM;YAClB,MAAM,qBAAqD,CAArD,IAAIX,8BAAc,CAAC,oCAAnB,qBAAA;uBAAA;4BAAA;8BAAA;YAAoD;QAC5D;QACAW,MAAMC,WAAW,CAACC,GAAG,CAACJ;QAEtB,OAAOC;IACT;AACF;AAMO,MAAMf,iDACXmB,IAAAA,oBAAa,EAAoB;AAE5B,SAASlB,sCAAsC,EACpDa,EAAE,EACFC,QAAQ,EAIT;IACC,OACE,sFAAsF;kBACtF,qBAACf;QAAiCoB,OAAON;kBACtCC;;AAGP;AAEO,SAASb,oCAAoC,EAClDY,EAAE,EACFC,QAAQ,EAIT;IACC,8GAA8G;IAC9G,qBACE,qBAACM;QAA0BP,IAAIA;kBAC7B,cAAA,qBAACd;YAAiCoB,OAAO;sBACtCL;;;AAIT;AAEA,MAAMM,4BACJ,gFAAgF;AAChF,4DAA4D;AAC5DT,SAAS,CACPC,mDAAgC,CAACS,KAAK,CACpC,GAEH;AAEH,iEAAiE;AACjE,gEAAgE;AAChE,gEAAgE;AAChE,gEAAgE;AAChE,MAAMC,kBAAkB,IAAIC;AAKrB,SAASrB,WAAW,EACzBsB,IAAI,EACJV,QAAQ,EAIT;IACC,IAAIW,SAASH,gBAAgBI,GAAG,CAACF;IACjC,IAAI,CAACC,QAAQ;QACX,MAAME,KAAK;YACT,CAACH,KAAK,EAAE,SAAU,EAAEV,UAAUc,CAAC,EAA2B;gBACxD,OAAOA;YACT;QACF;QACAH,SAASE,EAAE,CAACH,KAAK;QACjBF,gBAAgBO,GAAG,CAACL,MAAMC;IAC5B;IACA,qBAAO,qBAACA;kBAAQX;;AAClB","ignoreList":[0]}

@@ -87,3 +87,2 @@ "use strict";

case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':

@@ -90,0 +89,0 @@ case 'prerender':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/app-render/instant-validation/instant-samples.ts"],"sourcesContent":["import type { InstantSample } from '../../../build/segment-config/app/app-segment-config'\nimport type { ReadonlyRequestCookies } from '../../web/spec-extension/adapters/request-cookies'\nimport type { ReadonlyHeaders } from '../../web/spec-extension/adapters/headers'\nimport type { DraftModeProvider } from '../../async-storage/draft-mode-provider'\nimport type { Params } from '../../request/params'\n\nimport { RequestCookies } from '../../web/spec-extension/cookies'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport type { SearchParams } from '../../request/search-params'\nimport { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param'\nimport { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { InstantValidationError } from './instant-validation-error'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\nimport { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils'\nimport type { WorkStore } from '../work-async-storage.external'\n\nexport type InstantValidationSampleTracking = {\n // TODO(instant-validation-build): track which samples config we used and attribute errors\n missingSampleErrors: InstantValidationError[]\n}\n\nexport function createValidationSampleTracking(): InstantValidationSampleTracking {\n return {\n missingSampleErrors: [],\n }\n}\n\nfunction getExpectedSampleTracking(): InstantValidationSampleTracking {\n let validationSampleTracking: InstantValidationSampleTracking | null = null\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'request':\n case 'validation-client':\n // TODO(instant-validation-build): do we need any special handling for caches?\n validationSampleTracking =\n workUnitStore.validationSampleTracking ?? null\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender-client':\n case 'prerender':\n case 'prerender-runtime':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n if (!validationSampleTracking) {\n throw new InvariantError(\n 'Expected to have a workUnitStore that provides validationSampleTracking'\n )\n }\n return validationSampleTracking\n}\n\nexport function trackMissingSampleError(error: InstantValidationError): void {\n const validationSampleTracking = getExpectedSampleTracking()\n validationSampleTracking.missingSampleErrors.push(error)\n}\n\nexport function trackMissingSampleErrorAndThrow(\n error: InstantValidationError\n): never {\n // TODO(instant-validation-build): this should abort the render\n trackMissingSampleError(error)\n throw error\n}\n\n/**\n * Creates ReadonlyRequestCookies from sample cookie data.\n * Accessing a cookie not declared in the sample will throw an error.\n * Cookies with `value: null` are declared (allowed to access) but return no value.\n */\nexport function createCookiesFromSample(\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyRequestCookies {\n const declaredNames = new Set<string>()\n\n const cookies = new RequestCookies(new Headers())\n if (sampleCookies) {\n for (const cookie of sampleCookies) {\n declaredNames.add(cookie.name)\n if (cookie.value !== null) {\n cookies.set(cookie.name, cookie.value)\n }\n }\n }\n\n const sealed = RequestCookiesAdapter.seal(cookies)\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (name) {\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n if (prop === 'get') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (nameOrCookie) {\n let name: string\n if (typeof nameOrCookie === 'string') {\n name = nameOrCookie\n } else if (\n nameOrCookie &&\n typeof nameOrCookie === 'object' &&\n typeof nameOrCookie.name === 'string'\n ) {\n name = nameOrCookie.name\n } else {\n // This is an invalid input. Pass it through to the original method so it can error.\n return originalMethod.call(target, nameOrCookie)\n }\n\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n\n // TODO(instant-validation-build): what should getAll do?\n // Maybe we should only allow it if there's an array (possibly empty?)\n\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\nfunction createMissingCookieSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`cookies\\` array, ` +\n `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`\n )\n}\n\n/**\n * Creates ReadonlyHeaders from sample header data.\n * Accessing a header not declared in the sample will throw an error.\n * Headers with `value: null` are declared (allowed to access) but return null.\n */\nexport function createHeadersFromSample(\n rawSampleHeaders: InstantSample['headers'],\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyHeaders {\n // If we have cookie samples, add a `cookie` header to match.\n // Accessing it will be implicitly allowed by the proxy --\n // if the user defined some cookies, accessing the \"cookie\" header is also fine.\n const sampleHeaders = rawSampleHeaders ? [...rawSampleHeaders] : []\n if (sampleHeaders.find(([name]) => name.toLowerCase() === 'cookie')) {\n throw new InstantValidationError(\n 'Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'\n )\n }\n if (sampleCookies) {\n const cookieHeaderValue = sampleCookies.toString()\n sampleHeaders.push([\n 'cookie',\n // if the `cookies` samples were empty, or they were all `null`, then we have no cookies,\n // and the header isn't present, but should remains readable, so we set it to null.\n cookieHeaderValue !== '' ? cookieHeaderValue : null,\n ])\n }\n\n const declaredNames = new Set<string>()\n const headersInit: Record<string, string> = {}\n\n for (const [name, value] of sampleHeaders) {\n declaredNames.add(name.toLowerCase())\n if (value !== null) {\n headersInit[name.toLowerCase()] = value\n }\n }\n\n const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit))\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'get' || prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const patchedMethod: typeof originalMethod = function (rawName) {\n const name = rawName.toLowerCase()\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`headers\\` array, ` +\n `or \\`[\"${name}\", null]\\` if it should be absent.`\n )\n )\n }\n // typescript can't reconcile a union of functions with a union of return types,\n // so we have to cast the original return type away\n return (originalMethod as (...args: any[]) => any).call(target, name)\n }\n return patchedMethod\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\n/**\n * Creates a DraftModeProvider that always returns isEnabled: false.\n */\nexport function createDraftModeForValidation(): DraftModeProvider {\n // Create a minimal DraftModeProvider-compatible object\n // that always reports draft mode as disabled.\n //\n // private properties that can't be set from outside the class.\n return {\n get isEnabled() {\n return false\n },\n enable() {\n throw new Error(\n 'Draft mode cannot be enabled during build-time instant validation.'\n )\n },\n disable() {\n throw new Error(\n 'Draft mode cannot be disabled during build-time instant validation.'\n )\n },\n } as Partial<DraftModeProvider> as DraftModeProvider\n}\n\n/**\n * Creates params wrapped with an exhaustive proxy.\n * Accessing a param not declared in the sample will throw an error.\n */\nexport function createExhaustiveParamsProxy<TParams extends Params>(\n underlyingParams: TParams,\n declaredParamNames: Set<string>,\n route: string\n): TParams {\n return new Proxy(underlyingParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n // Only error when accessing a param that is part of the route but wasn't provided.\n // accessing properties that aren't expected to be a valid param value is fine.\n prop in underlyingParams &&\n !declaredParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n // We don't need to override `has` or `ownKeys`.\n // the shape of the params object is determined by the routing structure\n // and independent of the samples. We only need to instrument accessing the values.\n })\n}\n\n/**\n * Creates searchParams wrapped with an exhaustive proxy.\n * Accessing a searchParam not declared in the sample will throw an error.\n * A searchParam with `value: undefined` means \"declared but absent\" (allowed to access, returns undefined).\n */\nexport function createExhaustiveSearchParamsProxy(\n searchParams: SearchParams,\n declaredSearchParamNames: Set<string>,\n route: string\n): SearchParams {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n has(target, prop) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.has(target, prop)\n },\n })\n}\n\n/**\n * Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an\n * exhaustive proxy. Accessing a search param not declared in the sample via\n * get/getAll/has will throw an error.\n */\nexport function createExhaustiveURLSearchParamsProxy<T extends URLSearchParams>(\n searchParams: T,\n declaredSearchParamNames: Set<string>,\n route: string\n): T {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n // Intercept method calls that access specific param names\n if (prop === 'get' || prop === 'getAll' || prop === 'has') {\n const originalMathod = Reflect.get(target, prop, receiver)\n return (name: string) => {\n if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, name)\n )\n }\n return (originalMathod as (...args: any[]) => any).call(target, name)\n }\n }\n const value = Reflect.get(target, prop, receiver)\n // Prevent `TypeError: Value of \"this\" must be of type URLSearchParams` for methods\n if (typeof value === 'function' && !Object.hasOwn(target, prop)) {\n return value.bind(target)\n }\n return value\n },\n })\n}\n\nfunction createMissingSearchParamSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`searchParams\\` object, ` +\n `or \\`{ \"${name}\": null }\\` if it should be absent.`\n )\n}\n\nexport function createRelativeURLFromSamples(\n route: string,\n sampleParams: InstantSample['params'],\n sampleSearchParams: InstantSample['searchParams']\n) {\n // Build searchParams query object and URL search string from sample\n const pathname = createPathnameFromRouteAndSampleParams(\n route,\n sampleParams ?? {}\n )\n\n let search = ''\n if (sampleSearchParams) {\n const qs = createURLSearchParamsFromSample(sampleSearchParams).toString()\n if (qs) {\n search = '?' + qs\n }\n }\n\n return parseRelativeUrl(pathname + search, undefined, true)\n}\n\nfunction createURLSearchParamsFromSample(\n sampleSearchParams: InstantSample['searchParams']\n) {\n const result = new URLSearchParams()\n if (sampleSearchParams) {\n for (const [key, value] of Object.entries(sampleSearchParams)) {\n if (value === null || value === undefined) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n result.append(key, v)\n }\n } else {\n result.set(key, value)\n }\n }\n }\n return result\n}\n\n/**\n * Substitute sample params into `workStore.route` to create a plausible pathname.\n * TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,\n * but it should be good enough for some initial testing.\n */\nfunction createPathnameFromRouteAndSampleParams(route: string, params: Params) {\n let interpolatedSegments: string[] = []\n const rawSegments = route.split('/')\n for (const rawSegment of rawSegments) {\n const param = getSegmentParam(rawSegment)\n if (param) {\n switch (param.paramType) {\n case 'catchall':\n case 'optional-catchall': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = [rawSegment]\n } else if (!Array.isArray(paramValue)) {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(\n ...paramValue.map((v) => encodeURIComponent(v))\n )\n break\n }\n case 'dynamic': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = rawSegment\n } else if (typeof paramValue !== 'string') {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(encodeURIComponent(paramValue))\n break\n }\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)': {\n // TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here\n throw new InvariantError(\n 'Not implemented: Validation of interception routes'\n )\n }\n default: {\n param.paramType satisfies never\n }\n }\n } else {\n interpolatedSegments.push(rawSegment)\n }\n }\n return interpolatedSegments.join('/')\n}\n\nexport function assertRootParamInSamples(\n workStore: WorkStore,\n sampleParams: Params | undefined,\n paramName: string\n) {\n if (sampleParams && paramName in sampleParams) {\n // The param is defined in the samples.\n } else {\n const route = workStore.route\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n}\n"],"names":["assertRootParamInSamples","createCookiesFromSample","createDraftModeForValidation","createExhaustiveParamsProxy","createExhaustiveSearchParamsProxy","createExhaustiveURLSearchParamsProxy","createHeadersFromSample","createRelativeURLFromSamples","createValidationSampleTracking","trackMissingSampleError","trackMissingSampleErrorAndThrow","missingSampleErrors","getExpectedSampleTracking","validationSampleTracking","workUnitStore","workUnitAsyncStorage","getStore","type","InvariantError","error","push","sampleCookies","route","declaredNames","Set","cookies","RequestCookies","Headers","cookie","add","name","value","set","sealed","RequestCookiesAdapter","seal","Proxy","get","target","prop","receiver","originalMethod","Reflect","wrappedMethod","has","createMissingCookieSampleError","call","nameOrCookie","InstantValidationError","rawSampleHeaders","sampleHeaders","find","toLowerCase","cookieHeaderValue","toString","headersInit","HeadersAdapter","from","patchedMethod","rawName","isEnabled","enable","Error","disable","underlyingParams","declaredParamNames","wellKnownProperties","searchParams","declaredSearchParamNames","createMissingSearchParamSampleError","originalMathod","Object","hasOwn","bind","sampleParams","sampleSearchParams","pathname","createPathnameFromRouteAndSampleParams","search","qs","createURLSearchParamsFromSample","parseRelativeUrl","undefined","result","URLSearchParams","key","entries","Array","isArray","v","append","params","interpolatedSegments","rawSegments","split","rawSegment","param","getSegmentParam","paramType","paramValue","paramName","map","encodeURIComponent","join","workStore"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;IA+dgBA,wBAAwB;eAAxBA;;IA/YAC,uBAAuB;eAAvBA;;IAoJAC,4BAA4B;eAA5BA;;IA0BAC,2BAA2B;eAA3BA;;IAmCAC,iCAAiC;eAAjCA;;IAsCAC,oCAAoC;eAApCA;;IApKAC,uBAAuB;eAAvBA;;IA4MAC,4BAA4B;eAA5BA;;IAxVAC,8BAA8B;eAA9BA;;IAuCAC,uBAAuB;eAAvBA;;IAKAC,+BAA+B;eAA/BA;;;yBA7De;gCACO;yBACP;iCAEC;kCACC;gCACF;wCACQ;8CACF;8BACD;AAQ7B,SAASF;IACd,OAAO;QACLG,qBAAqB,EAAE;IACzB;AACF;AAEA,SAASC;IACP,IAAIC,2BAAmE;IACvE,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IACnD,IAAIF,eAAe;QACjB,OAAQA,cAAcG,IAAI;YACxB,KAAK;YACL,KAAK;gBACH,8EAA8E;gBAC9EJ,2BACEC,cAAcD,wBAAwB,IAAI;gBAC5C;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEC;QACJ;IACF;IACA,IAAI,CAACD,0BAA0B;QAC7B,MAAM,qBAEL,CAFK,IAAIK,8BAAc,CACtB,4EADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IACA,OAAOL;AACT;A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,eAAe,UAAU;4BACzC,2FAA2F;4BAC3F,MAAM,qBAEL,CAFK,IAAInD,8CAAsB,CAC9B,CAAC,yCAAyC,EAAE+C,WAAW,sBAAsB,EAAE,OAAOI,YAAY,GAD9F,qBAAA;uCAAA;4CAAA;8CAAA;4BAEN;wBACF;wBACAP,qBAAqBxE,IAAI,CAACkF,mBAAmBH;wBAC7C;oBACF;gBACA,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBAA6B;wBAChC,+GAA+G;wBAC/G,MAAM,qBAEL,CAFK,IAAIjF,8BAAc,CACtB,uDADI,qBAAA;mCAAA;wCAAA;0CAAA;wBAEN;oBACF;gBACA;oBAAS;wBACP8E,MAAME,SAAS;oBACjB;YACF;QACF,OAAO;YACLN,qBAAqBxE,IAAI,CAAC2E;QAC5B;IACF;IACA,OAAOH,qBAAqBW,IAAI,CAAC;AACnC;AAEO,SAASvG,yBACdwG,SAAoB,EACpB9B,YAAgC,EAChC0B,SAAiB;IAEjB,IAAI1B,gBAAgB0B,aAAa1B,cAAc;IAC7C,uCAAuC;IACzC,OAAO;QACL,MAAMpD,QAAQkF,UAAUlF,KAAK;QAC7BZ,gCACE,qBAGC,CAHD,IAAIsC,8CAAsB,CACxB,CAAC,OAAO,EAAE1B,MAAM,uBAAuB,EAAE8E,UAAU,mDAAmD,CAAC,GACrG,CAAC,yDAAyD,CAAC,GAF/D,qBAAA;mBAAA;wBAAA;0BAAA;QAGA;IAEJ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/app-render/instant-validation/instant-samples.ts"],"sourcesContent":["import type { InstantSample } from '../../../build/segment-config/app/app-segment-config'\nimport type { ReadonlyRequestCookies } from '../../web/spec-extension/adapters/request-cookies'\nimport type { ReadonlyHeaders } from '../../web/spec-extension/adapters/headers'\nimport type { DraftModeProvider } from '../../async-storage/draft-mode-provider'\nimport type { Params } from '../../request/params'\n\nimport { RequestCookies } from '../../web/spec-extension/cookies'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport type { SearchParams } from '../../request/search-params'\nimport { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param'\nimport { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { InstantValidationError } from './instant-validation-error'\nimport { workUnitAsyncStorage } from '../work-unit-async-storage.external'\nimport { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils'\nimport type { WorkStore } from '../work-async-storage.external'\n\nexport type InstantValidationSampleTracking = {\n // TODO(instant-validation-build): track which samples config we used and attribute errors\n missingSampleErrors: InstantValidationError[]\n}\n\nexport function createValidationSampleTracking(): InstantValidationSampleTracking {\n return {\n missingSampleErrors: [],\n }\n}\n\nfunction getExpectedSampleTracking(): InstantValidationSampleTracking {\n let validationSampleTracking: InstantValidationSampleTracking | null = null\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'request':\n case 'validation-client':\n // TODO(instant-validation-build): do we need any special handling for caches?\n validationSampleTracking =\n workUnitStore.validationSampleTracking ?? null\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'prerender-client':\n case 'prerender':\n case 'prerender-runtime':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n if (!validationSampleTracking) {\n throw new InvariantError(\n 'Expected to have a workUnitStore that provides validationSampleTracking'\n )\n }\n return validationSampleTracking\n}\n\nexport function trackMissingSampleError(error: InstantValidationError): void {\n const validationSampleTracking = getExpectedSampleTracking()\n validationSampleTracking.missingSampleErrors.push(error)\n}\n\nexport function trackMissingSampleErrorAndThrow(\n error: InstantValidationError\n): never {\n // TODO(instant-validation-build): this should abort the render\n trackMissingSampleError(error)\n throw error\n}\n\n/**\n * Creates ReadonlyRequestCookies from sample cookie data.\n * Accessing a cookie not declared in the sample will throw an error.\n * Cookies with `value: null` are declared (allowed to access) but return no value.\n */\nexport function createCookiesFromSample(\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyRequestCookies {\n const declaredNames = new Set<string>()\n\n const cookies = new RequestCookies(new Headers())\n if (sampleCookies) {\n for (const cookie of sampleCookies) {\n declaredNames.add(cookie.name)\n if (cookie.value !== null) {\n cookies.set(cookie.name, cookie.value)\n }\n }\n }\n\n const sealed = RequestCookiesAdapter.seal(cookies)\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (name) {\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n if (prop === 'get') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const wrappedMethod: typeof originalMethod = function (nameOrCookie) {\n let name: string\n if (typeof nameOrCookie === 'string') {\n name = nameOrCookie\n } else if (\n nameOrCookie &&\n typeof nameOrCookie === 'object' &&\n typeof nameOrCookie.name === 'string'\n ) {\n name = nameOrCookie.name\n } else {\n // This is an invalid input. Pass it through to the original method so it can error.\n return originalMethod.call(target, nameOrCookie)\n }\n\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingCookieSampleError(route, name)\n )\n }\n return originalMethod.call(target, name)\n }\n return wrappedMethod\n }\n\n // TODO(instant-validation-build): what should getAll do?\n // Maybe we should only allow it if there's an array (possibly empty?)\n\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\nfunction createMissingCookieSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`cookies\\` array, ` +\n `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`\n )\n}\n\n/**\n * Creates ReadonlyHeaders from sample header data.\n * Accessing a header not declared in the sample will throw an error.\n * Headers with `value: null` are declared (allowed to access) but return null.\n */\nexport function createHeadersFromSample(\n rawSampleHeaders: InstantSample['headers'],\n sampleCookies: InstantSample['cookies'],\n route: string\n): ReadonlyHeaders {\n // If we have cookie samples, add a `cookie` header to match.\n // Accessing it will be implicitly allowed by the proxy --\n // if the user defined some cookies, accessing the \"cookie\" header is also fine.\n const sampleHeaders = rawSampleHeaders ? [...rawSampleHeaders] : []\n if (sampleHeaders.find(([name]) => name.toLowerCase() === 'cookie')) {\n throw new InstantValidationError(\n 'Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'\n )\n }\n if (sampleCookies) {\n const cookieHeaderValue = sampleCookies.toString()\n sampleHeaders.push([\n 'cookie',\n // if the `cookies` samples were empty, or they were all `null`, then we have no cookies,\n // and the header isn't present, but should remains readable, so we set it to null.\n cookieHeaderValue !== '' ? cookieHeaderValue : null,\n ])\n }\n\n const declaredNames = new Set<string>()\n const headersInit: Record<string, string> = {}\n\n for (const [name, value] of sampleHeaders) {\n declaredNames.add(name.toLowerCase())\n if (value !== null) {\n headersInit[name.toLowerCase()] = value\n }\n }\n\n const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit))\n\n return new Proxy(sealed, {\n get(target, prop, receiver) {\n if (prop === 'get' || prop === 'has') {\n const originalMethod = Reflect.get(target, prop, receiver)\n const patchedMethod: typeof originalMethod = function (rawName) {\n const name = rawName.toLowerCase()\n if (!declaredNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`headers\\` array, ` +\n `or \\`[\"${name}\", null]\\` if it should be absent.`\n )\n )\n }\n // typescript can't reconcile a union of functions with a union of return types,\n // so we have to cast the original return type away\n return (originalMethod as (...args: any[]) => any).call(target, name)\n }\n return patchedMethod\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n}\n\n/**\n * Creates a DraftModeProvider that always returns isEnabled: false.\n */\nexport function createDraftModeForValidation(): DraftModeProvider {\n // Create a minimal DraftModeProvider-compatible object\n // that always reports draft mode as disabled.\n //\n // private properties that can't be set from outside the class.\n return {\n get isEnabled() {\n return false\n },\n enable() {\n throw new Error(\n 'Draft mode cannot be enabled during build-time instant validation.'\n )\n },\n disable() {\n throw new Error(\n 'Draft mode cannot be disabled during build-time instant validation.'\n )\n },\n } as Partial<DraftModeProvider> as DraftModeProvider\n}\n\n/**\n * Creates params wrapped with an exhaustive proxy.\n * Accessing a param not declared in the sample will throw an error.\n */\nexport function createExhaustiveParamsProxy<TParams extends Params>(\n underlyingParams: TParams,\n declaredParamNames: Set<string>,\n route: string\n): TParams {\n return new Proxy(underlyingParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n // Only error when accessing a param that is part of the route but wasn't provided.\n // accessing properties that aren't expected to be a valid param value is fine.\n prop in underlyingParams &&\n !declaredParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n // We don't need to override `has` or `ownKeys`.\n // the shape of the params object is determined by the routing structure\n // and independent of the samples. We only need to instrument accessing the values.\n })\n}\n\n/**\n * Creates searchParams wrapped with an exhaustive proxy.\n * Accessing a searchParam not declared in the sample will throw an error.\n * A searchParam with `value: undefined` means \"declared but absent\" (allowed to access, returns undefined).\n */\nexport function createExhaustiveSearchParamsProxy(\n searchParams: SearchParams,\n declaredSearchParamNames: Set<string>,\n route: string\n): SearchParams {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.get(target, prop, receiver)\n },\n has(target, prop) {\n if (\n typeof prop === 'string' &&\n !wellKnownProperties.has(prop) &&\n !declaredSearchParamNames.has(prop)\n ) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, prop)\n )\n }\n return Reflect.has(target, prop)\n },\n })\n}\n\n/**\n * Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an\n * exhaustive proxy. Accessing a search param not declared in the sample via\n * get/getAll/has will throw an error.\n */\nexport function createExhaustiveURLSearchParamsProxy<T extends URLSearchParams>(\n searchParams: T,\n declaredSearchParamNames: Set<string>,\n route: string\n): T {\n return new Proxy(searchParams, {\n get(target, prop, receiver) {\n // Intercept method calls that access specific param names\n if (prop === 'get' || prop === 'getAll' || prop === 'has') {\n const originalMathod = Reflect.get(target, prop, receiver)\n return (name: string) => {\n if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {\n trackMissingSampleErrorAndThrow(\n createMissingSearchParamSampleError(route, name)\n )\n }\n return (originalMathod as (...args: any[]) => any).call(target, name)\n }\n }\n const value = Reflect.get(target, prop, receiver)\n // Prevent `TypeError: Value of \"this\" must be of type URLSearchParams` for methods\n if (typeof value === 'function' && !Object.hasOwn(target, prop)) {\n return value.bind(target)\n }\n return value\n },\n })\n}\n\nfunction createMissingSearchParamSampleError(\n route: string,\n name: string\n): InstantValidationError {\n return new InstantValidationError(\n `Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`searchParams\\` object, ` +\n `or \\`{ \"${name}\": null }\\` if it should be absent.`\n )\n}\n\nexport function createRelativeURLFromSamples(\n route: string,\n sampleParams: InstantSample['params'],\n sampleSearchParams: InstantSample['searchParams']\n) {\n // Build searchParams query object and URL search string from sample\n const pathname = createPathnameFromRouteAndSampleParams(\n route,\n sampleParams ?? {}\n )\n\n let search = ''\n if (sampleSearchParams) {\n const qs = createURLSearchParamsFromSample(sampleSearchParams).toString()\n if (qs) {\n search = '?' + qs\n }\n }\n\n return parseRelativeUrl(pathname + search, undefined, true)\n}\n\nfunction createURLSearchParamsFromSample(\n sampleSearchParams: InstantSample['searchParams']\n) {\n const result = new URLSearchParams()\n if (sampleSearchParams) {\n for (const [key, value] of Object.entries(sampleSearchParams)) {\n if (value === null || value === undefined) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n result.append(key, v)\n }\n } else {\n result.set(key, value)\n }\n }\n }\n return result\n}\n\n/**\n * Substitute sample params into `workStore.route` to create a plausible pathname.\n * TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,\n * but it should be good enough for some initial testing.\n */\nfunction createPathnameFromRouteAndSampleParams(route: string, params: Params) {\n let interpolatedSegments: string[] = []\n const rawSegments = route.split('/')\n for (const rawSegment of rawSegments) {\n const param = getSegmentParam(rawSegment)\n if (param) {\n switch (param.paramType) {\n case 'catchall':\n case 'optional-catchall': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = [rawSegment]\n } else if (!Array.isArray(paramValue)) {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(\n ...paramValue.map((v) => encodeURIComponent(v))\n )\n break\n }\n case 'dynamic': {\n let paramValue = params[param.paramName]\n if (paramValue === undefined) {\n // The value for the param was not provided. `usePathname` will detect this and throw\n // before this can surface to userspace. Use `[NAME]` as a placeholder for the param value\n // in case it pops up somewhere unexpectedly.\n paramValue = rawSegment\n } else if (typeof paramValue !== 'string') {\n // NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`\n throw new InstantValidationError(\n `Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`\n )\n }\n interpolatedSegments.push(encodeURIComponent(paramValue))\n break\n }\n case 'catchall-intercepted-(..)(..)':\n case 'catchall-intercepted-(.)':\n case 'catchall-intercepted-(..)':\n case 'catchall-intercepted-(...)':\n case 'dynamic-intercepted-(..)(..)':\n case 'dynamic-intercepted-(.)':\n case 'dynamic-intercepted-(..)':\n case 'dynamic-intercepted-(...)': {\n // TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here\n throw new InvariantError(\n 'Not implemented: Validation of interception routes'\n )\n }\n default: {\n param.paramType satisfies never\n }\n }\n } else {\n interpolatedSegments.push(rawSegment)\n }\n }\n return interpolatedSegments.join('/')\n}\n\nexport function assertRootParamInSamples(\n workStore: WorkStore,\n sampleParams: Params | undefined,\n paramName: string\n) {\n if (sampleParams && paramName in sampleParams) {\n // The param is defined in the samples.\n } else {\n const route = workStore.route\n trackMissingSampleErrorAndThrow(\n new InstantValidationError(\n `Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`unstable_samples\\` ` +\n `of \\`instant\\`. Add it to the sample's \\`params\\` object.`\n )\n )\n }\n}\n"],"names":["assertRootParamInSamples","createCookiesFromSample","createDraftModeForValidation","createExhaustiveParamsProxy","createExhaustiveSearchParamsProxy","createExhaustiveURLSearchParamsProxy","createHeadersFromSample","createRelativeURLFromSamples","createValidationSampleTracking","trackMissingSampleError","trackMissingSampleErrorAndThrow","missingSampleErrors","getExpectedSampleTracking","validationSampleTracking","workUnitStore","workUnitAsyncStorage","getStore","type","InvariantError","error","push","sampleCookies","route","declaredNames","Set","cookies","RequestCookies","Headers","cookie","add","name","value","set","sealed","RequestCookiesAdapter","seal","Proxy","get","target","prop","receiver","originalMethod","Reflect","wrappedMethod","has","createMissingCookieSampleError","call","nameOrCookie","InstantValidationError","rawSampleHeaders","sampleHeaders","find","toLowerCase","cookieHeaderValue","toString","headersInit","HeadersAdapter","from","patchedMethod","rawName","isEnabled","enable","Error","disable","underlyingParams","declaredParamNames","wellKnownProperties","searchParams","declaredSearchParamNames","createMissingSearchParamSampleError","originalMathod","Object","hasOwn","bind","sampleParams","sampleSearchParams","pathname","createPathnameFromRouteAndSampleParams","search","qs","createURLSearchParamsFromSample","parseRelativeUrl","undefined","result","URLSearchParams","key","entries","Array","isArray","v","append","params","interpolatedSegments","rawSegments","split","rawSegment","param","getSegmentParam","paramType","paramValue","paramName","map","encodeURIComponent","join","workStore"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;IA8dgBA,wBAAwB;eAAxBA;;IA/YAC,uBAAuB;eAAvBA;;IAoJAC,4BAA4B;eAA5BA;;IA0BAC,2BAA2B;eAA3BA;;IAmCAC,iCAAiC;eAAjCA;;IAsCAC,oCAAoC;eAApCA;;IApKAC,uBAAuB;eAAvBA;;IA4MAC,4BAA4B;eAA5BA;;IAvVAC,8BAA8B;eAA9BA;;IAsCAC,uBAAuB;eAAvBA;;IAKAC,+BAA+B;eAA/BA;;;yBA5De;gCACO;yBACP;iCAEC;kCACC;gCACF;wCACQ;8CACF;8BACD;AAQ7B,SAASF;IACd,OAAO;QACLG,qBAAqB,EAAE;IACzB;AACF;AAEA,SAASC;IACP,IAAIC,2BAAmE;IACvE,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IACnD,IAAIF,eAAe;QACjB,OAAQA,cAAcG,IAAI;YACxB,KAAK;YACL,KAAK;gBACH,8EAA8E;gBAC9EJ,2BACEC,cAAcD,wBAAwB,IAAI;gBAC5C;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEC;QACJ;IACF;IACA,IAAI,CAACD,0BAA0B;QAC7B,MAAM,qBAEL,CAFK,IAAIK,8BAAc,CACtB,4EADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IACA,OAAOL;AACT;AAEO,SAASJ,wBAAwBU,K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AA2F;4BAC3F,MAAM,qBAEL,CAFK,IAAInD,8CAAsB,CAC9B,CAAC,yCAAyC,EAAE+C,WAAW,sBAAsB,EAAE,OAAOI,YAAY,GAD9F,qBAAA;uCAAA;4CAAA;8CAAA;4BAEN;wBACF;wBACAP,qBAAqBxE,IAAI,CAACkF,mBAAmBH;wBAC7C;oBACF;gBACA,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBAA6B;wBAChC,+GAA+G;wBAC/G,MAAM,qBAEL,CAFK,IAAIjF,8BAAc,CACtB,uDADI,qBAAA;mCAAA;wCAAA;0CAAA;wBAEN;oBACF;gBACA;oBAAS;wBACP8E,MAAME,SAAS;oBACjB;YACF;QACF,OAAO;YACLN,qBAAqBxE,IAAI,CAAC2E;QAC5B;IACF;IACA,OAAOH,qBAAqBW,IAAI,CAAC;AACnC;AAEO,SAASvG,yBACdwG,SAAoB,EACpB9B,YAAgC,EAChC0B,SAAiB;IAEjB,IAAI1B,gBAAgB0B,aAAa1B,cAAc;IAC7C,uCAAuC;IACzC,OAAO;QACL,MAAMpD,QAAQkF,UAAUlF,KAAK;QAC7BZ,gCACE,qBAGC,CAHD,IAAIsC,8CAAsB,CACxB,CAAC,OAAO,EAAE1B,MAAM,uBAAuB,EAAE8E,UAAU,mDAAmD,CAAC,GACrG,CAAC,yDAAyD,CAAC,GAF/D,qBAAA;mBAAA;wBAAA;0BAAA;QAGA;IAEJ;AACF","ignoreList":[0]}

@@ -125,3 +125,2 @@ "use strict";

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -128,0 +127,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/app-render/use-flight-response.tsx"],"sourcesContent":["import type { BinaryStreamOf } from './app-render'\nimport type { Readable } from 'node:stream'\n\nimport {\n htmlEscapeAttributeString,\n htmlEscapeJsonString,\n} from '../../shared/lib/htmlescape'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { getClientReferenceManifest } from './manifests-singleton'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0\nconst INLINE_FLIGHT_PAYLOAD_DATA = 1\nconst INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2\nconst INLINE_FLIGHT_PAYLOAD_BINARY = 3\n\nconst flightResponses = new WeakMap<\n Readable | BinaryStreamOf<any>,\n Promise<any>\n>()\nconst encoder = new TextEncoder()\n\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Render Flight stream.\n * This is only used for renderToHTML, the Flight response does not need additional wrappers.\n */\nexport function getFlightStream<T>(\n flightStream: Readable | BinaryStreamOf<T>,\n debugStream: Readable | ReadableStream<Uint8Array> | undefined,\n debugEndTime: number | undefined,\n nonce: string | undefined\n): Promise<T> {\n const response = flightResponses.get(flightStream)\n\n if (response) {\n return response\n }\n\n const { moduleLoading, edgeSSRModuleMapping, ssrModuleMapping } =\n getClientReferenceManifest()\n\n let newResponse: Promise<T>\n if (flightStream instanceof ReadableStream) {\n // The types of flightStream and debugStream should match.\n if (debugStream && !(debugStream instanceof ReadableStream)) {\n throw new InvariantError('Expected debug stream to be a ReadableStream')\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromReadableStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromReadableStream<T>(flightStream, {\n findSourceMapURL,\n serverConsumerManifest: {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n nonce,\n debugChannel: debugStream ? { readable: debugStream } : undefined,\n endTime: debugEndTime,\n })\n } else {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'getFlightStream should always receive a ReadableStream when using the edge runtime'\n )\n } else {\n const { Readable } =\n require('node:stream') as typeof import('node:stream')\n\n // Convert debug stream to Readable if it's a ReadableStream.\n // When __NEXT_USE_NODE_STREAMS is enabled, the debug channel produces\n // Node Readables natively. Otherwise, it produces web ReadableStreams.\n let nodeDebugStream: Readable | undefined\n if (debugStream) {\n if (debugStream instanceof Readable) {\n nodeDebugStream = debugStream\n } else {\n type WebReadableStream = import('stream/web').ReadableStream\n nodeDebugStream = Readable.fromWeb(debugStream as WebReadableStream)\n }\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromNodeStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromNodeStream<T>(\n flightStream,\n {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n {\n findSourceMapURL,\n nonce,\n debugChannel: nodeDebugStream,\n endTime: debugEndTime,\n }\n )\n }\n }\n\n // Edge pages are never prerendered so they necessarily cannot have a workUnitStore type\n // that requires the nextTick behavior. This is why it is safe to access a node only API here\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workUnitStore) {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n }\n\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'validation-client':\n const responseOnNextTick = new Promise<T>((resolve) => {\n process.nextTick(() => {\n resolve(newResponse)\n })\n })\n flightResponses.set(flightStream, responseOnNextTick)\n return responseOnNextTick\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n flightResponses.set(flightStream, newResponse)\n\n return newResponse\n}\n\n/**\n * Creates a ReadableStream provides inline script tag chunks for writing hydration\n * data to the client outside the React render itself.\n *\n * @param flightStream The RSC render stream\n * @param nonce optionally a nonce used during this particular render\n * @param formState optionally the formState used with this particular render\n * @returns a ReadableStream without the complete property. This signifies a lazy ReadableStream\n */\nexport function createInlinedDataReadableStream(\n flightStream: ReadableStream<Uint8Array>,\n nonce: string | undefined,\n formState: unknown | null\n): ReadableStream<Uint8Array> {\n const startScriptTag = nonce\n ? `<script nonce=\"${htmlEscapeAttributeString(nonce)}\">`\n : '<script>'\n\n const flightReader = flightStream.getReader()\n const decoder = new TextDecoder('utf-8', { fatal: true })\n\n const readable = new ReadableStream({\n type: 'bytes',\n start(controller) {\n try {\n writeInitialInstructions(controller, startScriptTag, formState)\n } catch (error) {\n // during encoding or enqueueing forward the error downstream\n controller.error(error)\n }\n },\n async pull(controller) {\n try {\n const { done, value } = await flightReader.read()\n\n if (value) {\n try {\n const decodedString = decoder.decode(value, { stream: !done })\n\n // The chunk cannot be decoded as valid UTF-8 string as it might\n // have arbitrary binary data.\n writeFlightDataInstruction(\n controller,\n startScriptTag,\n decodedString\n )\n } catch {\n // The chunk cannot be decoded as valid UTF-8 string.\n writeFlightDataInstruction(controller, startScriptTag, value)\n }\n }\n\n if (done) {\n controller.close()\n }\n } catch (error) {\n // There was a problem in the upstream reader or during decoding or enqueuing\n // forward the error downstream\n controller.error(error)\n }\n },\n })\n\n return readable\n}\n\nfunction writeInitialInstructions(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n formState: unknown | null\n) {\n let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])\n )})`\n\n if (formState != null) {\n scriptContents += `;self.__next_f.push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])\n )})`\n }\n\n controller.enqueue(encoder.encode(`${scriptStart}${scriptContents}</script>`))\n}\n\nfunction writeFlightDataInstruction(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n chunk: string | Uint8Array\n) {\n let htmlInlinedData: string\n\n if (typeof chunk === 'string') {\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, chunk])\n )\n } else {\n // The chunk cannot be embedded as a UTF-8 string in the script tag.\n // Instead let's inline it in base64.\n // Credits to Devon Govett (devongovett) for the technique.\n // https://github.com/devongovett/rsc-html-stream\n const base64 =\n typeof Buffer !== 'undefined'\n ? Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n ).toString('base64')\n : btoa(String.fromCodePoint(...chunk))\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64])\n )\n }\n\n controller.enqueue(\n encoder.encode(\n `${scriptStart}self.__next_f.push(${htmlInlinedData})</script>`\n )\n )\n}\n"],"names":["createInlinedDataReadableStream","getFlightStream","isEdgeRuntime","process","env","NEXT_RUNTIME","INLINE_FLIGHT_PAYLOAD_BOOTSTRAP","INLINE_FLIGHT_PAYLOAD_DATA","INLINE_FLIGHT_PAYLOAD_FORM_STATE","INLINE_FLIGHT_PAYLOAD_BINARY","flightResponses","WeakMap","encoder","TextEncoder","findSourceMapURL","NODE_ENV","require","findSourceMapURLDEV","undefined","flightStream","debugStream","debugEndTime","nonce","response","get","moduleLoading","edgeSSRModuleMapping","ssrModuleMapping","getClientReferenceManifest","newResponse","ReadableStream","InvariantError","createFromReadableStream","serverConsumerManifest","moduleMap","serverModuleMap","debugChannel","readable","endTime","Readable","nodeDebugStream","fromWeb","createFromNodeStream","workUnitStore","workUnitAsyncStorage","getStore","type","responseOnNextTick","Promise","resolve","nextTick","set","formState","startScriptTag","htmlEscapeAttributeString","flightReader","getReader","decoder","TextDecoder","fatal","start","controller","writeInitialInstructions","error","pull","done","value","read","decodedString","decode","stream","writeFlightDataInstruction","close","scriptStart","scriptContents","htmlEscapeJsonString","JSON","stringify","enqueue","encode","chunk","htmlInlinedData","base64","Buffer","from","buffer","byteOffset","byteLength","toString","btoa","String","fromCodePoint"],"mappings":";;;;;;;;;;;;;;;IAoKgBA,+BAA+B;eAA/BA;;IAlIAC,eAAe;eAAfA;;;4BA5BT;8CAC8B;gCACN;oCACY;AAE3C,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD,MAAMC,kCAAkC;AACxC,MAAMC,6BAA6B;AACnC,MAAMC,mCAAmC;AACzC,MAAMC,+BAA+B;AAErC,MAAMC,kBAAkB,IAAIC;AAI5B,MAAMC,UAAU,IAAIC;AAEpB,MAAMC,mBACJX,QAAQC,GAAG,CAACW,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AAMC,SAASjB,gBACdkB,YAA0C,EAC1CC,WAA8D,EAC9DC,YAAgC,EAChCC,KAAyB;IAEzB,MAAMC,WAAWb,gBAAgBc,GAAG,CAACL;IAErC,IAAII,UAAU;QACZ,OAAOA;IACT;IAEA,MAAM,EAAEE,aAAa,EAAEC,oBAAoB,EAAEC,gBAAgB,EAAE,GAC7DC,IAAAA,8CAA0B;IAE5B,IAAIC;IACJ,IAAIV,wBAAwBW,gBAAgB;QAC1C,0DAA0D;QAC1D,IAAIV,eAAe,CAAEA,CAAAA,uBAAuBU,cAAa,GAAI;YAC3D,MAAM,qBAAkE,CAAlE,IAAIC,8BAAc,CAAC,iDAAnB,qBAAA;uBAAA;4BAAA;8BAAA;YAAiE;QACzE;QAEA,wGAAwG;QACxG,MAAM,EAAEC,wBAAwB,EAAE,GAChC,6DAA6D;QAC7DhB,QAAQ;QAEVa,cAAcG,yBAA4Bb,cAAc;YACtDL;YACAmB,wBAAwB;gBACtBR;gBACAS,WAAWhC,gBAAgBwB,uBAAuBC;gBAClDQ,iBAAiB;YACnB;YACAb;YACAc,cAAchB,cAAc;gBAAEi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gC,GAChD,CAAC,CAAC;IAEJ,IAAI8C,aAAa,MAAM;QACrBsB,kBAAkB,CAAC,oBAAoB,EAAEC,IAAAA,gCAAoB,EAC3DC,KAAKC,SAAS,CAAC;YAACrE;YAAkC4C;SAAU,GAC5D,CAAC,CAAC;IACN;IAEAS,WAAWiB,OAAO,CAAClE,QAAQmE,MAAM,CAAC,GAAGN,cAAcC,eAAe,SAAS,CAAC;AAC9E;AAEA,SAASH,2BACPV,UAA2C,EAC3CY,WAAmB,EACnBO,KAA0B;IAE1B,IAAIC;IAEJ,IAAI,OAAOD,UAAU,UAAU;QAC7BC,kBAAkBN,IAAAA,gCAAoB,EACpCC,KAAKC,SAAS,CAAC;YAACtE;YAA4ByE;SAAM;IAEtD,OAAO;QACL,oEAAoE;QACpE,qCAAqC;QACrC,2DAA2D;QAC3D,iDAAiD;QACjD,MAAME,SACJ,OAAOC,WAAW,cACdA,OAAOC,IAAI,CACTJ,MAAMK,MAAM,EACZL,MAAMM,UAAU,EAChBN,MAAMO,UAAU,EAChBC,QAAQ,CAAC,YACXC,KAAKC,OAAOC,aAAa,IAAIX;QACnCC,kBAAkBN,IAAAA,gCAAoB,EACpCC,KAAKC,SAAS,CAAC;YAACpE;YAA8ByE;SAAO;IAEzD;IAEArB,WAAWiB,OAAO,CAChBlE,QAAQmE,MAAM,CACZ,GAAGN,YAAY,mBAAmB,EAAEQ,gBAAgB,UAAU,CAAC;AAGrE","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/app-render/use-flight-response.tsx"],"sourcesContent":["import type { BinaryStreamOf } from './app-render'\nimport type { Readable } from 'node:stream'\n\nimport {\n htmlEscapeAttributeString,\n htmlEscapeJsonString,\n} from '../../shared/lib/htmlescape'\nimport { workUnitAsyncStorage } from './work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { getClientReferenceManifest } from './manifests-singleton'\n\nconst isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'\n\nconst INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0\nconst INLINE_FLIGHT_PAYLOAD_DATA = 1\nconst INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2\nconst INLINE_FLIGHT_PAYLOAD_BINARY = 3\n\nconst flightResponses = new WeakMap<\n Readable | BinaryStreamOf<any>,\n Promise<any>\n>()\nconst encoder = new TextEncoder()\n\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n/**\n * Render Flight stream.\n * This is only used for renderToHTML, the Flight response does not need additional wrappers.\n */\nexport function getFlightStream<T>(\n flightStream: Readable | BinaryStreamOf<T>,\n debugStream: Readable | ReadableStream<Uint8Array> | undefined,\n debugEndTime: number | undefined,\n nonce: string | undefined\n): Promise<T> {\n const response = flightResponses.get(flightStream)\n\n if (response) {\n return response\n }\n\n const { moduleLoading, edgeSSRModuleMapping, ssrModuleMapping } =\n getClientReferenceManifest()\n\n let newResponse: Promise<T>\n if (flightStream instanceof ReadableStream) {\n // The types of flightStream and debugStream should match.\n if (debugStream && !(debugStream instanceof ReadableStream)) {\n throw new InvariantError('Expected debug stream to be a ReadableStream')\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromReadableStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromReadableStream<T>(flightStream, {\n findSourceMapURL,\n serverConsumerManifest: {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n nonce,\n debugChannel: debugStream ? { readable: debugStream } : undefined,\n endTime: debugEndTime,\n })\n } else {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'getFlightStream should always receive a ReadableStream when using the edge runtime'\n )\n } else {\n const { Readable } =\n require('node:stream') as typeof import('node:stream')\n\n // Convert debug stream to Readable if it's a ReadableStream.\n // When __NEXT_USE_NODE_STREAMS is enabled, the debug channel produces\n // Node Readables natively. Otherwise, it produces web ReadableStreams.\n let nodeDebugStream: Readable | undefined\n if (debugStream) {\n if (debugStream instanceof Readable) {\n nodeDebugStream = debugStream\n } else {\n type WebReadableStream = import('stream/web').ReadableStream\n nodeDebugStream = Readable.fromWeb(debugStream as WebReadableStream)\n }\n }\n\n // react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly\n const { createFromNodeStream } =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n\n newResponse = createFromNodeStream<T>(\n flightStream,\n {\n moduleLoading,\n moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,\n serverModuleMap: null,\n },\n {\n findSourceMapURL,\n nonce,\n debugChannel: nodeDebugStream,\n endTime: debugEndTime,\n }\n )\n }\n }\n\n // Edge pages are never prerendered so they necessarily cannot have a workUnitStore type\n // that requires the nextTick behavior. This is why it is safe to access a node only API here\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workUnitStore) {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n }\n\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'validation-client':\n const responseOnNextTick = new Promise<T>((resolve) => {\n process.nextTick(() => {\n resolve(newResponse)\n })\n })\n flightResponses.set(flightStream, responseOnNextTick)\n return responseOnNextTick\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n flightResponses.set(flightStream, newResponse)\n\n return newResponse\n}\n\n/**\n * Creates a ReadableStream provides inline script tag chunks for writing hydration\n * data to the client outside the React render itself.\n *\n * @param flightStream The RSC render stream\n * @param nonce optionally a nonce used during this particular render\n * @param formState optionally the formState used with this particular render\n * @returns a ReadableStream without the complete property. This signifies a lazy ReadableStream\n */\nexport function createInlinedDataReadableStream(\n flightStream: ReadableStream<Uint8Array>,\n nonce: string | undefined,\n formState: unknown | null\n): ReadableStream<Uint8Array> {\n const startScriptTag = nonce\n ? `<script nonce=\"${htmlEscapeAttributeString(nonce)}\">`\n : '<script>'\n\n const flightReader = flightStream.getReader()\n const decoder = new TextDecoder('utf-8', { fatal: true })\n\n const readable = new ReadableStream({\n type: 'bytes',\n start(controller) {\n try {\n writeInitialInstructions(controller, startScriptTag, formState)\n } catch (error) {\n // during encoding or enqueueing forward the error downstream\n controller.error(error)\n }\n },\n async pull(controller) {\n try {\n const { done, value } = await flightReader.read()\n\n if (value) {\n try {\n const decodedString = decoder.decode(value, { stream: !done })\n\n // The chunk cannot be decoded as valid UTF-8 string as it might\n // have arbitrary binary data.\n writeFlightDataInstruction(\n controller,\n startScriptTag,\n decodedString\n )\n } catch {\n // The chunk cannot be decoded as valid UTF-8 string.\n writeFlightDataInstruction(controller, startScriptTag, value)\n }\n }\n\n if (done) {\n controller.close()\n }\n } catch (error) {\n // There was a problem in the upstream reader or during decoding or enqueuing\n // forward the error downstream\n controller.error(error)\n }\n },\n })\n\n return readable\n}\n\nfunction writeInitialInstructions(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n formState: unknown | null\n) {\n let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])\n )})`\n\n if (formState != null) {\n scriptContents += `;self.__next_f.push(${htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])\n )})`\n }\n\n controller.enqueue(encoder.encode(`${scriptStart}${scriptContents}</script>`))\n}\n\nfunction writeFlightDataInstruction(\n controller: ReadableStreamDefaultController,\n scriptStart: string,\n chunk: string | Uint8Array\n) {\n let htmlInlinedData: string\n\n if (typeof chunk === 'string') {\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, chunk])\n )\n } else {\n // The chunk cannot be embedded as a UTF-8 string in the script tag.\n // Instead let's inline it in base64.\n // Credits to Devon Govett (devongovett) for the technique.\n // https://github.com/devongovett/rsc-html-stream\n const base64 =\n typeof Buffer !== 'undefined'\n ? Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n ).toString('base64')\n : btoa(String.fromCodePoint(...chunk))\n htmlInlinedData = htmlEscapeJsonString(\n JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64])\n )\n }\n\n controller.enqueue(\n encoder.encode(\n `${scriptStart}self.__next_f.push(${htmlInlinedData})</script>`\n )\n )\n}\n"],"names":["createInlinedDataReadableStream","getFlightStream","isEdgeRuntime","process","env","NEXT_RUNTIME","INLINE_FLIGHT_PAYLOAD_BOOTSTRAP","INLINE_FLIGHT_PAYLOAD_DATA","INLINE_FLIGHT_PAYLOAD_FORM_STATE","INLINE_FLIGHT_PAYLOAD_BINARY","flightResponses","WeakMap","encoder","TextEncoder","findSourceMapURL","NODE_ENV","require","findSourceMapURLDEV","undefined","flightStream","debugStream","debugEndTime","nonce","response","get","moduleLoading","edgeSSRModuleMapping","ssrModuleMapping","getClientReferenceManifest","newResponse","ReadableStream","InvariantError","createFromReadableStream","serverConsumerManifest","moduleMap","serverModuleMap","debugChannel","readable","endTime","Readable","nodeDebugStream","fromWeb","createFromNodeStream","workUnitStore","workUnitAsyncStorage","getStore","type","responseOnNextTick","Promise","resolve","nextTick","set","formState","startScriptTag","htmlEscapeAttributeString","flightReader","getReader","decoder","TextDecoder","fatal","start","controller","writeInitialInstructions","error","pull","done","value","read","decodedString","decode","stream","writeFlightDataInstruction","close","scriptStart","scriptContents","htmlEscapeJsonString","JSON","stringify","enqueue","encode","chunk","htmlInlinedData","base64","Buffer","from","buffer","byteOffset","byteLength","toString","btoa","String","fromCodePoint"],"mappings":";;;;;;;;;;;;;;;IAmKgBA,+BAA+B;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B,OAAO,CAAClE,QAAQmE,MAAM,CAAC,GAAGN,cAAcC,eAAe,SAAS,CAAC;AAC9E;AAEA,SAASH,2BACPV,UAA2C,EAC3CY,WAAmB,EACnBO,KAA0B;IAE1B,IAAIC;IAEJ,IAAI,OAAOD,UAAU,UAAU;QAC7BC,kBAAkBN,IAAAA,gCAAoB,EACpCC,KAAKC,SAAS,CAAC;YAACtE;YAA4ByE;SAAM;IAEtD,OAAO;QACL,oEAAoE;QACpE,qCAAqC;QACrC,2DAA2D;QAC3D,iDAAiD;QACjD,MAAME,SACJ,OAAOC,WAAW,cACdA,OAAOC,IAAI,CACTJ,MAAMK,MAAM,EACZL,MAAMM,UAAU,EAChBN,MAAMO,UAAU,EAChBC,QAAQ,CAAC,YACXC,KAAKC,OAAOC,aAAa,IAAIX;QACnCC,kBAAkBN,IAAAA,gCAAoB,EACpCC,KAAKC,SAAS,CAAC;YAACpE;YAA8ByE;SAAO;IAEzD;IAEArB,WAAWiB,OAAO,CAChBlE,QAAQmE,MAAM,CACZ,GAAGN,YAAY,mBAAmB,EAAEQ,gBAAgB,UAAU,CAAC;AAGrE","ignoreList":[0]}

@@ -12,3 +12,3 @@ import type { AsyncLocalStorage } from 'async_hooks';

import type { ServerComponentsHmrCache } from '../response-cache';
import type { PrerenderResumeDataCache, ResumeDataCache } from '../resume-data-cache/resume-data-cache';
import type { ResumeDataCache } from '../resume-data-cache/resume-data-cache';
import type { Params } from '../request/params';

@@ -255,16 +255,2 @@ import type { ImplicitTags } from '../lib/implicit-tags';

}
export interface PrerenderStorePPR extends CommonWorkUnitStore, RevalidateStore {
readonly type: 'prerender-ppr';
readonly rootParams: Params;
readonly dynamicTracking: null | DynamicTrackingState;
/**
* The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access.
*/
readonly fallbackRouteParams: OpaqueFallbackRouteParams | null;
/**
* The resume data cache for this prerender. Always mutable in PPR mode.
*/
resumeDataCache: PrerenderResumeDataCache;
}
export interface PrerenderStoreLegacy extends CommonWorkUnitStore, RevalidateStore {

@@ -274,3 +260,3 @@ readonly type: 'prerender-legacy';

}
export type PrerenderStore = PrerenderStoreLegacy | PrerenderStorePPR | PrerenderStoreModern;
export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern;
export type StaticPrerenderStore = Exclude<PrerenderStore, PrerenderStoreModernRuntime | ValidationStoreClient>;

@@ -277,0 +263,0 @@ export interface CommonCacheStore extends Omit<CommonWorkUnitStore, 'implicitTags'> {

@@ -76,3 +76,2 @@ "use strict";

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -110,3 +109,2 @@ return true;

case 'validation-client':
case 'prerender-ppr':
return workUnitStore.resumeDataCache;

@@ -134,3 +132,2 @@ case 'cache':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -157,3 +154,2 @@ case 'unstable-cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -180,3 +176,2 @@ case 'unstable-cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -204,3 +199,2 @@ case 'unstable-cache':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -223,3 +217,2 @@ case 'generate-static-params':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -250,3 +243,2 @@ case 'cache':

}
case 'prerender-ppr':
case 'prerender-legacy':

@@ -270,3 +262,2 @@ case 'cache':

}
case 'prerender-ppr':
case 'prerender-legacy':

@@ -273,0 +264,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n\n /**\n * DEV-only.\n * Certain APIs have different behavior in static and runtime prerenders.\n * - if `false`, they will follow static semantics\n * - if `true`, they will follow runtime semantics\n * */\n needsAppShell?: boolean // DEV-only\n /**\n * DEV-only, mutable.\n * Whether any APIs that resolve in different stages in static and\n * runtime prerenders (i.e. whose behavior varies on `needsAppShell`)\n * were used during this render.\n * */\n hasIncompatibleShellContent?: boolean\n\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["getCacheSignal","getDraftModeProviderForCacheScope","getHmrRefreshHash","getResumeDataCache","getServerComponentsHmrCache","getStagedRenderingController","getVaryParamsAccumulator","isHmrRefresh","throwForMissingRequestStore","throwInvariantForMissingStore","willConsumerServerCache","workUnitAsyncStorage","workUnitAsyncStorageInstance","workUnitStore","type","consumerWillServerCache","callingExpression","Error","InvariantError","resumeDataCache","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","serverComponentsHmrCache","workStore","isDraftMode","draftMode","stagedRendering","cacheSignal","varyParamsAccumulator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;IAkpBgBA,cAAc;eAAdA;;IAjDAC,iCAAiC;eAAjCA;;IA/EAC,iBAAiB;eAAjBA;;IAtBAC,kBAAkB;eAAlBA;;IAwEAC,2BAA2B;eAA3BA;;IAwDAC,4BAA4B;eAA5BA;;IAkDAC,wBAAwB;eAAxBA;;IAlIAC,YAAY;eAAZA;;IA/DAC,2BAA2B;eAA3BA;;IAMAC,6BAA6B;eAA7BA;;IArCAC,uBAAuB;eAAvBA;;IA6ByBC,oBAAoB;eAApDC,0DAA4B;;;8CAheQ;gCASd;AA0bxB,SAASF,wBACdG,aAAwC;IAExC,IAAI,CAACA,eAAe;QAClB,OAAO;IACT;IAEA,OAAQA,cAAcC,IAAI;QAC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;YACE,OAAOjB;IACX;AACF;AAEO,SAASP,yBACdO,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAckB,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACElB;YACA,OAAO;IACX;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n\n /**\n * DEV-only.\n * Certain APIs have different behavior in static and runtime prerenders.\n * - if `false`, they will follow static semantics\n * - if `true`, they will follow runtime semantics\n * */\n needsAppShell?: boolean // DEV-only\n /**\n * DEV-only, mutable.\n * Whether any APIs that resolve in different stages in static and\n * runtime prerenders (i.e. whose behavior varies on `needsAppShell`)\n * were used during this render.\n * */\n hasIncompatibleShellContent?: boolean\n\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["getCacheSignal","getDraftModeProviderForCacheScope","getHmrRefreshHash","getResumeDataCache","getServerComponentsHmrCache","getStagedRenderingController","getVaryParamsAccumulator","isHmrRefresh","throwForMissingRequestStore","throwInvariantForMissingStore","willConsumerServerCache","workUnitAsyncStorage","workUnitAsyncStorageInstance","workUnitStore","type","consumerWillServerCache","callingExpression","Error","InvariantError","resumeDataCache","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","serverComponentsHmrCache","workStore","isDraftMode","draftMode","stagedRendering","cacheSignal","varyParamsAccumulator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;IAknBgBA,cAAc;eAAdA;;IA/CAC,iCAAiC;eAAjCA;;IA5EAC,iBAAiB;eAAjBA;;IArBAC,kBAAkB;eAAlBA;;IAqEAC,2BAA2B;eAA3BA;;IAsDAC,4BAA4B;eAA5BA;;IAgDAC,wBAAwB;eAAxBA;;IA7HAC,YAAY;eAAZA;;IA7DAC,2BAA2B;eAA3BA;;IAMAC,6BAA6B;eAA7BA;;IApCAC,uBAAuB;eAAvBA;;IA4ByBC,oBAAoB;eAApDC,0DAA4B;;;8CA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QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOjB;IACX;AACF;AAEO,SAASP,yBACdO,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAckB,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACElB;YACA,OAAO;IACX;AACF","ignoreList":[0]}

@@ -276,2 +276,3 @@ import type { NextConfig } from './config';

turbopackCjsTreeShaking: z.ZodOptional<z.ZodBoolean>;
turbopackCjsScopeHoisting: z.ZodOptional<z.ZodBoolean>;
turbopackServerFastRefresh: z.ZodOptional<z.ZodBoolean>;

@@ -278,0 +279,0 @@ optimizePackageImports: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;

@@ -431,2 +431,3 @@ "use strict";

turbopackCjsTreeShaking: _zod.z.boolean().optional(),
turbopackCjsScopeHoisting: _zod.z.boolean().optional(),
turbopackServerFastRefresh: _zod.z.boolean().optional(),

@@ -433,0 +434,0 @@ optimizePackageImports: _zod.z.array(_zod.z.string()).optional(),

@@ -305,3 +305,2 @@ "use strict";

const experimental = {
ppr: ex.ppr,
taint: ex.taint,

@@ -308,0 +307,0 @@ serverActions: ex.serverActions,

@@ -582,3 +582,2 @@ "use strict";

config: {
pprConfig: this.nextConfig.experimental.ppr,
configFileName,

@@ -585,0 +584,0 @@ cacheComponents: Boolean(this.nextConfig.cacheComponents)

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = createPromiseWithResolvers<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value, cacheKey) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return (\n cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)\n )\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value, cacheKey) {\n return cacheKey.length + JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n // The router server or the render server may run in the same process and\n // have already registered the unhandled rejection listener, in which case\n // we must not register another one, to avoid logging unhandled rejections\n // multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["DevServer","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","React","createElement","Server","getStaticPathsWorker","worker","Worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getFormattedNodeOptionsWithoutInspect","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","createPromiseWithResolvers","conf","bundlerService","startServerSpan","trace","renderOpts","ErrorDebug","staticPathsCache","LRUCache","length","value","cacheKey","JSON","stringify","staticPaths","pagesDir","appDir","findPagesDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","defaultConfig","installUseCacheProbe","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","installDevValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","DevRouteMatcherManager","extensions","pageExtensions","extensionsExpression","RegExp","join","fileReader","BatchedFileReader","DefaultFileReader","pathnameFilter","test","push","DevPagesRouteMatcherProvider","localeNormalizer","DevPagesAPIRouteMatcherProvider","ignorePartFilter","part","startsWith","isTurbopack","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","getBuildId","prepareImpl","setGlobal","PHASE_DEVELOPMENT_SERVER","existingTelemetry","traceGlobals","get","telemetry","Telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","on","err","logErrorWithOriginalStack","hasPage","normalizedPath","normalizePagePath","console","error","isMiddlewareFile","findPageFile","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","DecodeError","MiddlewareNotFoundError","getProperError","decorateServerError","COMPILER_NAMES","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","getRequestMeta","requestStart","hrtime","bigint","addRequestMeta","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","logRequests","devRequestTimingInternalsEnd","manualTraceChild","hrtimeToEpochNanoseconds","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","pathHasPrefix","removePathPrefix","fs","existsSync","pathJoin","publicDir","PUBLIC_DIR_MIDDLEWARE_CONFLICT","formatServerError","sent","__NEXT_PAGE","isError","internalErr","body","send","type","getPagesManifest","NodeManifestLoader","serverDistDir","PAGES_MANIFEST","getAppPathsManifest","enabledDirectories","app","APP_PATHS_MANIFEST","rewrites","generateInterceptionRoutesRewrites","Object","keys","appPathRoutes","map","route","buildCustomRoute","regex","output","Log","exit","getMiddleware","middleware","getMiddlewareRouteMatcher","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","getInstrumentationModule","message","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","withCoalescedInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","FallbackMode","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","PRERENDER_MANIFEST","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackModeToFallbackField","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","getRouteRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","HMR_MESSAGE_SENT_TO_BROWSER","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","WrappedBuildError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","loadDefaultErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":";;;;+BAiIA;;;eAAqBA;;;6BAjHd;+DAQgB;2DACR;4BACQ;mCACc;yCACM;sBACV;2BACc;8BAClB;4BAOtB;oEACmC;mCACR;+BACJ;kCACG;yBACP;uBAMnB;wBACsB;8BACA;uBACyB;mCAClB;4CAI7B;wBAC8C;6DAChC;iEACmB;8BACe;wBACtB;mCACC;wCACK;8CACM;iDACG;gDACD;iDACC;oCACb;mCACD;mCACA;0BACT;wCACiB;sCACC;sCAIpC;oDAC4C;kCAClB;6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AAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACzN,yBAAyB,CAACD,KAAK;QACtC;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = createPromiseWithResolvers<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value, cacheKey) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return (\n cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)\n )\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value, cacheKey) {\n return cacheKey.length + JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n // The router server or the render server may run in the same process and\n // have already registered the unhandled rejection listener, in which case\n // we must not register another one, to avoid logging unhandled rejections\n // multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["DevServer","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","React","createElement","Server","getStaticPathsWorker","worker","Worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getFormattedNodeOptionsWithoutInspect","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","createPromiseWithResolvers","conf","bundlerService","startServerSpan","trace","renderOpts","ErrorDebug","staticPathsCache","LRUCache","length","value","cacheKey","JSON","stringify","staticPaths","pagesDir","appDir","findPagesDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","defaultConfig","installUseCacheProbe","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","installDevValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","DevRouteMatcherManager","extensions","pageExtensions","extensionsExpression","RegExp","join","fileReader","BatchedFileReader","DefaultFileReader","pathnameFilter","test","push","DevPagesRouteMatcherProvider","localeNormalizer","DevPagesAPIRouteMatcherProvider","ignorePartFilter","part","startsWith","isTurbopack","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","getBuildId","prepareImpl","setGlobal","PHASE_DEVELOPMENT_SERVER","existingTelemetry","traceGlobals","get","telemetry","Telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","on","err","logErrorWithOriginalStack","hasPage","normalizedPath","normalizePagePath","console","error","isMiddlewareFile","findPageFile","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","DecodeError","MiddlewareNotFoundError","getProperError","decorateServerError","COMPILER_NAMES","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","getRequestMeta","requestStart","hrtime","bigint","addRequestMeta","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","logRequests","devRequestTimingInternalsEnd","manualTraceChild","hrtimeToEpochNanoseconds","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","pathHasPrefix","removePathPrefix","fs","existsSync","pathJoin","publicDir","PUBLIC_DIR_MIDDLEWARE_CONFLICT","formatServerError","sent","__NEXT_PAGE","isError","internalErr","body","send","type","getPagesManifest","NodeManifestLoader","serverDistDir","PAGES_MANIFEST","getAppPathsManifest","enabledDirectories","app","APP_PATHS_MANIFEST","rewrites","generateInterceptionRoutesRewrites","Object","keys","appPathRoutes","map","route","buildCustomRoute","regex","output","Log","exit","getMiddleware","middleware","getMiddlewareRouteMatcher","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","getInstrumentationModule","message","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","withCoalescedInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","FallbackMode","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","PRERENDER_MANIFEST","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackModeToFallbackField","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","getRouteRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","HMR_MESSAGE_SENT_TO_BROWSER","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","WrappedBuildError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","loadDefaultErrorComponents","instrumentationOnRequ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M2P,IAAAA,sDAA0B,EAAC,IAAI,CAAC5Q,OAAO;IACtD;IAEA,MAAMsQ,oBAAoBvP,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACvC,cAAc,CAAC8R,mBAAmB,CAACvP;IACvD;IAEA,MAAgB8P,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACvN,SAASwN,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACvN,yBAAyB,CAACD,KAAK;QACtC;IACF;AACF","ignoreList":[0]}

@@ -6,5 +6,3 @@ import type { NextConfigComplete } from '../config-shared';

import type { IncrementalCache } from '../lib/incremental-cache';
import { type ExperimentalPPRConfig } from '../lib/experimental/ppr';
type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined;
configFileName: string;

@@ -11,0 +9,0 @@ cacheComponents: boolean;

@@ -17,3 +17,2 @@ "use strict";

const _checks = require("../route-modules/checks");
const _ppr = require("../lib/experimental/ppr");
const _invarianterror = require("../../shared/lib/invariant-error");

@@ -64,3 +63,3 @@ const _collectrootparamkeys = require("../../build/segment-config/app/collect-root-param-keys");

}
const isRoutePPREnabled = (0, _checks.isAppPageRouteModule)(routeModule) && (0, _ppr.checkIsRoutePPREnabled)(config.pprConfig);
const isRoutePPREnabled = (0, _checks.isAppPageRouteModule)(routeModule) && config.cacheComponents;
const rootParamKeys = (0, _collectrootparamkeys.collectRootParamKeys)(routeModule);

@@ -67,0 +66,0 @@ return (0, _app.buildAppStaticPaths)({

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/dev/static-paths-worker.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type {\n AppPageModule,\n AppPageRouteModule,\n} from '../route-modules/app-page/module'\nimport type {\n AppRouteModule,\n AppRouteRouteModule,\n} from '../route-modules/app-route/module.compiled'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { collectSegments } from '../../build/segment-config/app/app-segments'\nimport type { StaticPathsResult } from '../../build/static-paths/types'\nimport { loadComponents } from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport { isAppPageRouteModule } from '../route-modules/checks'\nimport {\n checkIsRoutePPREnabled,\n type ExperimentalPPRConfig,\n} from '../lib/experimental/ppr'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'\nimport { buildAppStaticPaths } from '../../build/static-paths/app'\nimport { buildPagesStaticPaths } from '../../build/static-paths/pages'\nimport { createIncrementalCache } from '../../export/helpers/create-incremental-cache'\nimport { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'\n\ntype RuntimeConfig = {\n pprConfig: ExperimentalPPRConfig | undefined\n configFileName: string\n cacheComponents: boolean\n}\n\n// we call getStaticPaths in a separate process to ensure\n// side-effects aren't relied on in dev that will break\n// during a production build\nexport async function loadStaticPaths({\n dir,\n distDir,\n pathname,\n config,\n httpAgentOptions,\n locales,\n defaultLocale,\n isAppPath,\n page,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n requestHeaders,\n cacheHandler,\n cacheHandlers,\n cacheLifeProfiles,\n nextConfigOutput,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n sriEnabled,\n}: {\n dir: string\n distDir: string\n pathname: string\n config: RuntimeConfig\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n locales?: readonly string[]\n defaultLocale?: string\n isAppPath: boolean\n page: string\n isrFlushToDisk?: boolean\n fetchCacheKeyPrefix?: string\n cacheMaxMemorySize: number\n requestHeaders: IncrementalCache['requestHeaders']\n cacheHandler?: string\n cacheHandlers?: NextConfigComplete['cacheHandlers']\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n nextConfigOutput: 'standalone' | 'export' | undefined\n buildId: string\n deploymentId: string\n authInterrupts: boolean\n useCacheTimeout: number\n staticPageGenerationTimeout: number\n sriEnabled: boolean\n}): Promise<StaticPathsResult> {\n // this needs to be initialized before loadComponents otherwise\n // \"use cache\" could be missing it's cache handlers\n await createIncrementalCache({\n dir,\n distDir,\n cacheHandler,\n cacheHandlers,\n requestHeaders,\n fetchCacheKeyPrefix,\n flushToDisk: isrFlushToDisk,\n cacheMaxMemorySize,\n })\n\n // update work memory runtime-config\n setHttpClientAndAgentOptions({\n httpAgentOptions,\n })\n\n const components = await loadComponents<AppPageModule | AppRouteModule>({\n distDir,\n // In `pages/`, the page is the same as the pathname.\n page: page || pathname,\n isAppPath,\n isDev: true,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n if (isAppPath) {\n const routeModule = components.routeModule\n const segments = await collectSegments(\n // We know this is an app page or app route module because we checked\n // above that the page type is 'app'.\n routeModule as AppPageRouteModule | AppRouteRouteModule\n )\n\n const route = parseNormalizedAppRoute(pathname)\n if (route.dynamicSegments.length === 0) {\n throw new InvariantError(\n `Expected a dynamic route, but got a static route: ${pathname}`\n )\n }\n\n const isRoutePPREnabled =\n isAppPageRouteModule(routeModule) &&\n checkIsRoutePPREnabled(config.pprConfig)\n\n const rootParamKeys = collectRootParamKeys(routeModule)\n\n return buildAppStaticPaths({\n dir,\n page: pathname,\n route,\n cacheComponents: config.cacheComponents,\n segments,\n distDir,\n requestHeaders,\n cacheHandler,\n cacheLifeProfiles,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n ComponentMod: components.ComponentMod,\n nextConfigOutput,\n isRoutePPREnabled,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n rootParamKeys,\n })\n } else if (!components.getStaticPaths) {\n // We shouldn't get to this point since the worker should only be called for\n // SSG pages with getStaticPaths.\n throw new InvariantError(\n `Failed to load page with getStaticPaths for ${pathname}`\n )\n }\n\n return buildPagesStaticPaths({\n page: pathname,\n getStaticPaths: components.getStaticPaths,\n configFileName: config.configFileName,\n locales,\n defaultLocale,\n })\n}\n"],"names":["loadStaticPaths","dir","distDir","pathname","config","httpAgentOptions","locales","defaultLocale","isAppPath","page","isrFlushToDisk","fetchCacheKeyPrefix","cacheMaxMemorySize","requestHeaders","cacheHandler","cacheHandlers","cacheLifeProfiles","nextConfigOutput","buildId","deploymentId","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","createIncrementalCache","flushToDisk","setHttpClientAndAgentOptions","components","loadComponents","isDev","needsManifestsForLegacyReasons","routeModule","segments","collectSegments","route","parseNormalizedAppRoute","dynamicSegments","length","InvariantError","isRoutePPREnabled","isAppPageRouteModule","checkIsRoutePPREnabled","pprConfig","rootParamKeys","collectRootParamKeys","buildAppStaticPaths","cacheComponents","ComponentMod","getStaticPaths","buildPagesStaticPaths","configFileName"],"mappings":";;;;+BAuCsBA;;;eAAAA;;;QA7Bf;QACA;6BAEyB;gCAED;mCACc;wBAER;qBAI9B;gCACwB;sCACM;qBACD;uBACE;wCACC;sBACC;AAWjC,eAAeA,gBAAgB,EACpCC,GAAG,EACHC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EACPC,aAAa,EACbC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,mBAAmB,EACnBC,kBAAkB,EAClBC,cAAc,EACdC,YAAY,EACZC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,EAChBC,OAAO,EACPC,YAAY,EACZC,cAAc,EACdC,eAAe,EACfC,2BAA2B,EAC3BC,UAAU,EAyBX;IACC,+DAA+D;IAC/D,mDAAmD;IACnD,MAAMC,IAAAA,8CAAsB,EAAC;QAC3BvB;QACAC;QACAY;QACAC;QACAF;QACAF;QACAc,aAAaf;QACbE;IACF;IAEA,oCAAoC;IACpCc,IAAAA,+CAA4B,EAAC;QAC3BrB;IACF;IAEA,MAAMsB,aAAa,MAAMC,IAAAA,8BAAc,EAAiC;QACtE1B;QACA,qDAAqD;QACrDO,MAAMA,QAAQN;QACdK;QACAqB,OAAO;QACPN;QACAO,gCAAgC;IAClC;IAEA,IAAItB,WAAW;QACb,MAAMuB,cAAcJ,WAAWI,WAAW;QAC1C,MAAMC,WAAW,MAAMC,IAAAA,4BAAe,EACpC,qEAAqE;QACrE,qCAAqC;QACrCF;QAGF,MAAMG,QAAQC,IAAAA,6BAAuB,EAAChC;QACtC,IAAI+B,MAAME,eAAe,CAACC,MAAM,KAAK,GAAG;YACtC,MAAM,qBAEL,CAFK,IAAIC,8BAAc,CACtB,CAAC,kDAAkD,EAAEnC,UAAU,GAD3D,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,MAAMoC,oBACJC,IAAAA,4BAAoB,EAACT,gBACrBU,IAAAA,2BAAsB,EAACrC,OAAOsC,SAAS;QAEzC,MAAMC,gBAAgBC,IAAAA,0CAAoB,EAACb;QAE3C,OAAOc,IAAAA,wBAAmB,EAAC;YACzB5C;YACAQ,MAAMN;YACN+B;YACAY,iBAAiB1C,OAAO0C,eAAe;YACvCd;YACA9B;YACAW;YACAC;YACAE;YACAN;YACAC;YACAC;YACAmC,cAAcpB,WAAWoB,YAAY;YACrC9B;YACAsB;YACArB;YACAC;YACAC;YACAC;YACAC;YACAqB;QACF;IACF,OAAO,IAAI,CAAChB,WAAWqB,cAAc,EAAE;QACrC,4EAA4E;QAC5E,iCAAiC;QACjC,MAAM,qBAEL,CAFK,IAAIV,8BAAc,CACtB,CAAC,4CAA4C,EAAEnC,UAAU,GADrD,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,OAAO8C,IAAAA,4BAAqB,EAAC;QAC3BxC,MAAMN;QACN6C,gBAAgBrB,WAAWqB,cAAc;QACzCE,gBAAgB9C,OAAO8C,cAAc;QACrC5C;QACAC;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/dev/static-paths-worker.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type {\n AppPageModule,\n AppPageRouteModule,\n} from '../route-modules/app-page/module'\nimport type {\n AppRouteModule,\n AppRouteRouteModule,\n} from '../route-modules/app-route/module.compiled'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { collectSegments } from '../../build/segment-config/app/app-segments'\nimport type { StaticPathsResult } from '../../build/static-paths/types'\nimport { loadComponents } from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport { isAppPageRouteModule } from '../route-modules/checks'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'\nimport { buildAppStaticPaths } from '../../build/static-paths/app'\nimport { buildPagesStaticPaths } from '../../build/static-paths/pages'\nimport { createIncrementalCache } from '../../export/helpers/create-incremental-cache'\nimport { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'\n\ntype RuntimeConfig = {\n configFileName: string\n cacheComponents: boolean\n}\n\n// we call getStaticPaths in a separate process to ensure\n// side-effects aren't relied on in dev that will break\n// during a production build\nexport async function loadStaticPaths({\n dir,\n distDir,\n pathname,\n config,\n httpAgentOptions,\n locales,\n defaultLocale,\n isAppPath,\n page,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n requestHeaders,\n cacheHandler,\n cacheHandlers,\n cacheLifeProfiles,\n nextConfigOutput,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n sriEnabled,\n}: {\n dir: string\n distDir: string\n pathname: string\n config: RuntimeConfig\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n locales?: readonly string[]\n defaultLocale?: string\n isAppPath: boolean\n page: string\n isrFlushToDisk?: boolean\n fetchCacheKeyPrefix?: string\n cacheMaxMemorySize: number\n requestHeaders: IncrementalCache['requestHeaders']\n cacheHandler?: string\n cacheHandlers?: NextConfigComplete['cacheHandlers']\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n nextConfigOutput: 'standalone' | 'export' | undefined\n buildId: string\n deploymentId: string\n authInterrupts: boolean\n useCacheTimeout: number\n staticPageGenerationTimeout: number\n sriEnabled: boolean\n}): Promise<StaticPathsResult> {\n // this needs to be initialized before loadComponents otherwise\n // \"use cache\" could be missing it's cache handlers\n await createIncrementalCache({\n dir,\n distDir,\n cacheHandler,\n cacheHandlers,\n requestHeaders,\n fetchCacheKeyPrefix,\n flushToDisk: isrFlushToDisk,\n cacheMaxMemorySize,\n })\n\n // update work memory runtime-config\n setHttpClientAndAgentOptions({\n httpAgentOptions,\n })\n\n const components = await loadComponents<AppPageModule | AppRouteModule>({\n distDir,\n // In `pages/`, the page is the same as the pathname.\n page: page || pathname,\n isAppPath,\n isDev: true,\n sriEnabled,\n needsManifestsForLegacyReasons: true,\n })\n\n if (isAppPath) {\n const routeModule = components.routeModule\n const segments = await collectSegments(\n // We know this is an app page or app route module because we checked\n // above that the page type is 'app'.\n routeModule as AppPageRouteModule | AppRouteRouteModule\n )\n\n const route = parseNormalizedAppRoute(pathname)\n if (route.dynamicSegments.length === 0) {\n throw new InvariantError(\n `Expected a dynamic route, but got a static route: ${pathname}`\n )\n }\n\n const isRoutePPREnabled =\n isAppPageRouteModule(routeModule) && config.cacheComponents\n\n const rootParamKeys = collectRootParamKeys(routeModule)\n\n return buildAppStaticPaths({\n dir,\n page: pathname,\n route,\n cacheComponents: config.cacheComponents,\n segments,\n distDir,\n requestHeaders,\n cacheHandler,\n cacheLifeProfiles,\n isrFlushToDisk,\n fetchCacheKeyPrefix,\n cacheMaxMemorySize,\n ComponentMod: components.ComponentMod,\n nextConfigOutput,\n isRoutePPREnabled,\n buildId,\n deploymentId,\n authInterrupts,\n useCacheTimeout,\n staticPageGenerationTimeout,\n rootParamKeys,\n })\n } else if (!components.getStaticPaths) {\n // We shouldn't get to this point since the worker should only be called for\n // SSG pages with getStaticPaths.\n throw new InvariantError(\n `Failed to load page with getStaticPaths for ${pathname}`\n )\n }\n\n return buildPagesStaticPaths({\n page: pathname,\n getStaticPaths: components.getStaticPaths,\n configFileName: config.configFileName,\n locales,\n defaultLocale,\n })\n}\n"],"names":["loadStaticPaths","dir","distDir","pathname","config","httpAgentOptions","locales","defaultLocale","isAppPath","page","isrFlushToDisk","fetchCacheKeyPrefix","cacheMaxMemorySize","requestHeaders","cacheHandler","cacheHandlers","cacheLifeProfiles","nextConfigOutput","buildId","deploymentId","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","createIncrementalCache","flushToDisk","setHttpClientAndAgentOptions","components","loadComponents","isDev","needsManifestsForLegacyReasons","routeModule","segments","collectSegments","route","parseNormalizedAppRoute","dynamicSegments","length","InvariantError","isRoutePPREnabled","isAppPageRouteModule","cacheComponents","rootParamKeys","collectRootParamKeys","buildAppStaticPaths","ComponentMod","getStaticPaths","buildPagesStaticPaths","configFileName"],"mappings":";;;;+BAkCsBA;;;eAAAA;;;QAxBf;QACA;6BAEyB;gCAED;mCACc;wBAER;gCACN;sCACM;qBACD;uBACE;wCACC;sBACC;AAUjC,eAAeA,gBAAgB,EACpCC,GAAG,EACHC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EACPC,aAAa,EACbC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,mBAAmB,EACnBC,kBAAkB,EAClBC,cAAc,EACdC,YAAY,EACZC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,EAChBC,OAAO,EACPC,YAAY,EACZC,cAAc,EACdC,eAAe,EACfC,2BAA2B,EAC3BC,UAAU,EAyBX;IACC,+DAA+D;IAC/D,mDAAmD;IACnD,MAAMC,IAAAA,8CAAsB,EAAC;QAC3BvB;QACAC;QACAY;QACAC;QACAF;QACAF;QACAc,aAAaf;QACbE;IACF;IAEA,oCAAoC;IACpCc,IAAAA,+CAA4B,EAAC;QAC3BrB;IACF;IAEA,MAAMsB,aAAa,MAAMC,IAAAA,8BAAc,EAAiC;QACtE1B;QACA,qDAAqD;QACrDO,MAAMA,QAAQN;QACdK;QACAqB,OAAO;QACPN;QACAO,gCAAgC;IAClC;IAEA,IAAItB,WAAW;QACb,MAAMuB,cAAcJ,WAAWI,WAAW;QAC1C,MAAMC,WAAW,MAAMC,IAAAA,4BAAe,EACpC,qEAAqE;QACrE,qCAAqC;QACrCF;QAGF,MAAMG,QAAQC,IAAAA,6BAAuB,EAAChC;QACtC,IAAI+B,MAAME,eAAe,CAACC,MAAM,KAAK,GAAG;YACtC,MAAM,qBAEL,CAFK,IAAIC,8BAAc,CACtB,CAAC,kDAAkD,EAAEnC,UAAU,GAD3D,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,MAAMoC,oBACJC,IAAAA,4BAAoB,EAACT,gBAAgB3B,OAAOqC,eAAe;QAE7D,MAAMC,gBAAgBC,IAAAA,0CAAoB,EAACZ;QAE3C,OAAOa,IAAAA,wBAAmB,EAAC;YACzB3C;YACAQ,MAAMN;YACN+B;YACAO,iBAAiBrC,OAAOqC,eAAe;YACvCT;YACA9B;YACAW;YACAC;YACAE;YACAN;YACAC;YACAC;YACAiC,cAAclB,WAAWkB,YAAY;YACrC5B;YACAsB;YACArB;YACAC;YACAC;YACAC;YACAC;YACAoB;QACF;IACF,OAAO,IAAI,CAACf,WAAWmB,cAAc,EAAE;QACrC,4EAA4E;QAC5E,iCAAiC;QACjC,MAAM,qBAEL,CAFK,IAAIR,8BAAc,CACtB,CAAC,4CAA4C,EAAEnC,UAAU,GADrD,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,OAAO4C,IAAAA,4BAAqB,EAAC;QAC3BtC,MAAMN;QACN2C,gBAAgBnB,WAAWmB,cAAc;QACzCE,gBAAgB5C,OAAO4C,cAAc;QACrC1C;QACAC;IACF;AACF","ignoreList":[0]}

@@ -173,3 +173,2 @@ "use strict";

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -296,3 +295,2 @@ case 'prerender-runtime':

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -299,0 +297,0 @@ case 'prerender-runtime':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function trackIncompatibleShellContent(workUnitStore: RequestStore) {\n workUnitStore.hasIncompatibleShellContent = true\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */\nexport function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {\n const methodCache: Record<string, (...args: any[]) => any> = {}\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n let patchedMethod = methodCache[prop]\n if (patchedMethod !== undefined) {\n return patchedMethod\n }\n\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n patchedMethod = {\n [prop]: (...args: unknown[]) => {\n try {\n onUse()\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err)\n }\n\n return originalMethod.apply(target, args)\n },\n }[prop]\n\n methodCache[prop] = patchedMethod\n return patchedMethod\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["ClientHookDynamicError","RENDER_STAGES_BY_DATA_KIND","applyOwnerStack","isClientHookDynamicError","isHangingPromiseRejectionError","makeClientHookHangingPromise","makeDevtoolsIOAwarePromise","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","makeRuntimeHangingPromise","makeStageHangingPromise","makeUntrackedHangingPromise","trackFallbackParamsAccessed","trackIncompatibleShellContent","trackPromiseUsed","trackRuntimeDataAccessed","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","abortListenersBySignal","WeakMap","signal","makeHangingPromiseWithError","workUnitStore","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","hasIncompatibleShellContent","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","trigger","value","promise","then","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","onUse","methodCache","Proxy","target","prop","receiver","patchedMethod","originalMethod","ReflectAdapter","args","console","apply","sessionData","RenderStage","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","process","env","NODE_ENV","getClientReact","getServerReact","ownerStack","workUnitAsyncStorage","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAuCaA,sBAAsB;eAAtBA;;IAsXAC,0BAA0B;eAA1BA;;IAMGC,eAAe;eAAfA;;IA7WAC,wBAAwB;eAAxBA;;IA1CAC,8BAA8B;eAA9BA;;IA8RAC,4BAA4B;eAA5BA;;IA0DAC,0BAA0B;eAA1BA;;IAjRAC,yBAAyB;eAAzBA;;IAsFAC,gCAAgC;eAAhCA;;IAkLAC,sBAAsB;eAAtBA;;IAlNAC,yBAAyB;eAAzBA;;IA6DAC,uBAAuB;eAAvBA;;IAxGAC,2BAA2B;eAA3BA;;IAgJAC,2BAA2B;eAA3BA;;IAwDAC,6BAA6B;eAA7BA;;IAsFAC,gBAAgB;eAAhBA;;IA1JAC,wBAAwB;eAAxBA;;;iCA/NT;8CAK8B;uCACU;yBAChB;AAExB,SAASZ,+BACda,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,KAAK,CACH,CAA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aACE,AAACG,CAAAA,mBAAmB,EAAC,IAAMpE,CAAAA,cAAcsE,eAAe,IAAI,EAAC,KAC7D/B;gBACF;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAKA;gBACH0B,aAAaG;gBACb;YACF;gBACEpE;QACJ;QAEA,IAAIiE,YAAY;YACd,IAAIM,QAAQN;YAEZ,IAAItD,MAAM4D,KAAK,EAAE;gBACf,MAAMC,SAAmB,EAAE;gBAE3B,KAAK,MAAMC,SAAS9D,MAAM4D,KAAK,CAACG,KAAK,CAAC,MAAMC,KAAK,CAAC,GAAI;oBACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAOnD,IAAI,CAACoD;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEA5D,MAAM4D,KAAK,GAAG5D,MAAMmE,IAAI,GAAG,OAAOnE,MAAMoE,OAAO,GAAGR;QACpD;IACF;IAEA,OAAO5D;AACT","ignoreList":[0]}
{"version":3,"sources":["../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function trackIncompatibleShellContent(workUnitStore: RequestStore) {\n workUnitStore.hasIncompatibleShellContent = true\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */\nexport function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {\n const methodCache: Record<string, (...args: any[]) => any> = {}\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n let patchedMethod = methodCache[prop]\n if (patchedMethod !== undefined) {\n return patchedMethod\n }\n\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n patchedMethod = {\n [prop]: (...args: unknown[]) => {\n try {\n onUse()\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err)\n }\n\n return originalMethod.apply(target, args)\n },\n }[prop]\n\n methodCache[prop] = patchedMethod\n return patchedMethod\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["ClientHookDynamicError","RENDER_STAGES_BY_DATA_KIND","applyOwnerStack","isClientHookDynamicError","isHangingPromiseRejectionError","makeClientHookHangingPromise","makeDevtoolsIOAwarePromise","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","makeRuntimeHangingPromise","makeStageHangingPromise","makeUntrackedHangingPromise","trackFallbackParamsAccessed","trackIncompatibleShellContent","trackPromiseUsed","trackRuntimeDataAccessed","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","abortListenersBySignal","WeakMap","signal","makeHangingPromiseWithError","workUnitStore","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","hasIncompatibleShellContent","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","trigger","value","promise","then","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","onUse","methodCache","Proxy","target","prop","receiver","patchedMethod","originalMethod","ReflectAdapter","args","console","apply","sessionData","RenderStage","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","process","env","NODE_ENV","getClientReact","getServerReact","ownerStack","workUnitAsyncStorage","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAuCaA,sBAAsB;eAAtBA;;IAqXAC,0BAA0B;eAA1BA;;IAMGC,eAAe;eAAfA;;IA5WAC,wBAAwB;eAAxBA;;IA1CAC,8BAA8B;eAA9BA;;IA6RAC,4BAA4B;eAA5BA;;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OAAO,GAAGR;QACpD;IACF;IAEA,OAAO5D;AACT","ignoreList":[0]}

@@ -82,3 +82,3 @@ "use strict";

const versionSuffix = logBundler ? ` (${(0, _bundler.bundlerName)((0, _bundler.getBundlerFromEnv)())})` : '';
_log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.1-canary.11"}`))}${versionSuffix}`);
_log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.1-canary.12"}`))}${versionSuffix}`);
if (appUrl) {

@@ -85,0 +85,0 @@ _log.bootstrap(`- Local: ${appUrl}`);

@@ -62,3 +62,2 @@ "use strict";

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -355,3 +354,2 @@ case 'cache':

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -394,3 +392,2 @@ case 'cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -502,3 +499,2 @@ case 'request':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -615,3 +611,2 @@ case 'cache':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -653,3 +648,2 @@ case 'cache':

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -757,3 +751,2 @@ case 'unstable-cache':

// fallthrough
case 'prerender-ppr':
case 'prerender-legacy':

@@ -816,3 +809,2 @@ case 'cache':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -911,3 +903,2 @@ case 'cache':

break;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -946,3 +937,2 @@ case 'cache':

case 'prerender-legacy':
case 'prerender-ppr':
case 'generate-static-params':

@@ -949,0 +939,0 @@ break;

@@ -34,3 +34,2 @@ // this must come first as it includes require hooks

const _nextrequest = require("../web/spec-extension/adapters/next-request");
const _ispostpone = require("./router-utils/is-postpone");
const _isnonhtmlsecfetchdest = require("./is-non-html-sec-fetch-dest");

@@ -644,7 +643,2 @@ const _parseurl = require("../../shared/lib/router/utils/parse-url");

const logError = async (err)=>{
if ((0, _ispostpone.isPostpone)(err)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return;
}
_log.error('uncaughtException: ', err);

@@ -651,0 +645,0 @@ };

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { releaseCompressionStream } from './release-compression-stream'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isPostpone } from './router-utils/is-postpone'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n const devMemoryThresholdRestart =\n development?.config.experimental.devMemoryThresholdRestart !== false\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n\n // On client disconnect the middleware never ends its zlib stream, which\n // then leaks past GC. See `releaseCompressionStream`.\n res.once('close', () => {\n if (res.writableFinished) return\n\n releaseCompressionStream(res)\n })\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n devMemoryThresholdRestart,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (err: Error | undefined) => {\n if (isPostpone(err)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n Log.error('uncaughtException: ', err)\n }\n\n process.on('uncaughtException', logError)\n\n // The render server may run in the same process and have already registered\n // the unhandled rejection listener, in which case we must not register\n // another one, to avoid logging unhandled rejections multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n devMemoryThresholdRestart,\n }\n}\n"],"names":["initialize","debug","setupDebug","isNextFont","pathname","test","requestHandlers","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","getBundlerFromEnv","undefined","experimentalFeatures","config","loadConfig","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_SERVER","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","finalizeBundlerFromConfig","compress","setupCompression","fsChecker","setupFsCheck","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","path","join","traceGlobals","set","pagesDir","appDir","findPagesDir","setupDevBundler","resetFetch","NEXT_PATCH_SYMBOL","setupDevBundlerSpan","startServerSpan","traceChild","trace","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","Log","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","DevBundlerService","req","res","Boolean","requestInsights","bundler","service","devMemoryThresholdRestart","instance","requestHandlerImpl","addRequestMeta","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","filterInternalHeaders","headers","url","__NEXT_REQUEST_INSIGHTS","urlParts","split","removePathPrefix","basePath","REQUEST_INSIGHTS_DEV_ENDPOINT","blockCrossSiteDEV","allowedDevOrigins","hostname","setHeader","isRequestInsightsEnabled","statusCode","end","JSON","stringify","error","getRequestInsightsSnapshot","i18n","localeDetection","urlNoQuery","pathnameInfo","getNextPathnameInfo","domainLocale","detectDomainLocale","domains","getHostname","defaultLocale","getLocaleRedirect","parsedUrl","parseUrlUtil","replace","redirect","pathLocale","locale","urlParsed","RedirectStatusCode","TemporaryRedirect","once","writableFinished","releaseCompressionStream","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","getRequestMeta","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","NoFallbackError","handleRequest","e","isAbortError","origUrl","pathHasPrefix","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","signalFromNodeResponse","closed","type","Object","keys","result","destination","format","PermanentRedirect","pipeToNodeResponse","protocol","proxyRequest","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","serveStatic","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","isChromeDevtoolsWorkspaceUrl","handleChromeDevtoolsWorkspaceRequest","realRequestPathname","isNonHtmlSecFetchDest","appNotFound","serverFields","hasAppNotFound","getItem","UNDERSCORE_NOT_FOUND_ROUTE","DecodeError","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","routerServerGlobal","RouterServerContextSymbol","relative","cwd","getNextConfigRuntime","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","isPostpone","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","getResolveRoutes","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","normalizedAssetPrefix","URL","canParse","isHMRRequest","ensureLeadingSlash","onHMR","client","isLegacyClient","send","HMR_MESSAGE_SENT_TO_BROWSER","ISR_MANIFEST","data","appIsrManifest","MockedResponse","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;;;;;+BA6F9BA;;;eAAAA;;;QAvFf;QACA;4DAES;6DACC;+DAC8C;yBACF;6BACjC;8DACL;6DACF;sCAId;uBACqB;8BACC;4BACA;8BACA;8BACoB;+BAChB;6BACc;+BACjB;kCACG;oEACJ;0CACY;6BACF;4BACZ;uCACW;0BACG;2BAOlC;oCAC4B;mCACD;uBACD;oCACE;qCACC;6BACR;oCACO;6BACJ;kCAIxB;uCAC+B;4BACJ;wBAEI;mCACJ;wBACL;yCACG;qCAIzB;yCAIA;8BACuD;iCAIvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,MAAMC,QAAQC,IAAAA,cAAU,EAAC;AACzB,MAAMC,aAAa,CAACC,WAClBA,YAAY,4CAA4CC,IAAI,CAACD;AAc/D,MAAME,kBAAwD,CAAC;AAExD,eAAeN,WAAWO,IAchC;QAmtBSC,sBACUA,sBAsCZA,uBAEUA,uBAEVA,uBAEiBA,uBA6BrBA;IA5xBF,IAAI,CAACC,QAAQC,GAAG,CAACC,QAAQ,EAAE;QACzB,0BAA0B;QAC1BF,QAAQC,GAAG,CAACC,QAAQ,GAAGJ,KAAKK,GAAG,GAAG,gBAAgB;IACpD;IAEA,gDAAgD;IAChD,MAAMC,sBAAs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D,OAAO/I,GAAG;YACnB;QAEA,sEAAsE;QACtE,sDAAsD;QACxD,EAAE,OAAO+C,KAAK;YACZ6D,QAAQzG,KAAK,CAAC,kCAAkC4C;YAChDgG,OAAO/I,GAAG;QACZ;IACF;IAEA,OAAO;QACL8C;QACAgG;QACA5B,QAAQzE,SAASyE,MAAM;QACvB+C;gBACElQ,kCAAAA;YAAAA,gCAAAA,uBAAAA,YAAa0E,OAAO,sBAApB1E,mCAAAA,qBAAsByJ,WAAW,qBAAjCzJ,iCAAmCmQ,KAAK;QAC1C;QACA/N,SAAS3B,OAAO2B,OAAO;QACvB5B;QACAkN,iBAAiBjN,OAAOiN,eAAe;QACvCC,oBAAoBlN,OAAOkN,kBAAkB;QAC7CyC,YAAY3P,OAAO2P,UAAU;QAC7BxL;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport {\n isUnhandledRejectionListenerRegistered,\n registerUnhandledRejectionListener,\n} from '../node-environment-extensions/process-error-handlers'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { releaseCompressionStream } from './release-compression-stream'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n const devMemoryThresholdRestart =\n development?.config.experimental.devMemoryThresholdRestart !== false\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n\n // On client disconnect the middleware never ends its zlib stream, which\n // then leaks past GC. See `releaseCompressionStream`.\n res.once('close', () => {\n if (res.writableFinished) return\n\n releaseCompressionStream(res)\n })\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n devMemoryThresholdRestart,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (err: Error | undefined) => {\n Log.error('uncaughtException: ', err)\n }\n\n process.on('uncaughtException', logError)\n\n // The render server may run in the same process and have already registered\n // the unhandled rejection listener, in which case we must not register\n // another one, to avoid logging unhandled rejections multiple times.\n if (!isUnhandledRejectionListenerRegistered()) {\n registerUnhandledRejectionListener()\n }\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n devMemoryThresholdRestart,\n }\n}\n"],"names":["initialize","debug","setupDebug","isNextFont","pathname","test","requestHandlers","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","getBundlerFromEnv","undefined","experimentalFeatures","config","loadConfig","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_SERVER","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","finalizeBundlerFromConfig","compress","setupCompression","fsChecker","setupFsCheck","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","path","join","traceGlobals","set","pagesDir","appDir","findPagesDir","setupDevBundler","resetFetch","NEXT_PATCH_SYMBOL","setupDevBundlerSpan","startServerSpan","traceChild","trace","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","Log","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","DevBundlerService","req","res","Boolean","requestInsights","bundler","service","devMemoryThresholdRestart","instance","requestHandlerImpl","addRequestMeta","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","filterInternalHeaders","headers","url","__NEXT_REQUEST_INSIGHTS","urlParts","split","removePathPrefix","basePath","REQUEST_INSIGHTS_DEV_ENDPOINT","blockCrossSiteDEV","allowedDevOrigins","hostname","setHeader","isRequestInsightsEnabled","statusCode","end","JSON","stringify","error","getRequestInsightsSnapshot","i18n","localeDetection","urlNoQuery","pathnameInfo","getNextPathnameInfo","domainLocale","detectDomainLocale","domains","getHostname","defaultLocale","getLocaleRedirect","parsedUrl","parseUrlUtil","replace","redirect","pathLocale","locale","urlParsed","RedirectStatusCode","TemporaryRedirect","once","writableFinished","releaseCompressionStream","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","getRequestMeta","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","NoFallbackError","handleRequest","e","isAbortError","origUrl","pathHasPrefix","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","signalFromNodeResponse","closed","type","Object","keys","result","destination","format","PermanentRedirect","pipeToNodeResponse","protocol","proxyRequest","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","serveStatic","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","isChromeDevtoolsWorkspaceUrl","handleChromeDevtoolsWorkspaceRequest","realRequestPathname","isNonHtmlSecFetchDest","appNotFound","serverFields","hasAppNotFound","getItem","UNDERSCORE_NOT_FOUND_ROUTE","DecodeError","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","routerServerGlobal","RouterServerContextSymbol","relative","cwd","getNextConfigRuntime","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","getResolveRoutes","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","normalizedAssetPrefix","URL","canParse","isHMRRequest","ensureLeadingSlash","onHMR","client","isLegacyClient","send","HMR_MESSAGE_SENT_TO_BROWSER","ISR_MANIFEST","data","appIsrManifest","MockedResponse","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;;;;;+BA4F9BA;;;eAAAA;;;QAtFf;QACA;4DAES;6DACC;+DAC8C;yBACF;6BACjC;8DACL;6DACF;sCAId;uBACqB;8BACC;4BACA;8BACA;8BACoB;+BAChB;6BACc;+BACjB;kCACG;oEACJ;0CACY;6BACF;uCACD;0BACG;2BAOlC;oCAC4B;mCACD;uBACD;oCACE;qCACC;6BACR;oCACO;6BACJ;kCAIxB;uCAC+B;4BACJ;wBAEI;mCACJ;wBACL;yCACG;qCAIzB;yCAIA;8BACuD;iCAIvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,MAAMC,QAAQC,IAAAA,cAAU,EAAC;AACzB,MAAMC,aAAa,CAACC,WAClBA,YAAY,4CAA4CC,IAAI,CAACD;AAc/D,MAAME,kBAAwD,CAAC;AAExD,eAAeN,WAAWO,IAchC;QAmtBSC,sBACUA,sBAsCZA,uBAEUA,uBAEVA,uBAE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BAClC,IAAI,CAAC5E,YAAY;oBACf,OAAO,MAAM6E,IAAAA,0BAAY,EAACvG,KAAKyK,QAAQ9H,WAAW+H;gBACpD;gBAEA,OAAOD,OAAO9I,GAAG;YACnB;QAEA,sEAAsE;QACtE,sDAAsD;QACxD,EAAE,OAAO+C,KAAK;YACZ6D,QAAQzG,KAAK,CAAC,kCAAkC4C;YAChD+F,OAAO9I,GAAG;QACZ;IACF;IAEA,OAAO;QACL8C;QACA+F;QACA3B,QAAQzE,SAASyE,MAAM;QACvB8C;gBACEjQ,kCAAAA;YAAAA,gCAAAA,uBAAAA,YAAa0E,OAAO,sBAApB1E,mCAAAA,qBAAsByJ,WAAW,qBAAjCzJ,iCAAmCkQ,KAAK;QAC1C;QACA9N,SAAS3B,OAAO2B,OAAO;QACvB5B;QACAkN,iBAAiBjN,OAAOiN,eAAe;QACvCC,oBAAoBlN,OAAOkN,kBAAkB;QAC7CwC,YAAY1P,OAAO0P,UAAU;QAC7BvL;IACF;AACF","ignoreList":[0]}

@@ -180,3 +180,3 @@ // Start CPU profile if it wasn't already started.

let { port } = serverOptions;
process.title = `next-server (v${"16.3.1-canary.11"})`;
process.title = `next-server (v${"16.3.1-canary.12"})`;
let handlersReady = ()=>{};

@@ -183,0 +183,0 @@ let handlersError = ()=>{};

@@ -253,3 +253,2 @@ "use strict";

case 'prerender-legacy':
case 'prerender-ppr':
case 'cache':

@@ -256,0 +255,0 @@ case 'unstable-cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/node-environment-extensions/console-dim.external.tsx"],"sourcesContent":["import * as inspector from 'node:inspector'\nimport { dim } from '../../lib/picocolors'\nimport {\n consoleAsyncStorage,\n type ConsoleStore,\n} from '../app-render/console-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value\nconst DIMMED_STYLE = 'dimmed'\nconst HIDDEN_STYLE = 'hidden'\n\ntype LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE\n\nlet currentAbortedLogsStyle: LogStyle = 'dimmed'\nexport function setAbortedLogsStyle(style: LogStyle) {\n currentAbortedLogsStyle = style\n}\n\ntype InterceptableConsoleMethod =\n | 'error'\n | 'assert'\n | 'debug'\n | 'dir'\n | 'dirxml'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'info'\n | 'log'\n | 'table'\n | 'trace'\n | 'warn'\n\nconst isColorSupported = dim('test') !== 'test'\n\n// 50% opacity for dimmed text\nconst dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'\nconst reactBadgeFormat = '\\x1b[0m\\x1b[7m%c%s\\x1b[0m%c '\n\nfunction dimmedConsoleArgs(...inputArgs: any[]): any[] {\n if (!isColorSupported) {\n return inputArgs\n }\n\n const newArgs = inputArgs.slice(0)\n let template = ''\n let argumentsPointer = 0\n if (typeof inputArgs[0] === 'string') {\n const originalTemplateString = inputArgs[0]\n // Remove the original template string from the args.\n newArgs.splice(argumentsPointer, 1)\n argumentsPointer += 1\n\n let i = 0\n if (originalTemplateString.startsWith(reactBadgeFormat)) {\n i = reactBadgeFormat.length\n // for `format` we already moved the pointer earlier\n // style, badge, reset style\n argumentsPointer += 3\n template += reactBadgeFormat\n // React's badge reset styles, reapply dimming\n template += '\\x1b[2m%c'\n // argumentsPointer includes template\n newArgs.splice(argumentsPointer - 1, 0, dimStyle)\n // dim the badge\n newArgs[0] += `;${dimStyle}`\n }\n\n for (i; i < originalTemplateString.length; i++) {\n const currentChar = originalTemplateString[i]\n if (currentChar !== '%') {\n template += currentChar\n continue\n }\n\n const nextChar = originalTemplateString[i + 1]\n ++i\n\n switch (nextChar) {\n case 'f':\n case 'O':\n case 'o':\n case 'd':\n case 's':\n case 'i':\n case 'c':\n ++argumentsPointer\n template += `%${nextChar}`\n break\n default:\n template += `%${nextChar}`\n }\n }\n }\n\n for (\n argumentsPointer;\n argumentsPointer < inputArgs.length;\n ++argumentsPointer\n ) {\n const arg = inputArgs[argumentsPointer]\n const argType = typeof arg\n if (argumentsPointer > 0) {\n template += ' '\n }\n switch (argType) {\n case 'boolean':\n case 'string':\n template += '%s'\n break\n case 'bigint':\n template += '%s'\n break\n case 'number':\n if (arg % 0) {\n template += '%f'\n } else {\n template += '%d'\n }\n break\n case 'object':\n template += '%O'\n break\n case 'symbol':\n case 'undefined':\n case 'function':\n template += '%s'\n break\n default:\n // deopt to string for new, unknown types\n template += '%s'\n }\n }\n\n template += '\\x1b[22m'\n\n return [dim(`%c${template}`), dimStyle, ...newArgs]\n}\n\nfunction convertToDimmedArgs(\n methodName: InterceptableConsoleMethod,\n args: any[]\n): any[] {\n // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely.\n // Dimming wraps arguments in a format string which defeats inspector\n // affordances such as collapsible objects and clickable/linkified stack\n // traces. Ideally we would only skip dimming when a debugger frontend is\n // actually attached, but Node.js does not expose a synchronous API for that.\n // Detecting would require async polling of the /json/list HTTP endpoint.\n if (inspector.url() !== undefined) {\n return args\n }\n\n switch (methodName) {\n case 'dir':\n case 'dirxml':\n case 'group':\n case 'groupCollapsed':\n case 'groupEnd':\n case 'table': {\n // These methods cannot be colorized because they don't take a formatting string.\n return args\n }\n case 'assert': {\n // assert takes formatting options as the second argument.\n return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))\n }\n case 'error':\n case 'debug':\n case 'info':\n case 'log':\n case 'trace':\n case 'warn':\n return dimmedConsoleArgs(args[0], ...args.slice(1))\n default:\n return methodName satisfies never\n }\n}\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethod(methodName: InterceptableConsoleMethod): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n const wrapperMethod = function (this: typeof console, ...args: any[]) {\n const consoleStore = consoleAsyncStorage.getStore()\n\n // First we see if there is a cache signal for our current scope. If we're in a client render it'll\n // come from the client React cacheSignal implementation. If we are in a server render it'll come from\n // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither\n // scope and these signals return null if you are out of scope so this can be called from a single global patch\n // and still work properly.\n const signal =\n getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()\n if (signal) {\n // We are in a React Server render and can consult the React cache signal to determine if logs\n // are now dimmable.\n if (signal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n }\n\n // We need to fall back to checking the work unit store for two reasons.\n // 1. Client React does not yet implement cacheSignal (it always returns null)\n // 2. route.ts files aren't rendered with React but do have prerender semantics\n // TODO in the future we should be able to remove this once there is a runnable cache\n // scope independent of actual React rendering.\n const workUnitStore = workUnitAsyncStorage.getStore()\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // These can be hit in a route handler. In the future we can use potential React.createCache API\n // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.\n // fallthrough\n case 'prerender-client':\n case 'validation-client': {\n // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.\n const renderSignal = workUnitStore.renderSignal\n if (renderSignal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n }\n }\n // intentional fallthrough\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n case 'request':\n case 'generate-static-params':\n case undefined:\n if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n default:\n workUnitStore satisfies never\n }\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\nfunction applyWithDimming<F extends (this: Console, ...args: any[]) => any>(\n this: Console,\n consoleStore: undefined | ConsoleStore,\n method: F,\n methodName: InterceptableConsoleMethod,\n args: Parameters<F>\n): ReturnType<F> {\n if (consoleStore?.dim === true) {\n return method.apply(this, convertToDimmedArgs(methodName, args))\n } else {\n return consoleAsyncStorage.run(\n DIMMED_STORE,\n method.bind(this, ...convertToDimmedArgs(methodName, args))\n )\n }\n}\n\nconst DIMMED_STORE = { dim: true }\n\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["setAbortedLogsStyle","DIMMED_STYLE","HIDDEN_STYLE","currentAbortedLogsStyle","style","isColorSupported","dim","dimStyle","reactBadgeFormat","dimmedConsoleArgs","inputArgs","newArgs","slice","template","argumentsPointer","originalTemplateString","splice","i","startsWith","length","currentChar","nextChar","arg","argType","convertToDimmedArgs","methodName","args","inspector","url","undefined","concat","patchConsoleMethod","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","getClientReact","getServerReact","consoleStore","consoleAsyncStorage","getStore","signal","cacheSignal","aborted","applyWithDimming","call","apply","workUnitStore","workUnitAsyncStorage","type","renderSignal","defineProperty","method","run","DIMMED_STORE","bind"],"mappings":";;;;+BAgBgBA;;;eA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BA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/node-environment-extensions/console-dim.external.tsx"],"sourcesContent":["import * as inspector from 'node:inspector'\nimport { dim } from '../../lib/picocolors'\nimport {\n consoleAsyncStorage,\n type ConsoleStore,\n} from '../app-render/console-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value\nconst DIMMED_STYLE = 'dimmed'\nconst HIDDEN_STYLE = 'hidden'\n\ntype LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE\n\nlet currentAbortedLogsStyle: LogStyle = 'dimmed'\nexport function setAbortedLogsStyle(style: LogStyle) {\n currentAbortedLogsStyle = style\n}\n\ntype InterceptableConsoleMethod =\n | 'error'\n | 'assert'\n | 'debug'\n | 'dir'\n | 'dirxml'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'info'\n | 'log'\n | 'table'\n | 'trace'\n | 'warn'\n\nconst isColorSupported = dim('test') !== 'test'\n\n// 50% opacity for dimmed text\nconst dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'\nconst reactBadgeFormat = '\\x1b[0m\\x1b[7m%c%s\\x1b[0m%c '\n\nfunction dimmedConsoleArgs(...inputArgs: any[]): any[] {\n if (!isColorSupported) {\n return inputArgs\n }\n\n const newArgs = inputArgs.slice(0)\n let template = ''\n let argumentsPointer = 0\n if (typeof inputArgs[0] === 'string') {\n const originalTemplateString = inputArgs[0]\n // Remove the original template string from the args.\n newArgs.splice(argumentsPointer, 1)\n argumentsPointer += 1\n\n let i = 0\n if (originalTemplateString.startsWith(reactBadgeFormat)) {\n i = reactBadgeFormat.length\n // for `format` we already moved the pointer earlier\n // style, badge, reset style\n argumentsPointer += 3\n template += reactBadgeFormat\n // React's badge reset styles, reapply dimming\n template += '\\x1b[2m%c'\n // argumentsPointer includes template\n newArgs.splice(argumentsPointer - 1, 0, dimStyle)\n // dim the badge\n newArgs[0] += `;${dimStyle}`\n }\n\n for (i; i < originalTemplateString.length; i++) {\n const currentChar = originalTemplateString[i]\n if (currentChar !== '%') {\n template += currentChar\n continue\n }\n\n const nextChar = originalTemplateString[i + 1]\n ++i\n\n switch (nextChar) {\n case 'f':\n case 'O':\n case 'o':\n case 'd':\n case 's':\n case 'i':\n case 'c':\n ++argumentsPointer\n template += `%${nextChar}`\n break\n default:\n template += `%${nextChar}`\n }\n }\n }\n\n for (\n argumentsPointer;\n argumentsPointer < inputArgs.length;\n ++argumentsPointer\n ) {\n const arg = inputArgs[argumentsPointer]\n const argType = typeof arg\n if (argumentsPointer > 0) {\n template += ' '\n }\n switch (argType) {\n case 'boolean':\n case 'string':\n template += '%s'\n break\n case 'bigint':\n template += '%s'\n break\n case 'number':\n if (arg % 0) {\n template += '%f'\n } else {\n template += '%d'\n }\n break\n case 'object':\n template += '%O'\n break\n case 'symbol':\n case 'undefined':\n case 'function':\n template += '%s'\n break\n default:\n // deopt to string for new, unknown types\n template += '%s'\n }\n }\n\n template += '\\x1b[22m'\n\n return [dim(`%c${template}`), dimStyle, ...newArgs]\n}\n\nfunction convertToDimmedArgs(\n methodName: InterceptableConsoleMethod,\n args: any[]\n): any[] {\n // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely.\n // Dimming wraps arguments in a format string which defeats inspector\n // affordances such as collapsible objects and clickable/linkified stack\n // traces. Ideally we would only skip dimming when a debugger frontend is\n // actually attached, but Node.js does not expose a synchronous API for that.\n // Detecting would require async polling of the /json/list HTTP endpoint.\n if (inspector.url() !== undefined) {\n return args\n }\n\n switch (methodName) {\n case 'dir':\n case 'dirxml':\n case 'group':\n case 'groupCollapsed':\n case 'groupEnd':\n case 'table': {\n // These methods cannot be colorized because they don't take a formatting string.\n return args\n }\n case 'assert': {\n // assert takes formatting options as the second argument.\n return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))\n }\n case 'error':\n case 'debug':\n case 'info':\n case 'log':\n case 'trace':\n case 'warn':\n return dimmedConsoleArgs(args[0], ...args.slice(1))\n default:\n return methodName satisfies never\n }\n}\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethod(methodName: InterceptableConsoleMethod): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n const wrapperMethod = function (this: typeof console, ...args: any[]) {\n const consoleStore = consoleAsyncStorage.getStore()\n\n // First we see if there is a cache signal for our current scope. If we're in a client render it'll\n // come from the client React cacheSignal implementation. If we are in a server render it'll come from\n // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither\n // scope and these signals return null if you are out of scope so this can be called from a single global patch\n // and still work properly.\n const signal =\n getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()\n if (signal) {\n // We are in a React Server render and can consult the React cache signal to determine if logs\n // are now dimmable.\n if (signal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n }\n\n // We need to fall back to checking the work unit store for two reasons.\n // 1. Client React does not yet implement cacheSignal (it always returns null)\n // 2. route.ts files aren't rendered with React but do have prerender semantics\n // TODO in the future we should be able to remove this once there is a runnable cache\n // scope independent of actual React rendering.\n const workUnitStore = workUnitAsyncStorage.getStore()\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // These can be hit in a route handler. In the future we can use potential React.createCache API\n // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.\n // fallthrough\n case 'prerender-client':\n case 'validation-client': {\n // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.\n const renderSignal = workUnitStore.renderSignal\n if (renderSignal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n }\n }\n // intentional fallthrough\n case 'prerender-legacy':\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n case 'request':\n case 'generate-static-params':\n case undefined:\n if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n default:\n workUnitStore satisfies never\n }\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\nfunction applyWithDimming<F extends (this: Console, ...args: any[]) => any>(\n this: Console,\n consoleStore: undefined | ConsoleStore,\n method: F,\n methodName: InterceptableConsoleMethod,\n args: Parameters<F>\n): ReturnType<F> {\n if (consoleStore?.dim === true) {\n return method.apply(this, convertToDimmedArgs(methodName, args))\n } else {\n return consoleAsyncStorage.run(\n DIMMED_STORE,\n method.bind(this, ...convertToDimmedArgs(methodName, args))\n )\n }\n}\n\nconst DIMMED_STORE = { dim: true }\n\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["setAbortedLogsStyle","DIMMED_STYLE","HIDDEN_STYLE","currentAbortedLogsStyle","style","isColorSupported","dim","dimStyle","reactBadgeFormat","dimmedConsoleArgs","inputArgs","newArgs","slice","template","argumentsPointer","originalTemplateString","splice","i","startsWith","length","currentChar","nextChar","arg","argType","convertToDimmedArgs","methodName","args","inspector","url","undefined","concat","patchConsoleMethod","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","getClientReact","getServerReact","consoleStore","consoleAsyncStorage","getStore","signal","cacheSignal","aborted","applyWithDimming","call","apply","workUnitStore","workUnitAsyncStorage","type","renderSignal","defineProperty","method","run","DIMMED_STORE","bind"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;uEAhBW;4BACP;6CAIb;8CAC8B;uCACU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE/C,6HAA6H;AAC7H,MAAMC,eAAe;AACrB,MAAMC,eAAe;AAIrB,IAAIC,0BAAoC;AACjC,SAASH,oBAAoBI,KAAe;IACjDD,0BAA0BC;AAC5B;AAiBA,MAAMC,mBAAmBC,IAAAA,eAAG,EAAC,YAAY;AAEzC,8BAA8B;AAC9B,MAAMC,WAAW;AACjB,MAAMC,mBAAmB;AAEzB,SAASC,kBAAkB,GAAGC,SAAgB;IAC5C,IAAI,CAACL,kBAAkB;QACrB,OAAOK;IACT;IAEA,MAAMC,UAAUD,UAAUE,KAAK,CAAC;IAChC,IAAIC,WAAW;IACf,IAAIC,mBAAmB;IACvB,IAAI,OAAOJ,SAAS,CAAC,EAAE,KAAK,UAAU;QACpC,MAAMK,yBAAyBL,SAAS,CAAC,EAAE;QAC3C,qDAAqD;QACrDC,QAAQK,MAAM,CAACF,kBAAkB;QACjCA,oBAAoB;QAEpB,IAAIG,IAAI;QACR,IAAIF,uBAAuBG,UAAU,CAACV,mBAAmB;YACvDS,IAAIT,iBAAiBW,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AOwB,cAAc,CAAChB,eAAe,QAAQD;QAC/C;QACAP,OAAOwB,cAAc,CAACtB,SAASV,YAAY;YACzCa,OAAOG;QACT;IACF;AACF;AAEA,SAASS,iBAEPN,YAAsC,EACtCc,MAAS,EACTjC,UAAsC,EACtCC,IAAmB;IAEnB,IAAIkB,CAAAA,gCAAAA,aAActC,GAAG,MAAK,MAAM;QAC9B,OAAOoD,OAAON,KAAK,CAAC,IAAI,EAAE5B,oBAAoBC,YAAYC;IAC5D,OAAO;QACL,OAAOmB,gDAAmB,CAACc,GAAG,CAC5BC,cACAF,OAAOG,IAAI,CAAC,IAAI,KAAKrC,oBAAoBC,YAAYC;IAEzD;AACF;AAEA,MAAMkC,eAAe;IAAEtD,KAAK;AAAK;AAEjCyB,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB","ignoreList":[0]}

@@ -90,3 +90,2 @@ "use strict";

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -93,0 +92,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/node-environment-extensions/io-utils.tsx"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport {\n createSyncIOClientError,\n createSyncIOError,\n createSyncIORuntimeError,\n type SyncIOApiType,\n} from '../app-render/sync-io-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function io(expression: string, type: SyncIOApiType) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const workStore = workAsyncStorage.getStore()\n\n if (!workUnitStore || !workStore) {\n return\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(createSyncIOError(workStore.route, expression, type)),\n workUnitStore\n )\n }\n break\n }\n case 'prerender-client': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(\n createSyncIOClientError(workStore.route, expression, type)\n ),\n workUnitStore\n )\n }\n break\n }\n case 'request': {\n const stageController = workUnitStore.stagedRendering\n if (stageController && stageController.shouldTrackSyncInterrupt()) {\n let syncIOError: Error\n // NOTE: keep stages where we can interrupt in sync with\n // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`\n switch (stageController.currentStage) {\n case RenderStage.ShellStatic:\n case RenderStage.Static: {\n syncIOError = createSyncIOError(workStore.route, expression, type)\n break\n }\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n // We're in the Runtime stage.\n // We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.\n syncIOError = createSyncIORuntimeError(\n workStore.route,\n expression,\n type\n )\n break\n }\n case RenderStage.Before:\n case RenderStage.Dynamic:\n case RenderStage.Abandoned: {\n throw new InvariantError(\n `shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${RenderStage[stageController.currentStage]}`\n )\n }\n }\n\n syncIOError = applyOwnerStack(syncIOError)\n stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n // A validation render uses a 'request' store type, but may be abortable.\n // If we're rendering with filled caches, Sync IO is an error and should trigger an abort.\n if (\n workUnitStore.controller &&\n !workUnitStore.controller.signal.aborted\n ) {\n workUnitStore.controller.abort(syncIOError)\n }\n }\n break\n }\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n}\n"],"names":["io","expression","type","workUnitStore","workUnitAsyncStorage","getStore","workStore","workAsyncStorage","prerenderSignal","controller","signal","aborted","abortOnSynchronousPlatformIOAccess","route","applyOwnerStack","createSyncIOError","createSyncIOClientError","stageController","stagedRendering","shouldTrackSyncInterrupt","syncIOError","currentStage","RenderStage","ShellStatic","Static","ShellRuntime","Runtime","createSyncIORuntimeError","Before","Dynamic","Abandoned","InvariantError","syncInterruptCurrentStageWithReason","abort"],"mappings":";;;;+BAagBA;;;eAAAA;;;0CAbiB;8CACI;kCACc;iCACvB;uCACI;gCAMzB;gCACwB;AAExB,SAASA,GAAGC,UAAkB,EAAEC,IAAmB;IACxD,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IACnD,MAAMC,YAAYC,0CAAgB,CAACF,QAAQ;IAE3C,IAAI,CAACF,iBAAiB,CAACG,WAAW;QAChC;IACF;IAEA,OAAQH,cAAcD,IAAI;QACxB,KAAK;QACL,KAAK;YAAqB;gBACxB,MAAMM,kBAAkBL,cAAcM,UAAU,CAACC,MAAM;gBAEvD,IAAIF,gBAAgBG,OAAO,KAAK,OAAO;oBACrC,wEAAwE;oBACxE,uEAAuE;oBACvEC,IAAAA,oDAAkC,EAChCN,UAAUO,KAAK,EACfZ,YACAa,IAAAA,sCAAe,EAACC,IAAAA,iCAAiB,EAACT,UAAUO,KAAK,EAAEZ,YAAYC,QAC/DC;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBACvB,MAAMK,kBAAkBL,cAAcM,UAAU,CAACC,MAAM;gBAEvD,IAAIF,gBAAgBG,OAAO,KAAK,OAAO;oBACrC,wEAAwE;oBACxE,uEAAuE;oBACvEC,IAAAA,oDAAkC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;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEjB;IACJ;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/node-environment-extensions/io-utils.tsx"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport {\n createSyncIOClientError,\n createSyncIOError,\n createSyncIORuntimeError,\n type SyncIOApiType,\n} from '../app-render/sync-io-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function io(expression: string, type: SyncIOApiType) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const workStore = workAsyncStorage.getStore()\n\n if (!workUnitStore || !workStore) {\n return\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(createSyncIOError(workStore.route, expression, type)),\n workUnitStore\n )\n }\n break\n }\n case 'prerender-client': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(\n createSyncIOClientError(workStore.route, expression, type)\n ),\n workUnitStore\n )\n }\n break\n }\n case 'request': {\n const stageController = workUnitStore.stagedRendering\n if (stageController && stageController.shouldTrackSyncInterrupt()) {\n let syncIOError: Error\n // NOTE: keep stages where we can interrupt in sync with\n // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`\n switch (stageController.currentStage) {\n case RenderStage.ShellStatic:\n case RenderStage.Static: {\n syncIOError = createSyncIOError(workStore.route, expression, type)\n break\n }\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n // We're in the Runtime stage.\n // We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.\n syncIOError = createSyncIORuntimeError(\n workStore.route,\n expression,\n type\n )\n break\n }\n case RenderStage.Before:\n case RenderStage.Dynamic:\n case RenderStage.Abandoned: {\n throw new InvariantError(\n `shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${RenderStage[stageController.currentStage]}`\n )\n }\n }\n\n syncIOError = applyOwnerStack(syncIOError)\n stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n // A validation render uses a 'request' store type, but may be abortable.\n // If we're rendering with filled caches, Sync IO is an error and should trigger an abort.\n if (\n workUnitStore.controller &&\n !workUnitStore.controller.signal.aborted\n ) {\n workUnitStore.controller.abort(syncIOError)\n }\n }\n break\n }\n case 'validation-client':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n}\n"],"names":["io","expression","type","workUnitStore","workUnitAsyncStorage","getStore","workStore","workAsyncStorage","prerenderSignal","controller","signal","aborted","abortOnSynchronousPlatformIOAccess","route","applyOwnerStack","createSyncIOError","createSyncIOClientError","stageController","stagedRendering","shouldTrackSyncInterrupt","syncIOError","currentStage","RenderStage","ShellStatic","Static","ShellRuntime","Runtime","createSyncIORuntimeError","Before","Dynamic","Abandoned","InvariantError","syncInterruptCurrentStageWithReason","abort"],"mappings":";;;;+BAagBA;;;eAAAA;;;0CAbiB;8CACI;kCACc;iCACvB;uCACI;gCAMzB;gCACwB;AAExB,SAASA,GAAGC,UAAkB,EAAEC,IAAmB;IACxD,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IACnD,MAAMC,YAAYC,0CAAgB,CAACF,QAAQ;IAE3C,IAAI,CAACF,iBAAiB,CAACG,WAAW;QAChC;IACF;IAEA,OAAQH,cAA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Q,SAAS;4BAAE;gCAC1B,MAAM,qBAEL,CAFK,IAAIC,8BAAc,CACtB,CAAC,6EAA6E,EAAET,4BAAW,CAACL,gBAAgBI,YAAY,CAAC,EAAE,GADvH,qBAAA;2CAAA;gDAAA;kDAAA;gCAEN;4BACF;oBACF;oBAEAD,cAAcN,IAAAA,sCAAe,EAACM;oBAC9BH,gBAAgBe,mCAAmC,CAACZ;oBAEpD,yEAAyE;oBACzE,0FAA0F;oBAC1F,IACEjB,cAAcM,UAAU,IACxB,CAACN,cAAcM,UAAU,CAACC,MAAM,CAACC,OAAO,EACxC;wBACAR,cAAcM,UAAU,CAACwB,KAAK,CAACb;oBACjC;gBACF;gBACA;YACF;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEjB;IACJ;AACF","ignoreList":[0]}

@@ -10,7 +10,7 @@ /**

* Registers the Next.js unhandled rejection listener, which logs unhandled
* rejections (except React postpones) and prevents them from crashing the
* process. Safe to call unconditionally: if the listener is already attached,
* this is a no-op, so it never registers a duplicate.
* rejections and prevents them from crashing the process. Safe to call
* unconditionally: if the listener is already attached, this is a no-op, so it
* never registers a duplicate.
*/
export declare function registerUnhandledRejectionListener(): void;
export declare function installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners: boolean): void;

@@ -27,3 +27,2 @@ "use strict";

});
const _ispostpone = require("../lib/router-utils/is-postpone");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));

@@ -77,7 +76,2 @@ function _getRequireWildcardCache(nodeInterop) {

function unhandledRejectionListener(reason) {
if ((0, _ispostpone.isPostpone)(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return;
}
// Immediately log the error.

@@ -158,5 +152,2 @@ // TODO: Ideally, if we knew that this error was triggered by application

process.on('uncaughtException', (reason)=>{
if ((0, _ispostpone.isPostpone)(reason)) {
return;
}
console.error(reason);

@@ -163,0 +154,0 @@ });

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/node-environment-extensions/process-error-handlers.ts"],"sourcesContent":["import { isPostpone } from '../lib/router-utils/is-postpone'\nimport * as Log from '../../build/output/log'\n\nlet _global = globalThis as typeof globalThis & {\n nextInitializedProcessErrorHandlers?: boolean\n [UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener\n}\n\n// The listener function is shared via globalThis so that multiple copies of\n// this module (e.g. in the pre-compiled server bundle and in a route module\n// bundle) still register and detect a single listener instance.\nconst UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(\n 'next.unhandledRejectionListener'\n)\n\nfunction unhandledRejectionListener(reason: unknown) {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n // Immediately log the error.\n // TODO: Ideally, if we knew that this error was triggered by application\n // code, we would suppress it entirely without logging. We can't reliably\n // detect all of these, but when cacheComponents is enabled, we could suppress\n // at least some of them by waiting to log the error until after all in-\n // progress renders have completed. Then, only log errors for which there\n // was not a corresponding \"rejectionHandled\" event.\n Log.error('unhandledRejection:', reason)\n}\n\n/**\n * Checks if the Next.js unhandled rejection listener is currently attached.\n * This queries the actual process listeners instead of relying on a module\n * global, so it stays accurate even if the listener was removed externally,\n * e.g. via `process.removeAllListeners('unhandledRejection')`.\n */\nexport function isUnhandledRejectionListenerRegistered(): boolean {\n const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]\n\n return (\n listener !== undefined &&\n process.listeners('unhandledRejection').includes(listener)\n )\n}\n\n/**\n * Registers the Next.js unhandled rejection listener, which logs unhandled\n * rejections (except React postpones) and prevents them from crashing the\n * process. Safe to call unconditionally: if the listener is already attached,\n * this is a no-op, so it never registers a duplicate.\n */\nexport function registerUnhandledRejectionListener(): void {\n if (isUnhandledRejectionListenerRegistered()) {\n return\n }\n\n const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=\n unhandledRejectionListener)\n\n process.on('unhandledRejection', listener)\n}\n\nexport function installProcessErrorHandlers(\n shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n if (!_global.nextInitializedProcessErrorHandlers) {\n _global.nextInitializedProcessErrorHandlers = true\n // The conventional wisdom of Node.js and other runtimes is to treat\n // unhandled errors as fatal and exit the process.\n //\n // But Next.js is not a generic JS runtime — it's a specialized runtime for\n // React Server Components.\n //\n // Many unhandled rejections are due to the late-awaiting pattern for\n // prefetching data. In Next.js it's OK to call an async function without\n // immediately awaiting it, to start the request as soon as possible\n // without blocking unncessarily on the result. These can end up\n // triggering an \"unhandledRejection\" if it later turns out that the\n // data is not needed to render the page. Example:\n //\n // const promise = fetchData()\n // const shouldShow = await checkCondition()\n // if (shouldShow) {\n // return <Component promise={promise} />\n // }\n //\n // In this example, `fetchData` is called immediately to start the request\n // as soon as possible, but if `shouldShow` is false, then it will be\n // discarded without unwrapping its result. If it errors, it will trigger\n // an \"unhandledRejection\" event.\n //\n // Ideally, we would suppress these rejections completely without warning,\n // because we don't consider them real errors. (TODO: Currently we do warn.)\n //\n // But regardless of whether we do or don't warn, we definitely shouldn't\n // crash the entire process.\n //\n // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n // prevent the rest of the page from rendering.\n //\n // So, we're going to intentionally override the default error handling\n // behavior of the outer JS runtime to be more forgiving\n\n // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n // This is gated behind an experimental flag until we've considered the impact\n // in various deployment environments. It's possible this may always need to\n // be configurable.\n if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n process.removeAllListeners('uncaughtException')\n process.removeAllListeners('unhandledRejection')\n }\n\n process.on('rejectionHandled', () => {\n // TODO: See note in the unhandledRejection listener above. In the\n // future, we may use the \"rejectionHandled\" event to de-queue an error\n // from being logged.\n })\n\n // Unhandled exceptions are errors triggered by non-async functions, so this\n // is unrelated to the late-awaiting pattern. However, for similar reasons,\n // we still shouldn't crash the process. Just log it.\n process.on('uncaughtException', (reason: unknown) => {\n if (isPostpone(reason)) {\n return\n }\n console.error(reason)\n })\n }\n\n // Register the listener unconditionally, and not only during the guarded\n // initialization above: a previous registration may have been undone by the\n // `removeAllListeners` call of a later `installProcessErrorHandlers` call\n // (or by external code), and registering is a no-op if the listener is\n // still attached.\n registerUnhandledRejectionListener()\n}\n"],"names":["installProcessErrorHandlers","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","_global","globalThis","UNHANDLED_REJECTION_LISTENER_KEY","Symbol","for","unhandledRejectionListener","reason","isPostpone","Log","error","listener","undefined","process","listeners","includes","on","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","console"],"mappings":";;;;;;;;;;;;;;;;IA+DgBA,2BAA2B;eAA3BA;;IA1BAC,sCAAsC;eAAtCA;;IAeAC,kCAAkC;eAAlCA;;;4BApDW;6DACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,IAAIC,UAAUC;AAKd,4EAA4E;AAC5E,4EAA4E;AAC5E,gEAAgE;AAChE,MAAMC,mCAAmCC,OAAOC,GAAG,CACjD;AAGF,SAASC,2BAA2BC,MAAe;IACjD,IAAIC,IAAAA,sBAAU,EAACD,SAAS;QACtB,0EAA0E;QAC1E,qDAAqD;QACrD;IACF;IACA,6BAA6B;IAC7B,yEAAyE;IACzE,yEAAyE;IACzE,8EAA8E;IAC9E,wEAAwE;IACxE,yEAAyE;IACzE,oDAAoD;IACpDE,KAAIC,KAAK,CAAC,uBAAuBH;AACnC;AAQO,SAASR;IACd,MAAMY,WAAWV,OAAO,CAACE,iCAAiC;IAE1D,OACEQ,aAAaC,aACbC,QAAQC,SAAS,CAAC,sBAAsBC,QAAQ,CAACJ;AAErD;AAQO,SAASX;IACd,IAAID,0CAA0C;QAC5C;IACF;IAEA,MAAMY,WAAYV,OAAO,CAACE,iCAAiC,KACzDG;IAEFO,QAAQG,EAAE,CAAC,sBAAsBL;AACnC;AAEO,SAASb,4BACdmB,8CAAuD;IAEvD,IAAI,CAAChB,QAAQiB,mCAAmC,EAAE;QAChDjB,QAAQiB,mCAAmC,GAAG;QAC9C,oEAAoE;QACpE,kDAAkD;QAClD,EAAE;QACF,2EAA2E;QAC3E,2BAA2B;QAC3B,EAAE;QACF,qEAAqE;QACrE,yEAAyE;QACzE,oEAAoE;QACpE,gEAAgE;QAChE,oEAAoE;QACpE,kDAAkD;QAClD,EAAE;QACF,kCAAkC;QAClC,gDAAgD;QAChD,wBAAwB;QACxB,+CAA+C;QAC/C,QAAQ;QACR,EAAE;QACF,0EAA0E;QAC1E,qEAAqE;QACrE,yEAAyE;QACzE,iCAAiC;QACjC,EAAE;QACF,0EAA0E;QAC1E,4EAA4E;QAC5E,EAAE;QACF,yEAAyE;QACzE,4BAA4B;QAC5B,EAAE;QACF,oEAAoE;QACpE,+CAA+C;QAC/C,EAAE;QACF,uEAAuE;QACvE,wDAAwD;QAExD,6EAA6E;QAC7E,8EAA8E;QAC9E,4EAA4E;QAC5E,mBAAmB;QACnB,IAAID,gDAAgD;YAClDJ,QAAQM,kBAAkB,CAAC;YAC3BN,QAAQM,kBAAkB,CAAC;QAC7B;QAEAN,QAAQG,EAAE,CAAC,oBAAoB;QAC7B,kEAAkE;QAClE,uEAAuE;QACvE,qBAAqB;QACvB;QAEA,4EAA4E;QAC5E,2EAA2E;QAC3E,qDAAqD;QACrDH,QAAQG,EAAE,CAAC,qBAAqB,CAACT;YAC/B,IAAIC,IAAAA,sBAAU,EAACD,SAAS;gBACtB;YACF;YACAa,QAAQV,KAAK,CAACH;QAChB;IACF;IAEA,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,uEAAuE;IACvE,kBAAkB;IAClBP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/node-environment-extensions/process-error-handlers.ts"],"sourcesContent":["import * as Log from '../../build/output/log'\n\nlet _global = globalThis as typeof globalThis & {\n nextInitializedProcessErrorHandlers?: boolean\n [UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener\n}\n\n// The listener function is shared via globalThis so that multiple copies of\n// this module (e.g. in the pre-compiled server bundle and in a route module\n// bundle) still register and detect a single listener instance.\nconst UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(\n 'next.unhandledRejectionListener'\n)\n\nfunction unhandledRejectionListener(reason: unknown) {\n // Immediately log the error.\n // TODO: Ideally, if we knew that this error was triggered by application\n // code, we would suppress it entirely without logging. We can't reliably\n // detect all of these, but when cacheComponents is enabled, we could suppress\n // at least some of them by waiting to log the error until after all in-\n // progress renders have completed. Then, only log errors for which there\n // was not a corresponding \"rejectionHandled\" event.\n Log.error('unhandledRejection:', reason)\n}\n\n/**\n * Checks if the Next.js unhandled rejection listener is currently attached.\n * This queries the actual process listeners instead of relying on a module\n * global, so it stays accurate even if the listener was removed externally,\n * e.g. via `process.removeAllListeners('unhandledRejection')`.\n */\nexport function isUnhandledRejectionListenerRegistered(): boolean {\n const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]\n\n return (\n listener !== undefined &&\n process.listeners('unhandledRejection').includes(listener)\n )\n}\n\n/**\n * Registers the Next.js unhandled rejection listener, which logs unhandled\n * rejections and prevents them from crashing the process. Safe to call\n * unconditionally: if the listener is already attached, this is a no-op, so it\n * never registers a duplicate.\n */\nexport function registerUnhandledRejectionListener(): void {\n if (isUnhandledRejectionListenerRegistered()) {\n return\n }\n\n const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=\n unhandledRejectionListener)\n\n process.on('unhandledRejection', listener)\n}\n\nexport function installProcessErrorHandlers(\n shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n if (!_global.nextInitializedProcessErrorHandlers) {\n _global.nextInitializedProcessErrorHandlers = true\n // The conventional wisdom of Node.js and other runtimes is to treat\n // unhandled errors as fatal and exit the process.\n //\n // But Next.js is not a generic JS runtime — it's a specialized runtime for\n // React Server Components.\n //\n // Many unhandled rejections are due to the late-awaiting pattern for\n // prefetching data. In Next.js it's OK to call an async function without\n // immediately awaiting it, to start the request as soon as possible\n // without blocking unncessarily on the result. These can end up\n // triggering an \"unhandledRejection\" if it later turns out that the\n // data is not needed to render the page. Example:\n //\n // const promise = fetchData()\n // const shouldShow = await checkCondition()\n // if (shouldShow) {\n // return <Component promise={promise} />\n // }\n //\n // In this example, `fetchData` is called immediately to start the request\n // as soon as possible, but if `shouldShow` is false, then it will be\n // discarded without unwrapping its result. If it errors, it will trigger\n // an \"unhandledRejection\" event.\n //\n // Ideally, we would suppress these rejections completely without warning,\n // because we don't consider them real errors. (TODO: Currently we do warn.)\n //\n // But regardless of whether we do or don't warn, we definitely shouldn't\n // crash the entire process.\n //\n // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n // prevent the rest of the page from rendering.\n //\n // So, we're going to intentionally override the default error handling\n // behavior of the outer JS runtime to be more forgiving\n\n // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n // This is gated behind an experimental flag until we've considered the impact\n // in various deployment environments. It's possible this may always need to\n // be configurable.\n if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n process.removeAllListeners('uncaughtException')\n process.removeAllListeners('unhandledRejection')\n }\n\n process.on('rejectionHandled', () => {\n // TODO: See note in the unhandledRejection listener above. In the\n // future, we may use the \"rejectionHandled\" event to de-queue an error\n // from being logged.\n })\n\n // Unhandled exceptions are errors triggered by non-async functions, so this\n // is unrelated to the late-awaiting pattern. However, for similar reasons,\n // we still shouldn't crash the process. Just log it.\n process.on('uncaughtException', (reason: unknown) => {\n console.error(reason)\n })\n }\n\n // Register the listener unconditionally, and not only during the guarded\n // initialization above: a previous registration may have been undone by the\n // `removeAllListeners` call of a later `installProcessErrorHandlers` call\n // (or by external code), and registering is a no-op if the listener is\n // still attached.\n registerUnhandledRejectionListener()\n}\n"],"names":["installProcessErrorHandlers","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","_global","globalThis","UNHANDLED_REJECTION_LISTENER_KEY","Symbol","for","unhandledRejectionListener","reason","Log","error","listener","undefined","process","listeners","includes","on","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","console"],"mappings":";;;;;;;;;;;;;;;;IAyDgBA,2BAA2B;eAA3BA;;IA1BAC,sCAAsC;eAAtCA;;IAeAC,kCAAkC;eAAlCA;;;6DA9CK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,IAAIC,UAAUC;AAKd,4EAA4E;AAC5E,4EAA4E;AAC5E,gEAAgE;AAChE,MAAMC,mCAAmCC,OAAOC,GAAG,CACjD;AAGF,SAASC,2BAA2BC,MAAe;IACjD,6BAA6B;IAC7B,yEAAyE;IACzE,yEAAyE;IACzE,8EAA8E;IAC9E,wEAAwE;IACxE,yEAAyE;IACzE,oDAAoD;IACpDC,KAAIC,KAAK,CAAC,uBAAuBF;AACnC;AAQO,SAASR;IACd,MAAMW,WAAWT,OAAO,CAACE,iCAAiC;IAE1D,OACEO,aAAaC,aACbC,QAAQC,SAAS,CAAC,sBAAsBC,QAAQ,CAACJ;AAErD;AAQO,SAASV;IACd,IAAID,0CAA0C;QAC5C;IACF;IAEA,MAAMW,WAAYT,OAAO,CAACE,iCAAiC,KACzDG;IAEFM,QAAQG,EAAE,CAAC,sBAAsBL;AACnC;AAEO,SAASZ,4BACdkB,8CAAuD;IAEvD,IAAI,CAACf,QAAQgB,mCAAmC,EAAE;QAChDhB,QAAQgB,mCAAmC,GAAG;QAC9C,oEAAoE;QACpE,kDAAkD;QAClD,EAAE;QACF,2EAA2E;QAC3E,2BAA2B;QAC3B,EAAE;QACF,qEAAqE;QACrE,yEAAyE;QACzE,oEAAoE;QACpE,gEAAgE;QAChE,oEAAoE;QACpE,kDAAkD;QAClD,EAAE;QACF,kCAAkC;QAClC,gDAAgD;QAChD,wBAAwB;QACxB,+CAA+C;QAC/C,QAAQ;QACR,EAAE;QACF,0EAA0E;QAC1E,qEAAqE;QACrE,yEAAyE;QACzE,iCAAiC;QACjC,EAAE;QACF,0EAA0E;QAC1E,4EAA4E;QAC5E,EAAE;QACF,yEAAyE;QACzE,4BAA4B;QAC5B,EAAE;QACF,oEAAoE;QACpE,+CAA+C;QAC/C,EAAE;QACF,uEAAuE;QACvE,wDAAwD;QAExD,6EAA6E;QAC7E,8EAA8E;QAC9E,4EAA4E;QAC5E,mBAAmB;QACnB,IAAID,gDAAgD;YAClDJ,QAAQM,kBAAkB,CAAC;YAC3BN,QAAQM,kBAAkB,CAAC;QAC7B;QAEAN,QAAQG,EAAE,CAAC,oBAAoB;QAC7B,kEAAkE;QAClE,uEAAuE;QACvE,qBAAqB;QACvB;QAEA,4EAA4E;QAC5E,2EAA2E;QAC3E,qDAAqD;QACrDH,QAAQG,EAAE,CAAC,qBAAqB,CAACR;YAC/BY,QAAQV,KAAK,CAACF;QAChB;IACF;IAEA,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,uEAAuE;IACvE,kBAAkB;IAClBP;AACF","ignoreList":[0]}

@@ -468,3 +468,2 @@ /**

}
case 'prerender-ppr':
case 'prerender-legacy':

@@ -471,0 +470,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/node-environment-extensions/unhandled-rejection.external.tsx"],"sourcesContent":["/**\n * Manages unhandled rejection listeners to intelligently filter rejections\n * from aborted prerenders when cache components are enabled.\n *\n * THE PROBLEM:\n * When we abort prerenders we expect to find numerous unhandled promise rejections due to\n * things like awaiting Request data like `headers()`. The rejections are fine and should\n * not be construed as problematic so we need to avoid the appearance of a problem by\n * omitting them from the logged output.\n *\n * THE STRATEGY:\n * 1. Install a filtering unhandled rejection handler\n * 2. Intercept process event methods to capture new handlers in our internal queue\n * 3. For each rejection, check if it comes from an aborted prerender context\n * 4. If yes, suppress it. If no, delegate to all handlers in our queue\n * 5. This provides precise filtering without time-based windows\n *\n * This ensures we suppress noisy prerender-related rejections while preserving\n * normal error logging for genuine unhandled rejections.\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\nconst MODE:\n | 'enabled'\n | 'debug'\n | 'silent'\n | 'true'\n | 'false'\n | '1'\n | '0'\n | ''\n | string\n | undefined = process.env.NEXT_UNHANDLED_REJECTION_FILTER\n\nlet ENABLE_UHR_FILTER = true\nlet UHR_FILTER_LOG_LEVEL: 'debug' | 'warn' | 'silent' = 'warn'\n\nswitch (MODE) {\n case 'silent':\n UHR_FILTER_LOG_LEVEL = 'silent'\n break\n case 'debug':\n UHR_FILTER_LOG_LEVEL = 'debug'\n break\n case 'false':\n case 'disabled':\n case '0':\n ENABLE_UHR_FILTER = false\n break\n case '':\n case undefined:\n case 'enabled':\n case 'true':\n case '1':\n break\n default:\n if (typeof MODE === 'string') {\n console.error(\n `NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use \"enabled\", \"disabled\", \"silent\", or \"debug\", or omit the environment variable altogether`\n )\n }\n}\n\nlet debug: typeof console.debug | undefined\nlet debugWithTrace: typeof console.debug | undefined\nlet warn: typeof console.warn | undefined\nlet warnWithTrace: typeof console.warn | undefined\n\nswitch (UHR_FILTER_LOG_LEVEL) {\n case 'debug':\n debug = (message: string) =>\n console.log('[Next.js Unhandled Rejection Filter]: ' + message)\n debugWithTrace = (message: string) => {\n console.log(new DebugWithStack(message))\n }\n // Intentional fallthrough\n case 'warn':\n warn = (message: string) => {\n console.warn('[Next.js Unhandled Rejection Filter]: ' + message)\n }\n warnWithTrace = (message: string) => {\n console.warn(new WarnWithStack(message))\n }\n break\n case 'silent':\n default:\n}\n\nclass DebugWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nclass WarnWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nlet didWarnUninstalled = false\nconst warnUninstalledOnce = warn\n ? function warnUninstalledOnce(...args: any[]) {\n if (!didWarnUninstalled) {\n didWarnUninstalled = true\n warn(...args)\n }\n }\n : undefined\n\ntype ListenerMetadata = {\n listener: NodeJS.UnhandledRejectionListener\n once: boolean\n}\n\n// We use a global symbol to detect if the filter has already been installed.\n// If two instances of this module are loaded, each captures the other's handler\n// as an underlying listener, creating mutual recursion that overflows the stack.\n// We error defensively rather than silently degrading.\nconst FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter')\nlet filterInstalled = false\n\n// We store the proxied listeners for unhandled rejections here.\nlet underlyingListeners: Array<NodeJS.UnhandledRejectionListener> = []\n// We store a unique pointer to each event listener registration to track\n// details like whether the listener is a once listener.\nlet listenerMetadata: Array<ListenerMetadata> = []\n\n// These methods are used to restore the original implementations when uninstalling the patch\nlet originalProcessAddListener: typeof process.addListener\nlet originalProcessRemoveListener: typeof process.removeListener\nlet originalProcessOn: typeof process.on\nlet originalProcessOff: typeof process.off\nlet originalProcessPrependListener: typeof process.prependListener\nlet originalProcessOnce: typeof process.once\nlet originalProcessPrependOnceListener: typeof process.prependOnceListener\nlet originalProcessRemoveAllListeners: typeof process.removeAllListeners\nlet originalProcessListeners: typeof process.listeners\n\ntype UnderlyingMethod =\n | typeof originalProcessAddListener\n | typeof originalProcessRemoveListener\n | typeof originalProcessOn\n | typeof originalProcessOff\n | typeof originalProcessPrependListener\n | typeof originalProcessOnce\n | typeof originalProcessPrependOnceListener\n | typeof originalProcessRemoveAllListeners\n | typeof originalProcessListeners\n\n// Some of these base methods call others and we don't want them to call the patched version so we\n// need a way to synchronously disable the patch temporarily.\nlet bypassPatch = false\n\n// This patch ensures that if any patched methods end up calling other methods internally they will\n// bypass the patch during their execution. This is important for removeAllListeners in particular\n// because it calls removeListener internally and we want to ensure it actually clears the listeners\n// from the process queue and not our private queue.\nfunction patchWithoutReentrancy<T extends UnderlyingMethod>(\n original: T,\n patchedImpl: T\n): T {\n // Produce a function which has the correct name\n const patched = {\n [original.name]: function (...args: Parameters<T>) {\n if (bypassPatch) {\n return Reflect.apply(original, process, args)\n }\n\n const previousBypassPatch = bypassPatch\n bypassPatch = true\n try {\n return Reflect.apply(patchedImpl, process, args)\n } finally {\n bypassPatch = previousBypassPatch\n }\n } as any,\n }[original.name]\n\n // Preserve the original toString behavior\n Object.defineProperty(patched, 'toString', {\n value: original.toString.bind(original),\n writable: true,\n configurable: true,\n })\n\n return patched\n}\n\nconst MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'\n\n/**\n * Installs a filtering unhandled rejection handler that intelligently suppresses\n * rejections from aborted prerender contexts.\n *\n * This should be called once during server startup to install the global filter.\n */\nfunction installUnhandledRejectionFilter(): void {\n if ((globalThis as any)[FILTER_INSTALLED_KEY] || filterInstalled) {\n // Already installed by another evaluation of this module in the same\n // process (e.g., Jest's module system re-evaluating an already-loaded\n // module). Safe to skip since the filter is already active.\n return\n }\n\n debug?.('Installing Filter')\n\n // Capture existing handlers\n underlyingListeners = Array.from(process.listeners('unhandledRejection'))\n // We assume all existing handlers are not \"once\"\n listenerMetadata = underlyingListeners.map((l) => ({\n listener: l,\n once: false,\n }))\n\n // Remove all existing handlers\n process.removeAllListeners('unhandledRejection')\n\n // Install our filtering handler\n process.addListener('unhandledRejection', filteringUnhandledRejectionHandler)\n\n // Store the original process methods\n originalProcessAddListener = process.addListener\n originalProcessRemoveListener = process.removeListener\n originalProcessOn = process.on\n originalProcessOff = process.off\n originalProcessPrependListener = process.prependListener\n originalProcessOnce = process.once\n originalProcessPrependOnceListener = process.prependOnceListener\n originalProcessRemoveAllListeners = process.removeAllListeners\n originalProcessListeners = process.listeners\n\n process.addListener = patchWithoutReentrancy(\n originalProcessAddListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessAddListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessAddListener.call(process, event as any, listener)\n } as typeof process.addListener\n )\n\n // Intercept process.removeListener (alias for process.off)\n process.removeListener = patchWithoutReentrancy(\n originalProcessRemoveListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeListener('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessRemoveListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessRemoveListener.call(process, event, listener)\n } as typeof process.removeListener\n )\n\n // If the process.on is referentially process.addListener then share the patched version as well\n if (originalProcessOn === originalProcessAddListener) {\n process.on = process.addListener\n } else {\n process.on = patchWithoutReentrancy(originalProcessOn, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOn.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessOn.call(process, event, listener)\n } as typeof process.on)\n }\n\n // If the process.off is referentially process.addListener then share the patched version as well\n if (originalProcessOff === originalProcessRemoveListener) {\n process.off = process.removeListener\n } else {\n process.off = patchWithoutReentrancy(originalProcessOff, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.off('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessOff.call(process, MACGUFFIN_EVENT as any, listener)\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessOff.call(process, event, listener)\n } as typeof process.off)\n }\n\n // Intercept process.prependListener for handlers that should go first\n process.prependListener = patchWithoutReentrancy(\n originalProcessPrependListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add new handlers to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependListener\n )\n\n // Intercept process.once for one-time handlers\n process.once = patchWithoutReentrancy(originalProcessOnce, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' once-listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOnce.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessOnce.call(process, event, listener)\n } as typeof process.once)\n\n // Intercept process.prependOnceListener for one-time handlers that should go first\n process.prependOnceListener = patchWithoutReentrancy(\n originalProcessPrependOnceListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' once-listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependOnceListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependOnceListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependOnceListener\n )\n\n // Intercept process.removeAllListeners\n process.removeAllListeners = patchWithoutReentrancy(\n originalProcessRemoveAllListeners,\n function (event?: string | symbol) {\n if (event === 'unhandledRejection') {\n // TODO add warning for this case once we stop importing this in test scopes automatically. Currently\n // we pull this file in whenever build/utils.tsx is imported which is not the right layering.\n // The extensions should be loaded from entrypoints like build/index or next-server\n // warnRemoveAllOnce?.(\n // `\\`process.removeAllListeners('unhandledRejection')\\` was called. Next.js maintains the first 'unhandledRejection' listener to filter out unnecessary rejection warnings caused by aborting prerenders early. It is not recommended that you uninstall this behavior, but if you want to you must you can acquire the listener with \\`process.listeners('unhandledRejection')[0]\\` and remove it with \\`process.removeListener('unhandledRejection', listener)\\`.\n\n // You can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\n // You can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n // )\n debugWithTrace?.(\n `Removing all 'unhandledRejection' listeners except for the Next.js filter.`\n )\n\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n return process\n }\n\n // For other specific events, use the original method\n if (event !== undefined) {\n return originalProcessRemoveAllListeners.call(process, event)\n }\n\n // If no event specified (removeAllListeners()), uninstall our patch completely\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeAllListeners()\\` was called. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return originalProcessRemoveAllListeners.call(process)\n } as typeof process.removeAllListeners\n )\n\n // Intercept process.listeners to return our internal handlers for unhandled rejection\n process.listeners = patchWithoutReentrancy(\n originalProcessListeners,\n function (event: string | symbol) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(`Retrieving all 'unhandledRejection' listeners.`)\n return [filteringUnhandledRejectionHandler, ...underlyingListeners]\n }\n return originalProcessListeners.call(process, event as any)\n } as typeof process.listeners\n )\n\n filterInstalled = true\n ;(globalThis as any)[FILTER_INSTALLED_KEY] = true\n}\n\n/**\n * Uninstalls the unhandled rejection filter and restores original process methods.\n * This is called when someone explicitly removes our filtering handler.\n * @internal\n */\nfunction uninstallUnhandledRejectionFilter(): void {\n if (!filterInstalled) {\n warnWithTrace?.(\n 'Unexpected subsequent filter uninstallation. This is a bug in Next.js'\n )\n return\n }\n\n debug?.('Uninstalling Filter')\n\n // Restore original process methods\n process.on = originalProcessOn\n process.addListener = originalProcessAddListener\n process.once = originalProcessOnce\n process.prependListener = originalProcessPrependListener\n process.prependOnceListener = originalProcessPrependOnceListener\n process.removeListener = originalProcessRemoveListener\n process.off = originalProcessOff\n process.removeAllListeners = originalProcessRemoveAllListeners\n process.listeners = originalProcessListeners\n\n // Remove our filtering handler\n process.removeListener(\n 'unhandledRejection',\n filteringUnhandledRejectionHandler\n )\n\n // Re-register all the handlers that were in our internal queue\n for (const meta of listenerMetadata) {\n if (meta.once) {\n process.once('unhandledRejection', meta.listener)\n } else {\n process.addListener('unhandledRejection', meta.listener)\n }\n }\n\n // Reset state\n filterInstalled = false\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n}\n\n/**\n * The filtering handler that decides whether to suppress or delegate unhandled rejections.\n */\nlet handlingRejection = false\n\nfunction filteringUnhandledRejectionHandler(\n reason: any,\n promise: Promise<any>\n): void {\n if (handlingRejection) {\n // An underlying listener synchronously re-emitted 'unhandledRejection'.\n // Re-entering the listener loop would overflow the stack.\n return\n }\n\n const capturedListenerMetadata = Array.from(listenerMetadata)\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'request': {\n const signal = workUnitStore.renderSignal\n if (signal && signal.aborted) {\n // This unhandledRejection is from async work spawned in a now\n // aborted prerender. We don't need to report this.\n return\n }\n break\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n // Not from an aborted prerender, delegate to original handlers\n if (capturedListenerMetadata.length === 0) {\n // We need to log something because the default behavior when there is\n // no event handler installed is to trigger an Unhandled Exception.\n // We don't do that here b/c we don't want to rely on this implicit default\n // to kill the process since it can be disabled by installing a userland listener\n // and you may also choose to run Next.js with args such that unhandled rejections\n // do not automatically terminate the process.\n console.error('Unhandled Rejection:', reason)\n } else {\n handlingRejection = true\n try {\n for (const meta of capturedListenerMetadata) {\n if (meta.once) {\n // This is a once listener. we remove it from our set before we call it\n const index = listenerMetadata.indexOf(meta)\n if (index !== -1) {\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n }\n }\n const listener = meta.listener\n listener(reason, promise)\n }\n } catch (error) {\n // If any handlers error we produce an Uncaught Exception\n setImmediate(() => {\n throw error\n })\n } finally {\n handlingRejection = false\n }\n }\n}\n\n// Install the filter when this module is imported\nif (ENABLE_UHR_FILTER) {\n installUnhandledRejectionFilter()\n}\n"],"names":["MODE","process","env","NEXT_UNHANDLED_REJECTION_FILTER","ENABLE_UHR_FILTER","UHR_FILTER_LOG_LEVEL","undefined","console","error","JSON","stringify","debug","debugWithTrace","warn","warnWithTrace","message","log","DebugWithStack","WarnWithStack","Error","constructor","name","didWarnUninstalled","warnUninstalledOnce","args","FILTER_INSTALLED_KEY","Symbol","for","filterInstalled","underlyingListeners","listenerMetadata","originalProcessAddListener","originalProcessRemoveListener","originalProcessOn","originalProcessOff","originalProcessPrependListener","originalProcessOnce","originalProcessPrependOnceListener","originalProcessRemoveAllListeners","originalProcessListeners","bypassPatch","patchWithoutReentrancy","original","patchedImpl","patched","Reflect","apply","previousBypassPatch","Object","defineProperty","value","toString","bind","writable","configurable","MACGUFFIN_EVENT","installUnhandledRejectionFilter","globalThis","Array","from","listeners","map","l","listener","once","removeAllListeners","addListener","filteringUnhandledRejectionHandler","removeListener","on","off","prependListener","prependOnceListener","event","call","push","uninstallUnhandledRejectionFilter","index","lastIndexOf","splice","unshift","length","meta","handlingRejection","reason","promise","capturedListenerMetadata","workUnitStore","workUnitAsyncStorage","getStore","type","signal","renderSignal","aborted","indexOf","setImmediate"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC;;;;8CAEoC;AAErC,MAAMA,OAUUC,QAAQC,GAAG,CAACC,+BAA+B;AAE3D,IAAIC,oBAAoB;AACxB,IAAIC,uBAAoD;AAExD,OAAQL;IACN,KAAK;QACHK,uBAAuB;QACvB;IACF,KAAK;QACHA,uBAAuB;QACvB;IACF,KAAK;IACL,KAAK;IACL,KAAK;QACHD,oBAAoB;QACpB;IACF,KAAK;IACL,KAAKE;IACL,KAAK;IACL,KAAK;IACL,KAAK;QACH;IACF;QACE,IAAI,OAAON,SAAS,UAAU;YAC5BO,QAAQC,KAAK,CACX,CAAC,2DAA2D,EAAEC,KAAKC,SAAS,CAACV,MAAM,8FAA8F,CAAC;QAEtL;AACJ;AAEA,IAAIW;AACJ,IAAIC;AACJ,IAAIC;AACJ,IAAIC;AAEJ,OAAQT;IACN,KAAK;QACHM,QAAQ,CAACI,UACPR,QAAQS,GAAG,CAAC,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AMvF;YACR;QACF,SAAU;YACR2E,oBAAoB;QACtB;IACF;AACF;AAEA,kDAAkD;AAClD,IAAI/E,mBAAmB;IACrBoD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/node-environment-extensions/unhandled-rejection.external.tsx"],"sourcesContent":["/**\n * Manages unhandled rejection listeners to intelligently filter rejections\n * from aborted prerenders when cache components are enabled.\n *\n * THE PROBLEM:\n * When we abort prerenders we expect to find numerous unhandled promise rejections due to\n * things like awaiting Request data like `headers()`. The rejections are fine and should\n * not be construed as problematic so we need to avoid the appearance of a problem by\n * omitting them from the logged output.\n *\n * THE STRATEGY:\n * 1. Install a filtering unhandled rejection handler\n * 2. Intercept process event methods to capture new handlers in our internal queue\n * 3. For each rejection, check if it comes from an aborted prerender context\n * 4. If yes, suppress it. If no, delegate to all handlers in our queue\n * 5. This provides precise filtering without time-based windows\n *\n * This ensures we suppress noisy prerender-related rejections while preserving\n * normal error logging for genuine unhandled rejections.\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\nconst MODE:\n | 'enabled'\n | 'debug'\n | 'silent'\n | 'true'\n | 'false'\n | '1'\n | '0'\n | ''\n | string\n | undefined = process.env.NEXT_UNHANDLED_REJECTION_FILTER\n\nlet ENABLE_UHR_FILTER = true\nlet UHR_FILTER_LOG_LEVEL: 'debug' | 'warn' | 'silent' = 'warn'\n\nswitch (MODE) {\n case 'silent':\n UHR_FILTER_LOG_LEVEL = 'silent'\n break\n case 'debug':\n UHR_FILTER_LOG_LEVEL = 'debug'\n break\n case 'false':\n case 'disabled':\n case '0':\n ENABLE_UHR_FILTER = false\n break\n case '':\n case undefined:\n case 'enabled':\n case 'true':\n case '1':\n break\n default:\n if (typeof MODE === 'string') {\n console.error(\n `NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use \"enabled\", \"disabled\", \"silent\", or \"debug\", or omit the environment variable altogether`\n )\n }\n}\n\nlet debug: typeof console.debug | undefined\nlet debugWithTrace: typeof console.debug | undefined\nlet warn: typeof console.warn | undefined\nlet warnWithTrace: typeof console.warn | undefined\n\nswitch (UHR_FILTER_LOG_LEVEL) {\n case 'debug':\n debug = (message: string) =>\n console.log('[Next.js Unhandled Rejection Filter]: ' + message)\n debugWithTrace = (message: string) => {\n console.log(new DebugWithStack(message))\n }\n // Intentional fallthrough\n case 'warn':\n warn = (message: string) => {\n console.warn('[Next.js Unhandled Rejection Filter]: ' + message)\n }\n warnWithTrace = (message: string) => {\n console.warn(new WarnWithStack(message))\n }\n break\n case 'silent':\n default:\n}\n\nclass DebugWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nclass WarnWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nlet didWarnUninstalled = false\nconst warnUninstalledOnce = warn\n ? function warnUninstalledOnce(...args: any[]) {\n if (!didWarnUninstalled) {\n didWarnUninstalled = true\n warn(...args)\n }\n }\n : undefined\n\ntype ListenerMetadata = {\n listener: NodeJS.UnhandledRejectionListener\n once: boolean\n}\n\n// We use a global symbol to detect if the filter has already been installed.\n// If two instances of this module are loaded, each captures the other's handler\n// as an underlying listener, creating mutual recursion that overflows the stack.\n// We error defensively rather than silently degrading.\nconst FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter')\nlet filterInstalled = false\n\n// We store the proxied listeners for unhandled rejections here.\nlet underlyingListeners: Array<NodeJS.UnhandledRejectionListener> = []\n// We store a unique pointer to each event listener registration to track\n// details like whether the listener is a once listener.\nlet listenerMetadata: Array<ListenerMetadata> = []\n\n// These methods are used to restore the original implementations when uninstalling the patch\nlet originalProcessAddListener: typeof process.addListener\nlet originalProcessRemoveListener: typeof process.removeListener\nlet originalProcessOn: typeof process.on\nlet originalProcessOff: typeof process.off\nlet originalProcessPrependListener: typeof process.prependListener\nlet originalProcessOnce: typeof process.once\nlet originalProcessPrependOnceListener: typeof process.prependOnceListener\nlet originalProcessRemoveAllListeners: typeof process.removeAllListeners\nlet originalProcessListeners: typeof process.listeners\n\ntype UnderlyingMethod =\n | typeof originalProcessAddListener\n | typeof originalProcessRemoveListener\n | typeof originalProcessOn\n | typeof originalProcessOff\n | typeof originalProcessPrependListener\n | typeof originalProcessOnce\n | typeof originalProcessPrependOnceListener\n | typeof originalProcessRemoveAllListeners\n | typeof originalProcessListeners\n\n// Some of these base methods call others and we don't want them to call the patched version so we\n// need a way to synchronously disable the patch temporarily.\nlet bypassPatch = false\n\n// This patch ensures that if any patched methods end up calling other methods internally they will\n// bypass the patch during their execution. This is important for removeAllListeners in particular\n// because it calls removeListener internally and we want to ensure it actually clears the listeners\n// from the process queue and not our private queue.\nfunction patchWithoutReentrancy<T extends UnderlyingMethod>(\n original: T,\n patchedImpl: T\n): T {\n // Produce a function which has the correct name\n const patched = {\n [original.name]: function (...args: Parameters<T>) {\n if (bypassPatch) {\n return Reflect.apply(original, process, args)\n }\n\n const previousBypassPatch = bypassPatch\n bypassPatch = true\n try {\n return Reflect.apply(patchedImpl, process, args)\n } finally {\n bypassPatch = previousBypassPatch\n }\n } as any,\n }[original.name]\n\n // Preserve the original toString behavior\n Object.defineProperty(patched, 'toString', {\n value: original.toString.bind(original),\n writable: true,\n configurable: true,\n })\n\n return patched\n}\n\nconst MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'\n\n/**\n * Installs a filtering unhandled rejection handler that intelligently suppresses\n * rejections from aborted prerender contexts.\n *\n * This should be called once during server startup to install the global filter.\n */\nfunction installUnhandledRejectionFilter(): void {\n if ((globalThis as any)[FILTER_INSTALLED_KEY] || filterInstalled) {\n // Already installed by another evaluation of this module in the same\n // process (e.g., Jest's module system re-evaluating an already-loaded\n // module). Safe to skip since the filter is already active.\n return\n }\n\n debug?.('Installing Filter')\n\n // Capture existing handlers\n underlyingListeners = Array.from(process.listeners('unhandledRejection'))\n // We assume all existing handlers are not \"once\"\n listenerMetadata = underlyingListeners.map((l) => ({\n listener: l,\n once: false,\n }))\n\n // Remove all existing handlers\n process.removeAllListeners('unhandledRejection')\n\n // Install our filtering handler\n process.addListener('unhandledRejection', filteringUnhandledRejectionHandler)\n\n // Store the original process methods\n originalProcessAddListener = process.addListener\n originalProcessRemoveListener = process.removeListener\n originalProcessOn = process.on\n originalProcessOff = process.off\n originalProcessPrependListener = process.prependListener\n originalProcessOnce = process.once\n originalProcessPrependOnceListener = process.prependOnceListener\n originalProcessRemoveAllListeners = process.removeAllListeners\n originalProcessListeners = process.listeners\n\n process.addListener = patchWithoutReentrancy(\n originalProcessAddListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessAddListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessAddListener.call(process, event as any, listener)\n } as typeof process.addListener\n )\n\n // Intercept process.removeListener (alias for process.off)\n process.removeListener = patchWithoutReentrancy(\n originalProcessRemoveListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeListener('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessRemoveListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessRemoveListener.call(process, event, listener)\n } as typeof process.removeListener\n )\n\n // If the process.on is referentially process.addListener then share the patched version as well\n if (originalProcessOn === originalProcessAddListener) {\n process.on = process.addListener\n } else {\n process.on = patchWithoutReentrancy(originalProcessOn, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOn.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessOn.call(process, event, listener)\n } as typeof process.on)\n }\n\n // If the process.off is referentially process.addListener then share the patched version as well\n if (originalProcessOff === originalProcessRemoveListener) {\n process.off = process.removeListener\n } else {\n process.off = patchWithoutReentrancy(originalProcessOff, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.off('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessOff.call(process, MACGUFFIN_EVENT as any, listener)\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessOff.call(process, event, listener)\n } as typeof process.off)\n }\n\n // Intercept process.prependListener for handlers that should go first\n process.prependListener = patchWithoutReentrancy(\n originalProcessPrependListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add new handlers to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependListener\n )\n\n // Intercept process.once for one-time handlers\n process.once = patchWithoutReentrancy(originalProcessOnce, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' once-listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOnce.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessOnce.call(process, event, listener)\n } as typeof process.once)\n\n // Intercept process.prependOnceListener for one-time handlers that should go first\n process.prependOnceListener = patchWithoutReentrancy(\n originalProcessPrependOnceListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' once-listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependOnceListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependOnceListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependOnceListener\n )\n\n // Intercept process.removeAllListeners\n process.removeAllListeners = patchWithoutReentrancy(\n originalProcessRemoveAllListeners,\n function (event?: string | symbol) {\n if (event === 'unhandledRejection') {\n // TODO add warning for this case once we stop importing this in test scopes automatically. Currently\n // we pull this file in whenever build/utils.tsx is imported which is not the right layering.\n // The extensions should be loaded from entrypoints like build/index or next-server\n // warnRemoveAllOnce?.(\n // `\\`process.removeAllListeners('unhandledRejection')\\` was called. Next.js maintains the first 'unhandledRejection' listener to filter out unnecessary rejection warnings caused by aborting prerenders early. It is not recommended that you uninstall this behavior, but if you want to you must you can acquire the listener with \\`process.listeners('unhandledRejection')[0]\\` and remove it with \\`process.removeListener('unhandledRejection', listener)\\`.\n\n // You can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\n // You can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n // )\n debugWithTrace?.(\n `Removing all 'unhandledRejection' listeners except for the Next.js filter.`\n )\n\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n return process\n }\n\n // For other specific events, use the original method\n if (event !== undefined) {\n return originalProcessRemoveAllListeners.call(process, event)\n }\n\n // If no event specified (removeAllListeners()), uninstall our patch completely\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeAllListeners()\\` was called. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return originalProcessRemoveAllListeners.call(process)\n } as typeof process.removeAllListeners\n )\n\n // Intercept process.listeners to return our internal handlers for unhandled rejection\n process.listeners = patchWithoutReentrancy(\n originalProcessListeners,\n function (event: string | symbol) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(`Retrieving all 'unhandledRejection' listeners.`)\n return [filteringUnhandledRejectionHandler, ...underlyingListeners]\n }\n return originalProcessListeners.call(process, event as any)\n } as typeof process.listeners\n )\n\n filterInstalled = true\n ;(globalThis as any)[FILTER_INSTALLED_KEY] = true\n}\n\n/**\n * Uninstalls the unhandled rejection filter and restores original process methods.\n * This is called when someone explicitly removes our filtering handler.\n * @internal\n */\nfunction uninstallUnhandledRejectionFilter(): void {\n if (!filterInstalled) {\n warnWithTrace?.(\n 'Unexpected subsequent filter uninstallation. This is a bug in Next.js'\n )\n return\n }\n\n debug?.('Uninstalling Filter')\n\n // Restore original process methods\n process.on = originalProcessOn\n process.addListener = originalProcessAddListener\n process.once = originalProcessOnce\n process.prependListener = originalProcessPrependListener\n process.prependOnceListener = originalProcessPrependOnceListener\n process.removeListener = originalProcessRemoveListener\n process.off = originalProcessOff\n process.removeAllListeners = originalProcessRemoveAllListeners\n process.listeners = originalProcessListeners\n\n // Remove our filtering handler\n process.removeListener(\n 'unhandledRejection',\n filteringUnhandledRejectionHandler\n )\n\n // Re-register all the handlers that were in our internal queue\n for (const meta of listenerMetadata) {\n if (meta.once) {\n process.once('unhandledRejection', meta.listener)\n } else {\n process.addListener('unhandledRejection', meta.listener)\n }\n }\n\n // Reset state\n filterInstalled = false\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n}\n\n/**\n * The filtering handler that decides whether to suppress or delegate unhandled rejections.\n */\nlet handlingRejection = false\n\nfunction filteringUnhandledRejectionHandler(\n reason: any,\n promise: Promise<any>\n): void {\n if (handlingRejection) {\n // An underlying listener synchronously re-emitted 'unhandledRejection'.\n // Re-entering the listener loop would overflow the stack.\n return\n }\n\n const capturedListenerMetadata = Array.from(listenerMetadata)\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'request': {\n const signal = workUnitStore.renderSignal\n if (signal && signal.aborted) {\n // This unhandledRejection is from async work spawned in a now\n // aborted prerender. We don't need to report this.\n return\n }\n break\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n // Not from an aborted prerender, delegate to original handlers\n if (capturedListenerMetadata.length === 0) {\n // We need to log something because the default behavior when there is\n // no event handler installed is to trigger an Unhandled Exception.\n // We don't do that here b/c we don't want to rely on this implicit default\n // to kill the process since it can be disabled by installing a userland listener\n // and you may also choose to run Next.js with args such that unhandled rejections\n // do not automatically terminate the process.\n console.error('Unhandled Rejection:', reason)\n } else {\n handlingRejection = true\n try {\n for (const meta of capturedListenerMetadata) {\n if (meta.once) {\n // This is a once listener. we remove it from our set before we call it\n const index = listenerMetadata.indexOf(meta)\n if (index !== -1) {\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n }\n }\n const listener = meta.listener\n listener(reason, promise)\n }\n } catch (error) {\n // If any handlers error we produce an Uncaught Exception\n setImmediate(() => {\n throw error\n })\n } finally {\n handlingRejection = false\n }\n }\n}\n\n// Install the filter when this module is imported\nif (ENABLE_UHR_FILTER) {\n installUnhandledRejectionFilter()\n}\n"],"names":["MODE","process","env","NEXT_UNHANDLED_REJECTION_FILTER","ENABLE_UHR_FILTER","UHR_FILTER_LOG_LEVEL","undefined","console","error","JSON","stringify","debug","debugWithTrace","warn","warnWithTrace","message","log","DebugWithStack","WarnWithStack","Error","constructor","name","didWarnUninstalled","warnUninstalledOnce","args","FILTER_INSTALLED_KEY","Symbol","for","filterInstalled","underlyingListeners","listenerMetadata","originalProcessAddListener","originalProcessRemoveListener","originalProcessOn","originalProcessOff","originalProcessPrependListener","originalProcessOnce","originalProcessPrependOnceListener","originalProcessRemoveAllListeners","originalProcessListeners","bypassPatch","patchWithoutReentrancy","original","patchedImpl","patched","Reflect","apply","previousBypassPatch","Object","defineProperty","value","toString","bind","writable","configurable","MACGUFFIN_EVENT","installUnhandledRejectionFilter","globalThis","Array","from","listeners","map","l","listener","once","removeAllListeners","addListener","filteringUnhandledRejectionHandler","removeListener","on","off","prependListener","prependOnceListener","event","call","push","uninstallUnhandledRejectionFilter","index","lastIndexOf","splice","unshift","length","meta","handlingRejection","reason","promise","capturedListenerMetadata","workUnitStore","workUnitAsyncStorage","getStore","type","signal","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F;IAEA,+DAA+D;IAC/D,IAAID,yBAAyBL,MAAM,KAAK,GAAG;QACzC,sEAAsE;QACtE,mEAAmE;QACnE,2EAA2E;QAC3E,iFAAiF;QACjF,kFAAkF;QAClF,8CAA8C;QAC9C1E,QAAQC,KAAK,CAAC,wBAAwB4E;IACxC,OAAO;QACLD,oBAAoB;QACpB,IAAI;YACF,KAAK,MAAMD,QAAQI,yBAA0B;gBAC3C,IAAIJ,KAAKlB,IAAI,EAAE;oBACb,uEAAuE;oBACvE,MAAMa,QAAQ/C,iBAAiBgE,OAAO,CAACZ;oBACvC,IAAIL,UAAU,CAAC,GAAG;wBAChBhD,oBAAoBkD,MAAM,CAACF,OAAO;wBAClC/C,iBAAiBiD,MAAM,CAACF,OAAO;oBACjC;gBACF;gBACA,MAAMd,WAAWmB,KAAKnB,QAAQ;gBAC9BA,SAASqB,QAAQC;YACnB;QACF,EAAE,OAAO7E,OAAO;YACd,yDAAyD;YACzDuF,aAAa;gBACX,MAAMvF;YACR;QACF,SAAU;YACR2E,oBAAoB;QACtB;IACF;AACF;AAEA,kDAAkD;AAClD,IAAI/E,mBAAmB;IACrBoD;AACF","ignoreList":[0]}

@@ -52,3 +52,2 @@ "use strict";

case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -55,0 +54,0 @@ case 'generate-static-params':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["getCachedImageResponseBody","importOgModule","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","workAsyncStorage","InvariantError","element","options","hangingInputAbortSignal","createHangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","getClientReferenceManifest","prelude","prerenderToNodeStream","signal","filterStackFrame","onError","error","makeDynamicHangingPromise","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","createHash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","createFromNodeStream","Readable","from","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":";;;;+BA+CgBA;;;eAAAA;;;4BA/CS;4BACa;gCAEP;0CACE;8CACI;kCACS;uCACJ;oCAInC;wBAE+B;wBAED;AAMrC,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAoBO,SAASD,2BACdE,IAAuB;IAEvB,OAAO,IAAIC,eAA2B;QACpC,MAAMC,OAAMC,UAAU;YACpB,MAAMC,cAAc,MAAMC,kCAAkCL;YAC5D,IAAII,YAAYE,UAA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CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["getCachedImageResponseBody","importOgModule","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","workAsyncStorage","InvariantError","element","options","hangingInputAbortSignal","createHangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","getClientReferenceManifest","prelude","prerenderToNodeStream","signal","filterStackFrame","onError","error","makeDynamicHangingPromise","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","createHash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","createFromNodeStream","Readable","from","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":";;;;+BA+CgBA;;;eAAAA;;;4BA/CS;4BACa;gCAEP;0CACE;8CACI;kCACS;uCACJ;oCAInC;wBAE+B;wBAED;AAMrC,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAoBO,SAASD,2BACdE,IAAuB;IAEvB,OAAO,IAAIC,eAA2B;QACpC,MAAMC,OAAMC,UAAU;YACpB,MAAMC,cAAc,MAAMC,kCAAkCL;YAC5D,IAAII,YAAYE,UAAU,GAAG,GAAG;gBAC9BH,WAAWI,OAAO,CAAC,IAAIC,WAAWJ;YACpC;YACAD,WAAWM,KAAK;QAClB;IACF;AACF;AAEA,eAAeJ,kCACbL,IAAuB;IAEvB,MAAMU,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;YAGH;QACF,KAAKC;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOC,+BAA+Bf;QACxC;YACE,OAAOU;IACX;IAEA,MAAM,EAAEM,WAAW,EAAEC,eAAe,EAAEC,YAAY,EAAE,GAAGR;IAEvD,IAAI,CAACO,iBAAiB;QACpB,OAAOF,+BAA+Bf;IACxC;IAEA,MAAMmB,YAAYC,0CAAgB,CAACR,QAAQ;IAE3C,IAAI,CAACO,WAAW;QACd,MAAM,qBAEL,CAFK,IAAIE,8BAAc,CACtB,gFADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAM,CAACC,SAASC,QAAQ,GAAGvB;IAE3B,4EAA4E;IAC5E,6EAA6E;IAC7E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,2BAA2B;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EA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAMlD,UAAUuF;IAChB,IAAIvF,QAAQ6F,KAAK,IAAI,cAAc7F,QAAQ6F,KAAK,EAAE;QAChD,OAAO;YACL,GAAG7F,OAAO;YACV6F,OAAO;gBACL,GAAG7F,QAAQ6F,KAAK;gBAChBC,UAAU5C,oBAAoBlD,QAAQ6F,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]}

@@ -101,6 +101,2 @@ "use strict";

}
case 'prerender-ppr':
// We use React's postpone API to interrupt rendering here to create a
// dynamic hole
return (0, _dynamicrendering.postponeWithTracking)(workStore.route, 'connection', workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -107,0 +103,0 @@ // We throw an error here to interrupt prerendering to mark the route

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-ppr':\n // We use React's postpone API to interrupt rendering here to create a\n // dynamic hole\n return postponeWithTracking(\n workStore.route,\n 'connection',\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["connection","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeDynamicHangingPromise","renderSignal","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","throwForMissingRequestStore"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;0CAzBiB;8CAI1B;kCAKA;yCAC+B;uCAI/B;uBAC2C;iCAEtB;gCACG;AAOxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,wVAAwV,CAAC,GAD9W,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,sEAAsE;YACtE,+CAA+C;YAC/C,OAAOC,QAAQC,OAAO,CAACC;QACzB;QAEA,IAAIX,UAAUY,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEb,UAAUO,KAAK,CAAC,sNAAsN,CAAC,GAD5O,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcW,IAAI;gB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BAAA;mCAAA;wCAAA;0CAAA;wBAEN;oBACF;gBACA,KAAK;oBACH,sEAAsE;oBACtE,eAAe;oBACf,OAAOE,IAAAA,sCAAoB,EACzBvB,UAAUO,KAAK,EACf,cACAJ,cAAcqB,eAAe;gBAEjC,KAAK;oBACH,qEAAqE;oBACrE,aAAa;oBACb,OAAOC,IAAAA,kDAAgC,EACrC,cACAzB,WACAG;gBAEJ,KAAK;oBACHuB,IAAAA,iDAA+B,EAACvB;oBAChC,IAAIwB,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;wBAC1C,wEAAwE;wBACxE,8EAA8E;wBAC9E,4EAA4E;wBAC5E,IAAI1B,cAAc2B,gBAAgB,EAAE;4BAClC,OAAO3B,cAAc2B,gBAAgB,CAAChC,UAAU;wBAClD;wBACA,OAAOiC,IAAAA,iDAA0B,EAC/BpB,WACAR,eACA6B,4BAAW,CAACC,OAAO;oBAEvB,OAAO,IAAI9B,cAAc2B,gBAAgB,EAAE;wBACzC,OAAO3B,cAAc2B,gBAAgB,CAAChC,UAAU;oBAClD,OAAO;wBACL,OAAOW,QAAQC,OAAO,CAACC;oBACzB;gBACF;oBACER;YACJ;QACF;IACF;IAEA,yEAAyE;IACzE,8GAA8G;IAC9G,sDAAsD;IACtD+B,IAAAA,yDAA2B,EAACnC;AAC9B","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["connection","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeDynamicHangingPromise","renderSignal","exportName","InvariantError","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","throwForMissingRequestStore"],"mappings":";;;;+BAwBgBA;;;eAAAA;;;0CAxBiB;8CAI1B;kCAIA;yCAC+B;uCAI/B;uBAC2C;iCAEtB;gCACG;AAOxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,wVAAwV,CAAC,GAD9W,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,sEAAsE;YACtE,+CAA+C;YAC/C,OAAOC,QAAQC,OAAO,CAACC;QACzB;QAEA,IAAIX,UAAUY,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEb,UAAUO,KAAK,CAAC,sNAAsN,CAAC,GAD5O,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBA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CAAA;0CAAA;wBAEN;oBACF;gBACA,KAAK;oBACH,qEAAqE;oBACrE,aAAa;oBACb,OAAOE,IAAAA,kDAAgC,EACrC,cACAvB,WACAG;gBAEJ,KAAK;oBACHqB,IAAAA,iDAA+B,EAACrB;oBAChC,IAAIsB,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;wBAC1C,wEAAwE;wBACxE,8EAA8E;wBAC9E,4EAA4E;wBAC5E,IAAIxB,cAAcyB,gBAAgB,EAAE;4BAClC,OAAOzB,cAAcyB,gBAAgB,CAAC9B,UAAU;wBAClD;wBACA,OAAO+B,IAAAA,iDAA0B,EAC/BlB,WACAR,eACA2B,4BAAW,CAACC,OAAO;oBAEvB,OAAO,IAAI5B,cAAcyB,gBAAgB,EAAE;wBACzC,OAAOzB,cAAcyB,gBAAgB,CAAC9B,UAAU;oBAClD,OAAO;wBACL,OAAOW,QAAQC,OAAO,CAACC;oBACzB;gBACF;oBACER;YACJ;QACF;IACF;IAEA,yEAAyE;IACzE,8GAA8G;IAC9G,sDAAsD;IACtD6B,IAAAA,yDAA2B,EAACjC;AAC9B","ignoreList":[0]}

@@ -80,6 +80,2 @@ "use strict";

});
case 'prerender-ppr':
// We need track dynamic access here eagerly to keep continuity with
// how cookies has worked in PPR without cacheComponents.
return (0, _dynamicrendering.postponeWithTracking)(workStore.route, callingExpression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -86,0 +82,0 @@ // We track dynamic access here so we don't need to wrap the cookies

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // We need track dynamic access here eagerly to keep continuity with\n // how cookies has worked in PPR without cacheComponents.\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["cookies","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeHangingCookies","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","areCookiesMutableInCurrentPhase","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","throwForMissingRequestStore","RequestCookiesAdapter","seal","RequestCookies","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","makeRuntimeHangingPromise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;gCA5BT;yBACwB;0CAIxB;8CAMA;kCAKA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAExB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBC;YAC1B,OAAOC,qBAAqBF;QAC9B;QAEA,IAAIT,UAAUY,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEb,UAAUO,KAAK,CAAC,mNAAmN,CAAC,GADzO,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBACH,MAAMC,QAAQ,qBAEb,CAFa,IAAIT,MAChB,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,kVAAkV,CAAC,GADhW,qBAAA;+BAAA;oCAAA;sCAAA;oBAEd;oBACAD,MAAMU,iBAAiB,CAACD,OAAOjB;oBAC/BmB,IAAAA,sCAAe,EAACF;oBAChBf,UAAUkB,wBAAwB,KAAKH;oBACvC,MAAMA;gBACR,KAAK;oBACH,MAAM,qBAEL,CAFK,IAAIT,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,0XAA0X,CAAC,GADhZ,qBAAA;+BAAA;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OAAOiB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASf,8CACPQ,MAAe,EACfnE,KAAyB;IAEzB,OAAO;QACLqE,YAAY;QACZ7B;YACEY,kBAAkBpD,OAAO;YACzB,OAAOsE;QACT;QACA1B,KAAI2B,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPtD,KAAyB,EACzB2E,UAAkB;IAElB,MAAMC,SAAS5E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG6E,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["cookies","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeHangingCookies","exportName","InvariantError","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","areCookiesMutableInCurrentPhase","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","throwForMissingRequestStore","RequestCookiesAdapter","seal","RequestCookies","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","makeRuntimeHangingPromise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BA+BgBA;;;eAAAA;;;gCA3BT;yBACwB;0CAIxB;8CAMA;kCAIA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAExB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,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M,IAAID,MACT,GAAG2E,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}

@@ -53,3 +53,2 @@ "use strict";

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -211,4 +210,2 @@ // Return empty draft mode

});
case 'prerender-ppr':
return (0, _dynamicrendering.postponeWithTracking)(workStore.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -215,0 +212,0 @@ workUnitStore.revalidate = 0;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/draft-mode.ts"],"sourcesContent":["import {\n getDraftModeProviderForCacheScope,\n throwForMissingRequestStore,\n} from '../app-render/work-unit-async-storage.external'\n\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\n\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n applyOwnerStack,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\n\nexport function draftMode(): Promise<DraftMode> {\n const callingExpression = 'draftMode'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n throwForMissingRequestStore(callingExpression)\n }\n\n switch (workUnitStore.type) {\n case 'prerender-runtime': {\n // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'draftMode',\n new DraftMode(workUnitStore.draftMode)\n )\n } else {\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n }\n }\n case 'request':\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside of `\"use cache\"` or `unstable_cache`, draft mode is available if\n // the outmost work unit store is a request store (or a runtime prerender),\n // and if draft mode is enabled.\n const draftModeProvider = getDraftModeProviderForCacheScope(\n workStore,\n workUnitStore\n )\n\n if (draftModeProvider) {\n return createOrGetCachedDraftMode(draftModeProvider, workStore)\n }\n\n // Otherwise, we fall through to providing an empty draft mode.\n // eslint-disable-next-line no-fallthrough\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Return empty draft mode\n return createOrGetCachedDraftMode(null, workStore)\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${callingExpression}()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n\n default:\n return workUnitStore satisfies never\n }\n}\n\nfunction createOrGetCachedDraftMode(\n draftModeProvider: DraftModeProvider | null,\n workStore: WorkStore | undefined\n): Promise<DraftMode> {\n const cacheKey = draftModeProvider ?? NullDraftMode\n const cachedDraftMode = CachedDraftModes.get(cacheKey)\n\n if (cachedDraftMode) {\n return cachedDraftMode\n }\n\n if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {\n const route = workStore?.route\n return createDraftModeWithDevWarnings(draftModeProvider, route)\n } else {\n return Promise.resolve(new DraftMode(draftModeProvider))\n }\n}\n\ninterface CacheLifetime {}\nconst NullDraftMode = {}\nconst CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()\n\nfunction createDraftModeWithDevWarnings(\n underlyingProvider: null | DraftModeProvider,\n route: undefined | string\n): Promise<DraftMode> {\n const instance = new DraftMode(underlyingProvider)\n const promise = Promise.resolve(instance)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'isEnabled':\n warnForSyncAccess(route, `\\`draftMode().${prop}\\``)\n break\n case 'enable':\n case 'disable': {\n warnForSyncAccess(route, `\\`draftMode().${prop}()\\``)\n break\n }\n default: {\n // We only warn for well-defined properties of the draftMode object.\n }\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n return proxiedPromise\n}\n\nclass DraftMode {\n /**\n * @internal - this declaration is stripped via `tsc --stripInternal`\n */\n private readonly _provider: null | DraftModeProvider\n\n constructor(provider: null | DraftModeProvider) {\n this._provider = provider\n }\n get isEnabled() {\n if (this._provider !== null) {\n return this._provider.isEnabled\n }\n return false\n }\n public enable() {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n trackDynamicDraftMode('draftMode().enable()', this.enable)\n if (this._provider !== null) {\n this._provider.enable()\n }\n }\n public disable() {\n trackDynamicDraftMode('draftMode().disable()', this.disable)\n if (this._provider !== null) {\n this._provider.disable()\n }\n }\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createDraftModeAccessError\n)\n\nfunction createDraftModeAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`draftMode()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction trackDynamicDraftMode(expression: string, constructorOpt: Function) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n if (workUnitStore?.phase === 'after') {\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside \\`after()\\`. The enabled status of \\`draftMode()\\` can be read inside \\`after()\\` but you cannot enable or disable \\`draftMode()\\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache': {\n const error = new Error(\n `Route ${workStore.route} used \"${expression}\" inside \"use cache\". The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, constructorOpt)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside a function cached with \\`unstable_cache()\\`. The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n\n case 'prerender':\n case 'prerender-runtime': {\n const error = new Error(\n `Route ${workStore.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n workStore.route,\n expression,\n error,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n workStore.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n workStore.dynamicUsageDescription = expression\n workStore.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n break\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${expression}\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n default:\n workUnitStore satisfies never\n }\n }\n }\n}\n"],"names":["draftMode","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","throwForMissingRequestStore","type","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","DraftMode","createOrGetCachedDraftMode","draftModeProvider","getDraftModeProviderForCacheScope","exportName","InvariantError","Error","route","cacheKey","NullDraftMode","cachedDraftMode","CachedDraftModes","get","process","env","NODE_ENV","isPrefetchRequest","createDraftModeWithDevWarnings","Promise","resolve","WeakMap","underlyingProvider","instance","promise","proxiedPromise","Proxy","target","prop","receiver","warnForSyncAccess","ReflectAdapter","constructor","provider","_provider","isEnabled","enable","trackDynamicDraftMode","disable","createDedupedByCallsiteServerErrorLoggerDev","createDraftModeAccessError","expression","prefix","constructorOpt","phase","dynamicShouldError","StaticGenBailoutError","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","abortAndThrowOnSynchronousRequestDataAccess","postponeWithTracking","dynamicTracking","revalidate","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","trackDynamicDataInDynamicRender"],"mappings":";;;;+BA2BgBA;;;eAAAA;;;8CAxBT;0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,MAAM,qBAEX,CAFW,IAAIC,sCAAkB,CAChC,CAAC,MAAM,EAAElE,UAAUkB,KAAK,CAAC,mDAAmD,EAAEiC,WAAW,6EAA6E,CAAC,GAD7J,qBAAA;+BAAA;oCAAA;sCAAA;oBAEZ;oBACAnD,UAAUmE,uBAAuB,GAAGhB;oBACpCnD,UAAUoE,iBAAiB,GAAGH,IAAII,KAAK;oBAEvC,MAAMJ;gBACR,KAAK;oBACHK,IAAAA,iDAA+B,EAACnE;oBAChC;gBACF,KAAK;oBACH,MAAM,qBAEL,CAFK,IAAIc,MACR,CAAC,MAAM,EAAEjB,UAAUkB,KAAK,CAAC,QAAQ,EAAEiC,WAAW,iNAAiN,CAAC,GAD5P,qBAAA;+BAAA;oCAAA;sCAAA;oBAEN;gBACF;oBACEhD;YACJ;QACF;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/draft-mode.ts"],"sourcesContent":["import {\n getDraftModeProviderForCacheScope,\n throwForMissingRequestStore,\n} from '../app-render/work-unit-async-storage.external'\n\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\n\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n abortAndThrowOnSynchronousRequestDataAccess,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n applyOwnerStack,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\n\nexport function draftMode(): Promise<DraftMode> {\n const callingExpression = 'draftMode'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n throwForMissingRequestStore(callingExpression)\n }\n\n switch (workUnitStore.type) {\n case 'prerender-runtime': {\n // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'draftMode',\n new DraftMode(workUnitStore.draftMode)\n )\n } else {\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n }\n }\n case 'request':\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside of `\"use cache\"` or `unstable_cache`, draft mode is available if\n // the outmost work unit store is a request store (or a runtime prerender),\n // and if draft mode is enabled.\n const draftModeProvider = getDraftModeProviderForCacheScope(\n workStore,\n workUnitStore\n )\n\n if (draftModeProvider) {\n return createOrGetCachedDraftMode(draftModeProvider, workStore)\n }\n\n // Otherwise, we fall through to providing an empty draft mode.\n // eslint-disable-next-line no-fallthrough\n case 'prerender':\n case 'prerender-legacy':\n // Return empty draft mode\n return createOrGetCachedDraftMode(null, workStore)\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${callingExpression}()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n\n default:\n return workUnitStore satisfies never\n }\n}\n\nfunction createOrGetCachedDraftMode(\n draftModeProvider: DraftModeProvider | null,\n workStore: WorkStore | undefined\n): Promise<DraftMode> {\n const cacheKey = draftModeProvider ?? NullDraftMode\n const cachedDraftMode = CachedDraftModes.get(cacheKey)\n\n if (cachedDraftMode) {\n return cachedDraftMode\n }\n\n if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {\n const route = workStore?.route\n return createDraftModeWithDevWarnings(draftModeProvider, route)\n } else {\n return Promise.resolve(new DraftMode(draftModeProvider))\n }\n}\n\ninterface CacheLifetime {}\nconst NullDraftMode = {}\nconst CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()\n\nfunction createDraftModeWithDevWarnings(\n underlyingProvider: null | DraftModeProvider,\n route: undefined | string\n): Promise<DraftMode> {\n const instance = new DraftMode(underlyingProvider)\n const promise = Promise.resolve(instance)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'isEnabled':\n warnForSyncAccess(route, `\\`draftMode().${prop}\\``)\n break\n case 'enable':\n case 'disable': {\n warnForSyncAccess(route, `\\`draftMode().${prop}()\\``)\n break\n }\n default: {\n // We only warn for well-defined properties of the draftMode object.\n }\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n return proxiedPromise\n}\n\nclass DraftMode {\n /**\n * @internal - this declaration is stripped via `tsc --stripInternal`\n */\n private readonly _provider: null | DraftModeProvider\n\n constructor(provider: null | DraftModeProvider) {\n this._provider = provider\n }\n get isEnabled() {\n if (this._provider !== null) {\n return this._provider.isEnabled\n }\n return false\n }\n public enable() {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n trackDynamicDraftMode('draftMode().enable()', this.enable)\n if (this._provider !== null) {\n this._provider.enable()\n }\n }\n public disable() {\n trackDynamicDraftMode('draftMode().disable()', this.disable)\n if (this._provider !== null) {\n this._provider.disable()\n }\n }\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createDraftModeAccessError\n)\n\nfunction createDraftModeAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`draftMode()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction trackDynamicDraftMode(expression: string, constructorOpt: Function) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n if (workUnitStore?.phase === 'after') {\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside \\`after()\\`. The enabled status of \\`draftMode()\\` can be read inside \\`after()\\` but you cannot enable or disable \\`draftMode()\\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache': {\n const error = new Error(\n `Route ${workStore.route} used \"${expression}\" inside \"use cache\". The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, constructorOpt)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside a function cached with \\`unstable_cache()\\`. The enabled status of \\`draftMode()\\` can be read in caches but you must not enable or disable \\`draftMode()\\` inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n\n case 'prerender':\n case 'prerender-runtime': {\n const error = new Error(\n `Route ${workStore.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n workStore.route,\n expression,\n error,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n workStore.dynamicUsageDescription = expression\n workStore.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n break\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`${expression}\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n default:\n workUnitStore satisfies never\n }\n }\n }\n}\n"],"names":["draftMode","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","throwForMissingRequestStore","type","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","DraftMode","createOrGetCachedDraftMode","draftModeProvider","getDraftModeProviderForCacheScope","exportName","InvariantError","Error","route","cacheKey","NullDraftMode","cachedDraftMode","CachedDraftModes","get","process","env","NODE_ENV","isPrefetchRequest","createDraftModeWithDevWarnings","Promise","resolve","WeakMap","underlyingProvider","instance","promise","proxiedPromise","Proxy","target","prop","receiver","warnForSyncAccess","ReflectAdapter","constructor","provider","_provider","isEnabled","enable","trackDynamicDraftMode","disable","createDedupedByCallsiteServerErrorLoggerDev","createDraftModeAccessError","expression","prefix","constructorOpt","phase","dynamicShouldError","StaticGenBailoutError","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","abortAndThrowOnSynchronousRequestDataAccess","revalidate","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","trackDynamicDataInDynamicRender"],"mappings":";;;;+BA0BgBA;;;eAAAA;;;8CAvBT;0CAOA;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,CAAC,GAD7J,qBAAA;+BAAA;oCAAA;sCAAA;oBAEZ;oBACAnD,UAAUiE,uBAAuB,GAAGd;oBACpCnD,UAAUkE,iBAAiB,GAAGH,IAAII,KAAK;oBAEvC,MAAMJ;gBACR,KAAK;oBACHK,IAAAA,iDAA+B,EAACjE;oBAChC;gBACF,KAAK;oBACH,MAAM,qBAEL,CAFK,IAAIc,MACR,CAAC,MAAM,EAAEjB,UAAUkB,KAAK,CAAC,QAAQ,EAAEiC,WAAW,iNAAiN,CAAC,GAD5P,qBAAA;+BAAA;oCAAA;sCAAA;oBAEN;gBACF;oBACEhD;YACJ;QACF;IACF;AACF","ignoreList":[0]}

@@ -69,3 +69,2 @@ "use strict";

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -97,8 +96,2 @@ case 'request':

});
case 'prerender-ppr':
// PPR Prerender (no cacheComponents)
// We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how headers has worked in PPR without cacheComponents.
// TODO consider switching the semantic to throw on property access instead
return (0, _dynamicrendering.postponeWithTracking)(workStore.route, callingExpression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -105,0 +98,0 @@ // Legacy Prerender

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // PPR Prerender (no cacheComponents)\n // We are prerendering with PPR. We need track dynamic access here eagerly\n // to keep continuity with how headers has worked in PPR without cacheComponents.\n // TODO consider switching the semantic to throw on property access instead\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["headers","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingHeaders","HeadersAdapter","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","dynamicShouldError","StaticGenBailoutError","makeHangingHeaders","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","throwForMissingRequestStore","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","makeRuntimeHangingPromise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAuCgBA;;;eAAAA;;;yBApCT;0CAIA;8CAMA;kCAKA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAWxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC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AC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAGyE,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["headers","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingHeaders","HeadersAdapter","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","dynamicShouldError","StaticGenBailoutError","makeHangingHeaders","exportName","InvariantError","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","throwForMissingRequestStore","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","makeRuntimeHangingPromise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAsCgBA;;;eAAAA;;;yBAnCT;0CAIA;8CAMA;kCAIA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAWxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBC,uBAAc,CAACC,IAAI,CAAC,IAAIC,QAAQ,CAAC;YAC3D,OAAOC,qBAAqBJ;QAC9B;QAEA,IAAIN,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBAAS;wBACZ,MAAMC,QAAQ,qBAEb,CAFa,IAAIT,MAChB,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,kVAAkV,CAAC,GADhW,qBAAA;mCAAA;wCAAA;0CAAA;wBAEd;wBACAD,MAAMU,iBAAiB,CAACD,OAAOjB;wBAC/BmB,IAAAA,sCAAe,EAACF;wBAChBf,UAAUkB,wBAAwB,KAAKH;wBACvC,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;QACL+D,YAAY;QACZ9B;YACEW,kBAAkB5C,OAAO;YACzB,OAAOgE;QACT;QACA3B,KAAI4B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQZ,OAAOC,QAAQ,EAAE;gBAC7Ce;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAAStB,yBACP9C,KAAyB,EACzBqE,UAAkB;IAElB,MAAMC,SAAStE,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAGuE,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}

@@ -15,3 +15,2 @@ "use strict";

const _stagedrendering = require("../app-render/staged-rendering");
const _pprremovederror = require("../../shared/lib/ppr-removed-error");
const _utils = require("./utils");

@@ -58,6 +57,2 @@ // A fulfilled thenable that React can unwrap synchronously via `use()` without

return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`io()`');
case 'prerender-ppr':
// Dead code to be removed when we eliminate legacy ppr code
(0, _pprremovederror.throwPrerenderPPRRemovedError)();
break;
case 'cache':

@@ -64,0 +59,0 @@ case 'private-cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'prerender-ppr':\n // Dead code to be removed when we eliminate legacy ppr code\n throwPrerenderPPRRemovedError()\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["io","resolvedIOPromise","Promise","resolve","undefined","status","value","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","type","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","makeDynamicHangingPromise","renderSignal","throwPrerenderPPRRemovedError"],"mappings":";;;;+BA2BgBA;;;eAAAA;;;0CA3BiB;8CACI;uCAI9B;iCACqB;iCACkB;uBACI;AAElD,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAMC,oBAAmCC,QAAQC,OAAO,CAACC;AACvDH,kBAA0BI,MAAM,GAAG;AACnCJ,kBAA0BK,KAAK,GAAGF;AAa7B,SAASJ;IACd,MAAMO,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,aAAaG,eAAe;QAC9B,IAAIA,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MA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sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["io","resolvedIOPromise","Promise","resolve","undefined","status","value","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","type","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","makeDynamicHangingPromise","renderSignal"],"mappings":";;;;+BA0BgBA;;;eAAAA;;;0CA1BiB;8CACI;uCAI9B;iCACqB;uBACsB;AAElD,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAMC,oBAAmCC,QAAQC,OAAO,CAACC;AACvDH,kBAA0BI,MAAM,GAAG;AACnCJ,kBAA0BK,KAAK,GAAGF;AAa7B,SAASJ;IACd,MAAMO,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kD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E;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]}

@@ -38,3 +38,2 @@ "use strict";

const _reflect = require("../web/spec-extension/adapters/reflect");
const _dynamicrendering = require("../app-render/dynamic-rendering");
const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external");

@@ -61,3 +60,2 @@ const _invarianterror = require("../../shared/lib/invariant-error");

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -132,3 +130,2 @@ // Client params don't need additional vary tracking because by the

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -193,3 +190,2 @@ return createStaticPrerenderParams(underlyingParams, null, workStore, workUnitStore, varyParamsAccumulator);

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -278,3 +274,2 @@ return createStaticPrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator);

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -339,14 +334,2 @@ case 'request':

}
case 'prerender-ppr':
{
const fallbackParams = prerenderStore.fallbackRouteParams;
if (fallbackParams) {
for(const key in underlyingParams){
if (fallbackParams.has(key)) {
return makeErroringParams(underlyingParams, fallbackParams, workStore, prerenderStore);
}
}
}
break;
}
case 'prerender-legacy':

@@ -536,45 +519,2 @@ break;

}
function makeErroringParams(underlyingParams, fallbackParams, workStore, prerenderStore) {
const cachedParams = CachedParams.get(underlyingParams);
if (cachedParams) {
return cachedParams;
}
const augmentedUnderlying = {
...underlyingParams
};
// We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(augmentedUnderlying);
CachedParams.set(underlyingParams, promise);
Object.keys(underlyingParams).forEach((prop)=>{
if (_reflectutils.wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
if (fallbackParams.has(prop)) {
Object.defineProperty(augmentedUnderlying, prop, {
get () {
const expression = (0, _reflectutils.describeStringPropertyAccess)('params', prop);
// In most dynamic APIs we also throw if `dynamic = "error"` however
// for params is only dynamic when we're generating a fallback shell
// and even when `dynamic = "error"` we still support generating dynamic
// fallback shells
// TODO remove this comment when cacheComponents is the default since there
// will be no `dynamic = "error"`
if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
(0, _dynamicrendering.postponeWithTracking)(workStore.route, expression, prerenderStore.dynamicTracking);
} else {
// Legacy Prerender
(0, _dynamicrendering.throwToInterruptStaticGeneration)(expression, workStore, prerenderStore);
}
},
enumerable: true
});
}
}
});
return promise;
}
function makeUntrackedParams(underlyingParams) {

@@ -581,0 +521,0 @@ const cachedParams = CachedParams.get(underlyingParams);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsAppShell`.\n const staticParamsStage = workUnitStore.needsAppShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(null, workUnitStore)\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackRouteParams","key","has","makeFallbackParamsHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsAppShell","__NEXT_DEV_SERVER","trackPromiseUsed","trackIncompatibleShellContent","bind","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","undefined","trackFallbackParamsAccessed","store","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","wellKnownProperties","defineProperty","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","enumerable","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAqDgBA,sBAAsB;eAAtBA;;IAwNAC,qCAAqC;eAArCA;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C,SAAS;QACxB+B,KAAIC,MAAM,EAAEC,IAAI,EAAEC,QAAQ;YACxB,IAAI,OAAOD,SAAS,UAAU;gBAC5B,IACE,uEAAuE;gBACvE6B,kBAAkBtF,GAAG,CAACyD,OACtB;oBACA,MAAMoB,aAAaC,IAAAA,0CAA4B,EAAC,UAAUrB;oBAC1D+B,kBAAkBnH,UAAU8B,KAAK,EAAE0E;gBACrC;YACF;YACA,OAAOjB,uBAAc,CAACL,GAAG,CAACC,QAAQC,MAAMC;QAC1C;QACAc,KAAIhB,MAAM,EAAEC,IAAI,EAAEgC,KAAK,EAAE/B,QAAQ;YAC/B,IAAI,OAAOD,SAAS,UAAU;gBAC5B6B,kBAAkBI,MAAM,CAACjC;YAC3B;YACA,OAAOG,uBAAc,CAACY,GAAG,CAAChB,QAAQC,MAAMgC,OAAO/B;QACjD;QACAiC,SAAQnC,MAAM;YACZ,MAAMqB,aAAa;YACnBW,kBAAkBnH,UAAU8B,KAAK,EAAE0E;YACnC,OAAOe,QAAQD,OAAO,CAACnC;QACzB;IACF;AACF;AAEA,MAAMgC,oBAAoBK,IAAAA,qFAA2C,EACnEC;AAGF,SAASA,wBACP3F,KAAyB,EACzB0E,UAAkB;IAElB,MAAMkB,SAAS5F,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIiE,MACT,GAAG2B,OAAO,KAAK,EAAElB,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n workUnitAsyncStorage,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsAppShell`.\n const staticParamsStage = workUnitStore.needsAppShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(null, workUnitStore)\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackRouteParams","key","has","makeFallbackParamsHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticLinkData","delayUntilStage","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsAppShell","__NEXT_DEV_SERVER","trackPromiseUsed","trackIncompatibleShellContent","bind","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","undefined","trackFallbackParamsAccessed","store","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","cachedParams","set","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","forEach","wellKnownProperties","add","expression","describeStringPropertyAccess","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IA8CgBA,sBAAsB;eAAtBA;;IAqNAC,qCAAqC;eAArCA;;IAtIAC,6BAA6B;eAA7BA;;IAaAC,0BAA0B;eAA1BA;;IA6DAC,kCAAkC;eAAlCA;;;0CApMT;4BAMA;yBAEwB;8CASxB;gCACwB;8BAIxB;uCASA;0DACqD;mDAClB;6BAKnC;AAKA,SAASJ,uBACdK,gBAAwB;IAExB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,iEAAiE;gBACjE,yBAAyB;gBACzB,MAAMC,wBAAwB;gBAC9B,OAAOC,4BACLT,kBACA,MACAC,WACAI,eACAG;YAEJ,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIJ,8BAAc,CACtB,mEADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,wEADI,qBAAA;2BAAA;g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AAGqB,OAAO,KAAK,EAAET,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]}

@@ -12,3 +12,2 @@ "use strict";

const _workasyncstorageexternal = require("../app-render/work-async-storage.external");
const _dynamicrendering = require("../app-render/dynamic-rendering");
const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external");

@@ -30,3 +29,2 @@ const _dynamicrenderingutils = require("../dynamic-rendering-utils");

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -99,10 +97,2 @@ {

}
case 'prerender-ppr':
{
const fallbackParams = prerenderStore.fallbackRouteParams;
if (fallbackParams && fallbackParams.size > 0) {
return makeErroringPathname(workStore, prerenderStore.dynamicTracking);
}
break;
}
case 'prerender-legacy':

@@ -116,26 +106,2 @@ break;

}
function makeErroringPathname(workStore, dynamicTracking) {
let reject = null;
const promise = new Promise((_, re)=>{
reject = re;
});
const originalThen = promise.then.bind(promise);
// We instrument .then so that we can generate a tracking event only if you actually
// await this promise, not just that it is created.
promise.then = (onfulfilled, onrejected)=>{
if (reject) {
try {
(0, _dynamicrendering.postponeWithTracking)(workStore.route, 'metadata relative url resolving', dynamicTracking);
} catch (error) {
reject(error);
reject = null;
}
}
return originalThen(onfulfilled, onrejected);
};
// We wrap in a noop proxy to trick the runtime into thinking it
// isn't a native promise (it's not really). This is so that awaiting
// the promise will call the `then` property triggering the lazy postpone
return new Proxy(promise, {});
}
function createRenderPathname(underlyingPathname) {

@@ -142,0 +108,0 @@ return Promise.resolve(underlyingPathname);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n postponeWithTracking,\n type DynamicTrackingState,\n} from '../app-render/dynamic-rendering'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeDynamicHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname only hangs when there are fallback params, and a\n // concrete (ISR-upgraded) prerender resolves it — so this access is\n // fallback-param data for the static-prefetch hint.\n return makeFallbackParamsHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeErroringPathname(workStore, prerenderStore.dynamicTracking)\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction makeErroringPathname<T>(\n workStore: WorkStore,\n dynamicTracking: null | DynamicTrackingState\n): Promise<T> {\n let reject: null | ((reason: unknown) => void) = null\n const promise = new Promise<T>((_, re) => {\n reject = re\n })\n\n const originalThen = promise.then.bind(promise)\n\n // We instrument .then so that we can generate a tracking event only if you actually\n // await this promise, not just that it is created.\n promise.then = (onfulfilled, onrejected) => {\n if (reject) {\n try {\n postponeWithTracking(\n workStore.route,\n 'metadata relative url resolving',\n dynamicTracking\n )\n } catch (error) {\n reject(error)\n reject = null\n }\n }\n return originalThen(onfulfilled, onrejected)\n }\n\n // We wrap in a noop proxy to trick the runtime into thinking it\n // isn't a native promise (it's not really). This is so that awaiting\n // the promise will call the `then` property triggering the lazy postpone\n return new Proxy(promise, {})\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["createServerPathnameForMetadata","underlyingPathname","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createPrerenderPathname","stagedRendering","pathnameStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","delayUntilStage","undefined","isSessionShell","makeDynamicHangingPromise","renderSignal","route","createRenderPathname","throwInvariantForMissingStore","prerenderStore","fallbackParams","fallbackRouteParams","size","makeFallbackParamsHangingPromise","makeErroringPathname","dynamicTracking","Promise","resolve","reject","promise","_","re","originalThen","then","bind","onfulfilled","onrejected","postponeWithTracking","error","Proxy"],"mappings":";;;;+BAwBgBA;;;eAAAA;;;0CArBT;kCAKA;8CAQA;uCAKA;gCACwB;AAExB,SAASA,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLR,oBACAC,WACAI;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAID,8BAAc,CACtB,6EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,4EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,sFADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBAAqB;oBACxB,iEAAiE;oBACjE,kDAAkD;oBAClD,4CAA4C;oBAC5C,sEAAsE;oBACtE,oDAAoD;oBACpD,iEAAiE;oBACjE,MAAM,EAAEK,eAAe,EAAE,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AAmD;IACnDA,QAAQI,IAAI,GAAG,CAACE,aAAaC;QAC3B,IAAIR,QAAQ;YACV,IAAI;gBACFS,IAAAA,sCAAoB,EAClBtC,UAAUiB,KAAK,EACf,mCACAS;YAEJ,EAAE,OAAOa,OAAO;gBACdV,OAAOU;gBACPV,SAAS;YACX;QACF;QACA,OAAOI,aAAaG,aAAaC;IACnC;IAEA,gEAAgE;IAChE,qEAAqE;IACrE,yEAAyE;IACzE,OAAO,IAAIG,MAAMV,SAAS,CAAC;AAC7B;AAEA,SAASZ,qBAAqBnB,kBAA0B;IACtD,OAAO4B,QAAQC,OAAO,CAAC7B;AACzB","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeDynamicHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname only hangs when there are fallback params, and a\n // concrete (ISR-upgraded) prerender resolves it — so this access is\n // fallback-param data for the static-prefetch hint.\n return makeFallbackParamsHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["createServerPathnameForMetadata","underlyingPathname","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createPrerenderPathname","stagedRendering","pathnameStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","delayUntilStage","undefined","isSessionShell","makeDynamicHangingPromise","renderSignal","route","createRenderPathname","throwInvariantForMissingStore","prerenderStore","fallbackParams","fallbackRouteParams","size","makeFallbackParamsHangingPromise","Promise","resolve"],"mappings":";;;;+BAkBgBA;;;eAAAA;;;0CAfT;8CAOA;uCAKA;gCACwB;AAExB,SAASA,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLR,oBACAC,WACAI;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAID,8BAAc,CACtB,6EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,4EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,sFADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBAAqB;oBACxB,iEAAiE;oBACjE,kDAAkD;oBAClD,4CAA4C;oBAC5C,sEAAsE;oBACtE,oDAAoD;oBACpD,iEAAiE;oBACjE,MAAM,EAAEK,eAAe,EAAE,GAAGJ;oBAC5B,IAAII,iBAAiB;wBACnB,MAAMC,gBAAgBC,iDAA0B,CAACC,eAAe;wBAChE,OAAOH,gBAAgBI,eAAe,CACpCH,eACAI,WACAd;oBAEJ,OAAO;wBACL,IAAIK,cAAcU,cAAc,EAAE;4BAChC,OAAOC,IAAAA,gDAAyB,EAC9BX,cAAcY,YAAY,EAC1BhB,UAAUiB,KAAK,EACf;wBAEJ,OAAO;4BACL,OAAOC,qBAAqBnB;wBAC9B;oBACF;gBACF;YACA,KAAK;gBACH,wEAAwE;gBACxE,OAAOmB,qBAAqBnB;YAC9B;gBACEK;QACJ;IACF;IACAe,IAAAA,2DAA6B;AAC/B;AAEA,SAASZ,wBACPR,kBAA0B,EAC1BC,SAAoB,EACpBoB,cAAiE;IAEjE,OAAQA,eAAed,IAAI;QACzB,KAAK;YAAa;gBAChB,MAAMe,iBAAiBD,eAAeE,mBAAmB;gBACzD,IAAID,kBAAkBA,eAAeE,IAAI,GAAG,GAAG;oBAC7C,gEAAgE;oBAChE,oEAAoE;oBACpE,oDAAoD;oBACpD,OAAOC,IAAAA,uDAAgC,EACrCJ,eAAeJ,YAAY,EAC3BhB,UAAUiB,KAAK,EACf,cACAG;gBAEJ;gBACA;YACF;QACA,KAAK;YACH;QACF;YACEA;IACJ;IAEA,qFAAqF;IACrF,OAAOK,QAAQC,OAAO,CAAC3B;AACzB;AAEA,SAASmB,qBAAqBnB,kBAA0B;IACtD,OAAO0B,QAAQC,OAAO,CAAC3B;AACzB","ignoreList":[0]}

@@ -12,7 +12,5 @@ "use strict";

const _invarianterror = require("../../shared/lib/invariant-error");
const _dynamicrendering = require("../app-render/dynamic-rendering");
const _workasyncstorageexternal = require("../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external");
const _dynamicrenderingutils = require("../dynamic-rendering-utils");
const _reflectutils = require("../../shared/lib/utils/reflect-utils");
const _actionasyncstorageexternal = require("../app-render/action-async-storage.external");

@@ -82,3 +80,2 @@ const _varyparams = require("../app-render/vary-params");

case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -146,3 +143,2 @@ {

case 'prerender-legacy':
case 'prerender-ppr':
default:

@@ -161,11 +157,2 @@ }

}
case 'prerender-ppr':
{
// We aren't in a cacheComponents prerender, but the param is a fallback,
// so we need to make an erroring params object which will postpone/error if you access it
if (prerenderStore.fallbackRouteParams && prerenderStore.fallbackRouteParams.has(paramName)) {
return makeErroringRootParamPromise(paramName, workStore, prerenderStore, apiName);
}
break;
}
case 'prerender-legacy':

@@ -184,24 +171,3 @@ {

}
/** Deliberately async -- we want to create a rejected promise, not error synchronously. */ async function makeErroringRootParamPromise(paramName, workStore, prerenderStore, apiName) {
const expression = (0, _reflectutils.describeStringPropertyAccess)(apiName, paramName);
// In most dynamic APIs, we also throw if `dynamic = "error"`.
// However, root params are only dynamic when we're generating a fallback shell,
// and even with `dynamic = "error"` we still support generating dynamic fallback shells.
// TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = "error"`
switch(prerenderStore.type){
case 'prerender-ppr':
{
return (0, _dynamicrendering.postponeWithTracking)(workStore.route, expression, prerenderStore.dynamicTracking);
}
case 'prerender-legacy':
{
return (0, _dynamicrendering.throwToInterruptStaticGeneration)(expression, workStore, prerenderStore);
}
default:
{
prerenderStore;
}
}
}
//# sourceMappingURL=root-params.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStorePPR\n | PrerenderStoreLegacy\n | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-ppr':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n // We aren't in a cacheComponents prerender, but the param is a fallback,\n // so we need to make an erroring params object which will postpone/error if you access it\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeErroringRootParamPromise(\n paramName,\n workStore,\n prerenderStore,\n apiName\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n\n/** Deliberately async -- we want to create a rejected promise, not error synchronously. */\nasync function makeErroringRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,\n apiName: string\n): Promise<ParamValue> {\n const expression = describeStringPropertyAccess(apiName, paramName)\n // In most dynamic APIs, we also throw if `dynamic = \"error\"`.\n // However, root params are only dynamic when we're generating a fallback shell,\n // and even with `dynamic = \"error\"` we still support generating dynamic fallback shells.\n // TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = \"error\"`\n switch (prerenderStore.type) {\n case 'prerender-ppr': {\n return postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n }\n case 'prerender-legacy': {\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n default: {\n prerenderStore satisfies never\n }\n }\n}\n"],"names":["getRootParam","paramName","apiName","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","Error","route","actionStore","actionAsyncStorage","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","accumulateRootVaryParam","prerenderStore","underlyingParams","fallbackRouteParams","has","makeFallbackParamsHangingPromise","renderSignal","makeErroringRootParamPromise","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;gCAzBe;kCAIxB;0CAIA;8CAMA;uCAC0C;8BAEJ;4CACV;4BACK;AAMjC,SAASA,aAAaC,SAAiB;IAC5C,MA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AAiB;gBACpB,OAAO0B,IAAAA,sCAAoB,EACzBvC,UAAUO,KAAK,EACf8B,YACAP,eAAeU,eAAe;YAElC;QACA,KAAK;YAAoB;gBACvB,OAAOC,IAAAA,kDAAgC,EACrCJ,YACArC,WACA8B;YAEJ;QACA;YAAS;gBACPA;YACF;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n"],"names":["getRootParam","paramName","apiName","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","Error","route","actionStore","actionAsyncStorage","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","accumulateRootVaryParam","prerenderStore","underlyingParams","fallbackRouteParams","has","makeFallbackParamsHangingPromise","renderSignal"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;gCAnBe;0CAIxB;8CAKA;uCAC0C;4CAEd;4BACK;AAMjC,SAASA,aAAaC,SAAiB;IAC5C,MAAMC,UAAU,CAAC,6BAA6B,EAAED,UAAU,IAAI,CAAC;IAE/D,MAAME,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAAqD,CAArD,IAAIG,8BAAc,CAAC,CAAC,qBAAqB,EAAEJ,SAAS,GAApD,q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AAiB,EACjBE,SAAoB,EACpB8B,cAAiE,EACjE/B,OAAe;IAEf,OAAQ+B,eAAejB,IAAI;QACzB,KAAK;QACL,KAAK;QACL;IACF;IAEA,MAAMkB,mBAAmBD,eAAehB,UAAU;IAElD,OAAQgB,eAAejB,IAAI;QACzB,KAAK;YAAa;gBAChB,yCAAyC;gBACzC,+DAA+D;gBAC/D,IACEiB,eAAeE,mBAAmB,IAClCF,eAAeE,mBAAmB,CAACC,GAAG,CAACnC,YACvC;oBACA,OAAOoC,IAAAA,uDAAgC,EACrCJ,eAAeK,YAAY,EAC3BnC,UAAUO,KAAK,EACfR,SACA+B;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBAEvB;YACF;QACA;YAAS;gBACPA;YACF;IACF;IAEA,uFAAuF;IACvFD,IAAAA,mCAAuB,EAAC/B;IACxB,OAAOmB,QAAQC,OAAO,CAACa,gBAAgB,CAACjC,UAAU;AACpD","ignoreList":[0]}

@@ -60,3 +60,2 @@ "use strict";

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -117,3 +116,2 @@ return createStaticPrerenderSearchParams(workStore, workUnitStore);

case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -199,3 +197,2 @@ return createStaticPrerenderSearchParams(workStore, workUnitStore);

});
case 'prerender-ppr':
case 'prerender-legacy':

@@ -221,3 +218,2 @@ case 'request':

return makeHangingSearchParams(workStore, prerenderStore);
case 'prerender-ppr':
case 'prerender-legacy':

@@ -399,5 +395,2 @@ // We are in a legacy static generation and need to interrupt the

(0, _utils.throwWithStaticGenerationBailoutErrorWithDynamicError)(workStore.route, expression);
} else if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
(0, _dynamicrendering.postponeWithTracking)(workStore.route, expression, prerenderStore.dynamicTracking);
} else {

@@ -404,0 +397,0 @@ // Legacy Prerender

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStorePPR,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n makePromiseFromTrigger,\n trackRuntimeDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeRuntimeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeRuntimeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // This promise is created for every page whether or not it reads search\n // params, so recording the access at creation would mark every render.\n // The access is tracked in the proxy traps below instead.\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)\n }\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["createPrerenderSearchParamsForClientPage","createSearchParamsFromClient","createServerSearchParamsForMetadata","createServerSearchParamsForServerPage","makeErroringSearchParamsForUseCache","underlyingSearchParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","throwInvariantForMissingStore","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","varyParamsAccumulator","createRuntimePrerenderSearchParams","forceStatic","Promise","resolve","makeRuntimeHangingPromise","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","createVaryingSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","makePromiseFromTrigger","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","trackRuntimeDataAccessed","proxyHandler","target","prop","receiver","hasOwn","ReflectAdapter","originalMethod","args","expression","annotateDynamicAccess","dynamicAccessStore","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","throwWithStaticGenerationBailoutErrorWithDynamicError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","wellKnownProperties","has","throwForSearchParamsAccessInUseCache","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","makeDevtoolsIOAwarePromise","describeStringPropertyAccess","describeHasCheckingStringProperty","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createDedupedByCallsiteServerErrorLoggerDev","createSearchAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAmKgBA,wCAAwC;eAAxCA;;IAjHAC,4BAA4B;eAA5BA;;IAqDAC,mCAAmC;eAAnCA;;IAUAC,qCAAqC;eAArCA;;IA2ZAC,mCAAmC;eAAnCA;;;0CAzgBT;4BAKA;yBAEwB;kCAKxB;mDACmC;8CAYnC;gCACwB;uCAOxB;0DACqD;8BAKrD;uBAIA;AAIA,SAASH,6BACdI,sBAAoC;IAEpC,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAo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MAAMqC,SAAS1F,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAI2D,MACT,GAAG+B,OAAO,KAAK,EAAErC,WAAW,EAAE,CAAC,GAC7B,CAAC,uHAAuH,CAAC,GACzH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF;AAEA,SAASlE,qCACPV,sBAAoC,EACpCC,SAAoB,EACpBI,aAAoC;QAKtBA;IAHd,MAAM,EAAEiD,iCAAiC,EAAE,GACzCC,QAAQ;IACV,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACtD,EAAAA,mCAAAA,cAAcI,iBAAiB,qBAA/BJ,iCAAiCuD,YAAY,KAAI,CAAC;IAEhE5D,yBAAyBsD,kCACvBtD,wBACAwD,cACAvD,UAAUsB,KAAK;IAEjB,OAAOJ,QAAQC,OAAO,CAACpB;AACzB","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n makePromiseFromTrigger,\n trackRuntimeDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeRuntimeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeRuntimeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // This promise is created for every page whether or not it reads search\n // params, so recording the access at creation would mark every render.\n // The access is tracked in the proxy traps below instead.\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)\n }\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["createPrerenderSearchParamsForClientPage","createSearchParamsFromClient","createServerSearchParamsForMetadata","createServerSearchParamsForServerPage","makeErroringSearchParamsForUseCache","underlyingSearchParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","throwInvariantForMissingStore","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","varyParamsAccumulator","createRuntimePrerenderSearchParams","forceStatic","Promise","resolve","makeRuntimeHangingPromise","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","createVaryingSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","makePromiseFromTrigger","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","trackRuntimeDataAccessed","proxyHandler","target","prop","receiver","hasOwn","ReflectAdapter","originalMethod","args","expression","annotateDynamicAccess","dynamicAccessStore","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","throwWithStaticGenerationBailoutErrorWithDynamicError","throwToInterruptStaticGeneration","wellKnownProperties","has","throwForSearchParamsAccessInUseCache","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","makeDevtoolsIOAwarePromise","describeStringPropertyAccess","describeHasCheckingStringProperty","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createDedupedByCallsiteServerErrorLoggerDev","createSearchAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IA+JgBA,wCAAwC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;QAC7B;QACAgC,SAAQjC,MAAM;YACZ,MAAMO,aAAa;YACnB8B,kBAAkBzG,UAAUsB,KAAK,EAAEqD;YACnC,OAAOyB,QAAQC,OAAO,CAACjC;QACzB;IACF;AACF;AAEA,MAAMqC,oBAAoBG,IAAAA,qFAA2C,EACnEC;AAGF,SAASA,wBACPvF,KAAyB,EACzBqD,UAAkB;IAElB,MAAMmC,SAASxF,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAI2D,MACT,GAAG6B,OAAO,KAAK,EAAEnC,WAAW,EAAE,CAAC,GAC7B,CAAC,uHAAuH,CAAC,GACzH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF;AAEA,SAASlE,qCACPV,sBAAoC,EACpCC,SAAoB,EACpBI,aAAoC;QAKtBA;IAHd,MAAM,EAAEiD,iCAAiC,EAAE,GACzCC,QAAQ;IACV,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACtD,EAAAA,mCAAAA,cAAcI,iBAAiB,qBAA/BJ,iCAAiCuD,YAAY,KAAI,CAAC;IAEhE5D,yBAAyBsD,kCACvBtD,wBACAwD,cACAvD,UAAUsB,KAAK;IAEjB,OAAOJ,QAAQC,OAAO,CAACpB;AACzB","ignoreList":[0]}

@@ -969,4 +969,2 @@ "use strict";

});
case 'prerender-ppr':
return (0, _dynamicrendering.postponeWithTracking)(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -973,0 +971,0 @@ workUnitStore.revalidate = 0;

@@ -89,3 +89,3 @@ "use strict";

META: {
// Only the match the prefix cause the suffix can be different wether it's xml compatible or not ">" or "/>"
// Only the match the prefix cause the suffix can be different whether it's xml compatible or not ">" or "/>"
// <meta name="«nxt-icon»"

@@ -92,0 +92,0 @@ // This is a special mark that will be replaced by the icon insertion script tag.

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/stream-utils/encoded-tags.ts"],"sourcesContent":["export const ENCODED_TAGS = {\n // opening tags do not have the closing `>` since they can contain other attributes such as `<body className=''>`\n OPENING: {\n // <html\n HTML: new Uint8Array([60, 104, 116, 109, 108]),\n // <head\n HEAD: new Uint8Array([60, 104, 101, 97, 100]),\n // <body\n BODY: new Uint8Array([60, 98, 111, 100, 121]),\n },\n CLOSED: {\n // </head>\n HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n // </body>\n BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n // </html>\n HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n // </body></html>\n BODY_AND_HTML: new Uint8Array([\n 60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,\n ]),\n },\n META: {\n // Only the match the prefix cause the suffix can be different wether it's xml compatible or not \">\" or \"/>\"\n // <meta name=\"«nxt-icon»\"\n // This is a special mark that will be replaced by the icon insertion script tag.\n ICON_MARK: new Uint8Array([\n 60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,\n 116, 45, 105, 99, 111, 110, 194, 187, 34,\n ]),\n },\n} as const\n"],"names":["ENCODED_TAGS","OPENING","HTML","Uint8Array","HEAD","BODY","CLOSED","BODY_AND_HTML","META","ICON_MARK"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,eAAe;IAC1B,iHAAiH;IACjHC,SAAS;QACP,QAAQ;QACRC,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAK;YAAK;YAAK;SAAI;QAC7C,QAAQ;QACRC,MAAM,IAAID,WAAW;YAAC;YAAI;YAAK;YAAK;YAAI;SAAI;QAC5C,QAAQ;QACRE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;SAAI;IAC9C;IACAG,QAAQ;QACN,UAAU;QACVF,MAAM,IAAID,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAI;YAAK;SAAG;QACpD,UAAU;QACVE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;SAAG;QACpD,UAAU;QACVD,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAAG;QACrD,iBAAiB;QACjBI,eAAe,IAAIJ,WAAW;YAC5B;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAC5D;IACH;IACAK,MAAM;QACJ,4GAA4G;QAC5G,0BAA0B;QAC1B,iFAAiF;QACjFC,WAAW,IAAIN,WAAW;YACxB;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAK;YAAI;YAAK;YAAK;YAAI;YAAI;YAAK;YAAK;YAAK;YACrE;YAAK;YAAI;YAAK;YAAI;YAAK;YAAK;YAAK;YAAK;SACvC;IACH;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/stream-utils/encoded-tags.ts"],"sourcesContent":["export const ENCODED_TAGS = {\n // opening tags do not have the closing `>` since they can contain other attributes such as `<body className=''>`\n OPENING: {\n // <html\n HTML: new Uint8Array([60, 104, 116, 109, 108]),\n // <head\n HEAD: new Uint8Array([60, 104, 101, 97, 100]),\n // <body\n BODY: new Uint8Array([60, 98, 111, 100, 121]),\n },\n CLOSED: {\n // </head>\n HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n // </body>\n BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n // </html>\n HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n // </body></html>\n BODY_AND_HTML: new Uint8Array([\n 60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,\n ]),\n },\n META: {\n // Only the match the prefix cause the suffix can be different whether it's xml compatible or not \">\" or \"/>\"\n // <meta name=\"«nxt-icon»\"\n // This is a special mark that will be replaced by the icon insertion script tag.\n ICON_MARK: new Uint8Array([\n 60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,\n 116, 45, 105, 99, 111, 110, 194, 187, 34,\n ]),\n },\n} as const\n"],"names":["ENCODED_TAGS","OPENING","HTML","Uint8Array","HEAD","BODY","CLOSED","BODY_AND_HTML","META","ICON_MARK"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,eAAe;IAC1B,iHAAiH;IACjHC,SAAS;QACP,QAAQ;QACRC,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAK;YAAK;YAAK;SAAI;QAC7C,QAAQ;QACRC,MAAM,IAAID,WAAW;YAAC;YAAI;YAAK;YAAK;YAAI;SAAI;QAC5C,QAAQ;QACRE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;SAAI;IAC9C;IACAG,QAAQ;QACN,UAAU;QACVF,MAAM,IAAID,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAI;YAAK;SAAG;QACpD,UAAU;QACVE,MAAM,IAAIF,WAAW;YAAC;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;SAAG;QACpD,UAAU;QACVD,MAAM,IAAIC,WAAW;YAAC;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAAG;QACrD,iBAAiB;QACjBI,eAAe,IAAIJ,WAAW;YAC5B;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAI;YAAK;YAAK;YAAK;YAAK;SAC5D;IACH;IACAK,MAAM;QACJ,6GAA6G;QAC7G,0BAA0B;QAC1B,iFAAiF;QACjFC,WAAW,IAAIN,WAAW;YACxB;YAAI;YAAK;YAAK;YAAK;YAAI;YAAI;YAAK;YAAI;YAAK;YAAK;YAAI;YAAI;YAAK;YAAK;YAAK;YACrE;YAAK;YAAI;YAAK;YAAI;YAAK;YAAK;YAAK;YAAK;SACvC;IACH;AACF","ignoreList":[0]}

@@ -28,3 +28,2 @@ "use strict";

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -31,0 +30,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/use-cache/cache-life.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateAndNormalizeCacheLifeProfile } from './cache-life-profile'\nimport type { CacheLife } from './cache-life-profile'\n\nexport type { CacheLife }\n\n// The equivalent header is kind of like:\n// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]\n// Except that stale-while-revalidate/stale-if-error only applies to shared caches - not private caches.\n\n// The default revalidates relatively frequently but doesn't expire to ensure it's always\n// able to serve fast results but by default doesn't hang.\n\n// This gets overridden by the next-types-plugin\ntype CacheLifeProfiles =\n | 'default'\n | 'seconds'\n | 'minutes'\n | 'hours'\n | 'days'\n | 'weeks'\n | 'max'\n | (string & {})\n\nexport function cacheLife(profile: CacheLifeProfiles | CacheLife): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheLife()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheLife()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n if (typeof profile === 'string') {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new Error(\n '`cacheLife()` can only be called during App Router rendering at the moment.'\n )\n }\n\n // TODO: This should be globally available and not require an AsyncLocalStorage.\n const configuredProfile = workStore.cacheLifeProfiles[profile]\n if (configuredProfile === undefined) {\n if (workStore.cacheLifeProfiles[profile.trim()]) {\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n `Did you mean \"${profile.trim()}\" without the spaces?`\n )\n }\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n 'module.exports = {\\n' +\n ' cacheLife: {\\n' +\n ` \"${profile}\": ...\\n` +\n ' }\\n' +\n '}'\n )\n }\n profile = configuredProfile\n } else if (\n typeof profile !== 'object' ||\n profile === null ||\n Array.isArray(profile)\n ) {\n throw new Error(\n 'Invalid `cacheLife()` option. Either pass a profile name or object.'\n )\n } else {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n\n if (profile.revalidate !== undefined) {\n // Track the explicit revalidate time.\n if (\n workUnitStore.explicitRevalidate === undefined ||\n workUnitStore.explicitRevalidate > profile.revalidate\n ) {\n workUnitStore.explicitRevalidate = profile.revalidate\n }\n }\n if (profile.expire !== undefined) {\n // Track the explicit expire time.\n if (\n workUnitStore.explicitExpire === undefined ||\n workUnitStore.explicitExpire > profile.expire\n ) {\n workUnitStore.explicitExpire = profile.expire\n }\n }\n if (profile.stale !== undefined) {\n // Track the explicit stale time.\n if (\n workUnitStore.explicitStale === undefined ||\n workUnitStore.explicitStale > profile.stale\n ) {\n workUnitStore.explicitStale = profile.stale\n }\n }\n}\n"],"names":["cacheLife","profile","process","env","__NEXT_USE_CACHE","Error","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","workStore","workAsyncStorage","configuredProfile","cacheLifeProfiles","trim","Array","isArray","validateAndNormalizeCacheLifeProfile","kind","revalidate","explicitRevalidate","expire","explicitExpire","stale","explicitStale"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;0CAzBiB;8CACI;kCACgB;AAuB9C,SAASA,UAAUC,OAAsC;IAC9D,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,uEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBC,k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YAAEkB,MAAM;QAAS;IAC3E;IAEA,IAAIlB,QAAQmB,UAAU,KAAKV,WAAW;QACpC,sCAAsC;QACtC,IACEJ,cAAce,kBAAkB,KAAKX,aACrCJ,cAAce,kBAAkB,GAAGpB,QAAQmB,UAAU,EACrD;YACAd,cAAce,kBAAkB,GAAGpB,QAAQmB,UAAU;QACvD;IACF;IACA,IAAInB,QAAQqB,MAAM,KAAKZ,WAAW;QAChC,kCAAkC;QAClC,IACEJ,cAAciB,cAAc,KAAKb,aACjCJ,cAAciB,cAAc,GAAGtB,QAAQqB,MAAM,EAC7C;YACAhB,cAAciB,cAAc,GAAGtB,QAAQqB,MAAM;QAC/C;IACF;IACA,IAAIrB,QAAQuB,KAAK,KAAKd,WAAW;QAC/B,iCAAiC;QACjC,IACEJ,cAAcmB,aAAa,KAAKf,aAChCJ,cAAcmB,aAAa,GAAGxB,QAAQuB,KAAK,EAC3C;YACAlB,cAAcmB,aAAa,GAAGxB,QAAQuB,KAAK;QAC7C;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/use-cache/cache-life.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateAndNormalizeCacheLifeProfile } from './cache-life-profile'\nimport type { CacheLife } from './cache-life-profile'\n\nexport type { CacheLife }\n\n// The equivalent header is kind of like:\n// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]\n// Except that stale-while-revalidate/stale-if-error only applies to shared caches - not private caches.\n\n// The default revalidates relatively frequently but doesn't expire to ensure it's always\n// able to serve fast results but by default doesn't hang.\n\n// This gets overridden by the next-types-plugin\ntype CacheLifeProfiles =\n | 'default'\n | 'seconds'\n | 'minutes'\n | 'hours'\n | 'days'\n | 'weeks'\n | 'max'\n | (string & {})\n\nexport function cacheLife(profile: CacheLifeProfiles | CacheLife): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheLife()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheLife()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n if (typeof profile === 'string') {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new Error(\n '`cacheLife()` can only be called during App Router rendering at the moment.'\n )\n }\n\n // TODO: This should be globally available and not require an AsyncLocalStorage.\n const configuredProfile = workStore.cacheLifeProfiles[profile]\n if (configuredProfile === undefined) {\n if (workStore.cacheLifeProfiles[profile.trim()]) {\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n `Did you mean \"${profile.trim()}\" without the spaces?`\n )\n }\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n 'module.exports = {\\n' +\n ' cacheLife: {\\n' +\n ` \"${profile}\": ...\\n` +\n ' }\\n' +\n '}'\n )\n }\n profile = configuredProfile\n } else if (\n typeof profile !== 'object' ||\n profile === null ||\n Array.isArray(profile)\n ) {\n throw new Error(\n 'Invalid `cacheLife()` option. Either pass a profile name or object.'\n )\n } else {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n\n if (profile.revalidate !== undefined) {\n // Track the explicit revalidate time.\n if (\n workUnitStore.explicitRevalidate === undefined ||\n workUnitStore.explicitRevalidate > profile.revalidate\n ) {\n workUnitStore.explicitRevalidate = profile.revalidate\n }\n }\n if (profile.expire !== undefined) {\n // Track the explicit expire time.\n if (\n workUnitStore.explicitExpire === undefined ||\n workUnitStore.explicitExpire > profile.expire\n ) {\n workUnitStore.explicitExpire = profile.expire\n }\n }\n if (profile.stale !== undefined) {\n // Track the explicit stale time.\n if (\n workUnitStore.explicitStale === undefined ||\n workUnitStore.explicitStale > profile.stale\n ) {\n workUnitStore.explicitStale = profile.stale\n }\n }\n}\n"],"names":["cacheLife","profile","process","env","__NEXT_USE_CACHE","Error","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","workStore","workAsyncStorage","configuredProfile","cacheLifeProfiles","trim","Array","isArray","validateAndNormalizeCacheLifeProfile","kind","revalidate","explicitRevalidate","expire","explicitExpire","stale","explicitStale"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;0CAzBiB;8CACI;kCACgB;AAuB9C,SAASA,UAAUC,OAAsC;IAC9D,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,uEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;YACH,MAAM,qBAEL,CAFK,IAAIL,MACR,oEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;QACL,KAAK;YACH;QACF;YACEC;IACJ;IAEA,IAAI,OAAOL,YAAY,UAAU;QAC/B,MAAMU,YAAYC,0CAAgB,CAACJ,QAAQ;QAC3C,IAAI,CAACG,WAAW;YACd,MAAM,qBAEL,CAFK,IAAIN,MACR,gFADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,gFAAgF;QAChF,MAAMQ,oBAAoBF,UAAUG,iBAAiB,CAACb,QAAQ;QAC9D,IAAIY,sBAAsBH,WAAW;YACnC,IAAIC,UAAUG,iBAAiB,CAACb,QAAQc,IAAI,GAAG,EAAE;gBAC/C,MAAM,qBAGL,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+27,2 @@ "use strict";

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -30,0 +29,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/server/use-cache/cache-tag.ts"],"sourcesContent":["import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateTags } from '../lib/patch-fetch'\n\nexport function cacheTag(...tags: string[]): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheTag()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheTag()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n const validTags = validateTags(tags, '`cacheTag()`')\n\n if (!workUnitStore.tags) {\n workUnitStore.tags = validTags\n } else {\n workUnitStore.tags.push(...validTags)\n }\n}\n"],"names":["cacheTag","tags","process","env","__NEXT_USE_CACHE","Error","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","validTags","validateTags","push"],"mappings":";;;;+BAGgBA;;;eAAAA;;;8CAHqB;4BACR;AAEtB,SAASA,SAAS,GAAGC,IAAc;IACxC,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,sEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;YACH,MAAM,qBAEL,CAFK,IAAIL,MACR,mEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;QACL,KAAK;YACH;QACF;YACEC;IACJ;IAEA,MAAMK,YAAYC,IAAAA,wBAAY,EAACX,MAAM;IAErC,IAAI,CAACK,cAAcL,IAAI,EAAE;QACvBK,cAAcL,IAAI,GAAGU;IACvB,OAAO;QACLL,cAAcL,IAAI,CAACY,IAAI,IAAIF;IAC7B;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/server/use-cache/cache-tag.ts"],"sourcesContent":["import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateTags } from '../lib/patch-fetch'\n\nexport function cacheTag(...tags: string[]): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheTag()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'generate-static-params':\n case undefined:\n throw new Error(\n '`cacheTag()` can only be called inside a \"use cache\" function.'\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n const validTags = validateTags(tags, '`cacheTag()`')\n\n if (!workUnitStore.tags) {\n workUnitStore.tags = validTags\n } else {\n workUnitStore.tags.push(...validTags)\n }\n}\n"],"names":["cacheTag","tags","process","env","__NEXT_USE_CACHE","Error","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","validTags","validateTags","push"],"mappings":";;;;+BAGgBA;;;eAAAA;;;8CAHqB;4BACR;AAEtB,SAASA,SAAS,GAAGC,IAAc;IACxC,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,qBAEL,CAFK,IAAIC,MACR,sEADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;YACH,MAAM,qBAEL,CAFK,IAAIL,MACR,mEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;QACL,KAAK;YACH;QACF;YACEC;IACJ;IAEA,MAAMK,YAAYC,IAAAA,wBAAY,EAACX,MAAM;IAErC,IAAI,CAACK,cAAcL,IAAI,EAAE;QACvBK,cAAcL,IAAI,GAAGU;IACvB,OAAO;QACLL,cAAcL,IAAI,CAACY,IAAI,IAAIF;IAC7B;AACF","ignoreList":[0]}

@@ -161,4 +161,2 @@ "use strict";

});
case 'prerender-ppr':
return (0, _dynamicrendering.postponeWithTracking)(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':

@@ -165,0 +163,0 @@ workUnitStore.revalidate = 0;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n} from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["refresh","revalidatePath","revalidateTag","updateTag","tag","profile","console","warn","validateAndNormalizeCacheLifeProfile","kind","revalidate","encodeHeaderSafe","workStore","workAsyncStorage","getStore","page","endsWith","Error","undefined","workUnitStore","workUnitAsyncStorage","phase","pathWasRevalidated","ActionDidRevalidateDynamicOnly","originalPath","type","length","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","normalizedPath","NEXT_CACHE_IMPLICIT_TAG_ID","removeTrailingSlash","isDynamicRoute","tags","push","expression","store","incrementalCache","route","error","abortAndThrowOnSynchronousRequestDataAccess","InvariantError","postponeWithTracking","dynamicTracking","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire","ActionDidRevalidate"],"mappings":";;;;;;;;;;;;;;;;;IAwEgBA,OAAO;eAAPA;;IA2BAC,cAAc;eAAdA;;IAjEAC,aAAa;eAAbA;;IAiBAC,SAAS;eAATA;;;kCAhDT;uBACwB;2BAIxB;0CAC0B;8CACI;oCACF;gCACJ;wCAIxB;qCAC6B;kCACH;kCACoB;AAe9C,SAASD,cAAcE,GAAW,EAAEC,OAAiC;IAC1E,IAAI,CAACA,SAAS;QACZC,QAAQC,IAAI,CACV;IAEJ,OAAO,IAAI,OAAOF,YAAY,UAAU;QACtCA,UAAUG,IAAAA,sDAAoC,EAACH,SAAS;YAAEI,MAAM;QAAS;IAC3E;IACA,OAAOC,WAAW;QAACC,IAAAA,kCAAgB,EAACP;KAAK,EAAE,CAAC,cAAc,EAAEA,KAAK,EAAEC;AACrE;AAQO,SAASF,UAAUC,GAAW;IACnC,MAAMQ,YAAYC,0CAAgB,CAACC,QAAQ;IAE3C,+DAA+D;IAC/D,yBAAyB;IACzB,IAAI,CAACF,aAAaA,UAAUG,IAAI,CAACC,QAAQ,CAAC,WAAW;QACnD,MAAM,qBAIL,CAJK,IAAIC,MACR,+DACE,8FACA,sFAHE,qBAAA;mBAAA;wBAAA;0BAAA;QAIN;IAC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AACC;YAC5D,IAAIA,KAAKvD,GAAG,KAAKA,KAAK,OAAO;YAC7B,kEAAkE;YAClE,IAAI,OAAOuD,KAAKtD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOsD,KAAKtD,OAAO,KAAKA;YAC1B;YACA,IAAI,OAAOsD,KAAKtD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOuD,KAAKC,SAAS,CAACF,KAAKtD,OAAO,MAAMuD,KAAKC,SAAS,CAACxD;YACzD;YACA,OAAOsD,KAAKtD,OAAO,KAAKA;QAC1B;QACA,IAAIoD,kBAAkB,CAAC,GAAG;YACxBtB,MAAMiB,sBAAsB,CAACnB,IAAI,CAAC;gBAChC7B;gBACAC;gBACAgD;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACTlB,MAAMiB,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJzD,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnB8B,yBAAAA,MAAO4B,iBAAiB,CAAC1D,QAAQ,IACjC8B,MAAM4B,iBAAiB,CAAC1D,QAAQ,GAChCa;IAER,IAAI,CAACb,WAAWyD,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5C7B,MAAMb,kBAAkB,GAAG2C,2DAAmB;IAChD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import { abortAndThrowOnSynchronousRequestDataAccess } from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["refresh","revalidatePath","revalidateTag","updateTag","tag","profile","console","warn","validateAndNormalizeCacheLifeProfile","kind","revalidate","encodeHeaderSafe","workStore","workAsyncStorage","getStore","page","endsWith","Error","undefined","workUnitStore","workUnitAsyncStorage","phase","pathWasRevalidated","ActionDidRevalidateDynamicOnly","originalPath","type","length","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","normalizedPath","NEXT_CACHE_IMPLICIT_TAG_ID","removeTrailingSlash","isDynamicRoute","tags","push","expression","store","incrementalCache","route","error","abortAndThrowOnSynchronousRequestDataAccess","InvariantError","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire","ActionDidRevalidate"],"mappings":";;;;;;;;;;;;;;;;;IAqEgBA,OAAO;eAAPA;;IA2BAC,cAAc;eAAdA;;IAjEAC,aAAa;eAAbA;;IAiBAC,SAAS;eAATA;;;kCAhD4C;uBAC7B;2BAIxB;0CAC0B;8CACI;oCACF;gCACJ;wCAIxB;qCAC6B;kCACH;kCACoB;AAe9C,SAASD,cAAcE,GAAW,EAAEC,OAAiC;IAC1E,IAAI,CAACA,SAAS;QACZC,QAAQC,IAAI,CACV;IAEJ,OAAO,IAAI,OAAOF,YAAY,UAAU;QACtCA,UAAUG,IAAAA,sDAAoC,EAACH,SAAS;YAAEI,MAAM;QAAS;IAC3E;IACA,OAAOC,WAAW;QAACC,IAAAA,kCAAgB,EAACP;KAAK,EAAE,CAAC,cAAc,EAAEA,KAAK,EAAEC;AACrE;AAQO,SAASF,UAAUC,GAAW;IACn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AAgBC,YAAYC,UAAU,GAAGD,YAAYE,GAAG;IAE9D,KAAK,MAAMlD,OAAO4B,KAAM;QACtB,MAAMuB,gBAAgBpB,MAAMe,sBAAsB,CAACM,SAAS,CAAC,CAACC;YAC5D,IAAIA,KAAKrD,GAAG,KAAKA,KAAK,OAAO;YAC7B,kEAAkE;YAClE,IAAI,OAAOqD,KAAKpD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOoD,KAAKpD,OAAO,KAAKA;YAC1B;YACA,IAAI,OAAOoD,KAAKpD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOqD,KAAKC,SAAS,CAACF,KAAKpD,OAAO,MAAMqD,KAAKC,SAAS,CAACtD;YACzD;YACA,OAAOoD,KAAKpD,OAAO,KAAKA;QAC1B;QACA,IAAIkD,kBAAkB,CAAC,GAAG;YACxBpB,MAAMe,sBAAsB,CAACjB,IAAI,CAAC;gBAChC7B;gBACAC;gBACA8C;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACThB,MAAMe,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJvD,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnB8B,yBAAAA,MAAO0B,iBAAiB,CAACxD,QAAQ,IACjC8B,MAAM0B,iBAAiB,CAACxD,QAAQ,GAChCa;IAER,IAAI,CAACb,WAAWuD,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5C3B,MAAMb,kBAAkB,GAAGyC,2DAAmB;IAChD;AACF","ignoreList":[0]}

@@ -122,3 +122,2 @@ "use strict";

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -298,3 +297,2 @@ // We update the store's revalidate property if the revalidate option is a higher precedence

case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':

@@ -301,0 +299,0 @@ case 'cache':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["unstable_cache","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","CachedRouteKind","FETCH","data","headers","body","JSON","stringify","status","url","CACHE_ONE_YEAR_SECONDS","fetchCache","cb","keyParts","options","Error","toString","validateTags","validateRevalidate","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","getCacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","encodeHeaderSafe","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","getDraftModeProviderForCacheScope","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","IncrementalCacheKind","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","willConsumerServerCache","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":";;;;+BA8DgBA;;;eAAAA;;;2BA5DuB;4BACU;kCAChB;0CAI1B;8CAMA;+BAKA;AAQP,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMC,8BAAe,CAACC,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACf;YACrBgB,QAAQ;YACRC,KAAK;QACP;QACAb,YACE,OAAOA,eAAe,WAAWc,iCAAsB,GAAGd;IAC9D,GACA;QAAEe,YAAY;QAAMhB;QAAME;QAAUC;IAAS;IAE/C;AACF;AAOO,SAAST,eACduB,EAAK,EACLC,QAAmB,EAC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3C5B,iBACAjC,OACGa;gBAGL,uDAAuD;gBACvD,oDAAoD;gBACpD,+CAA+C;gBAC/C,MAAMlC,eACJC,QACAC,kBACAC,UACAC,MACAC,YACAC,UACAC;gBAEF,OAAON;YACT;QACF,SAAU;YACR,IAAI0C,aAAa;gBACfA,YAAY4C,OAAO;YACrB;QACF;IACF;IACA,yGAAyG;IACzG,OAAOtD;AACT;AAEA,SAASc,kBACPZ,SAAoB,EACpBG,aAA4B;IAE5B,OAAQA,cAAciB,IAAI;QACxB,KAAK;YACH,MAAMiC,WAAWlD,cAAcpB,GAAG,CAACsE,QAAQ;YAC3C,MAAMC,eAAe,IAAIC,gBAAgBpD,cAAcpB,GAAG,CAACyE,MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAalB,GAAG,CAAC4B,MAAM,EAC9CnE,IAAI,CAAC;YAER,OAAO,GAAGwD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOzD,UAAUkE,KAAK;QACxB;YACE,OAAO/D;IACX;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["unstable_cache","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","CachedRouteKind","FETCH","data","headers","body","JSON","stringify","status","url","CACHE_ONE_YEAR_SECONDS","fetchCache","cb","keyParts","options","Error","toString","validateTags","validateRevalidate","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","getCacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","encodeHeaderSafe","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","getDraftModeProviderForCacheScope","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","IncrementalCacheKind","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","willConsumerServerCache","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":";;;;+BA8DgBA;;;eAAAA;;;2BA5DuB;4BACU;kCAChB;0CAI1B;8CAMA;+BAKA;AAQP,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMC,8BAAe,CAACC,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACf;YACrBgB,QAAQ;YACRC,KAAK;QACP;QACAb,YACE,OAAOA,eAAe,WAAWc,iCAAsB,GAAGd;IAC9D,GACA;QAAEe,YAAY;QAAMhB;QAAME;QAAUC;IAAS;IAE/C;AACF;AAOO,SAAST,eACduB,EAAK,EACLC,QAAmB,EACnBC,UAMI,CAAC,CAAC;IAEN,IAAIA,QAAQlB,UAAU,KAAK,GAAG;QAC5B,MAAM,qBAEL,CAFK,IAAImB,MACR,CAAC,wFAAwF,EAAEH,GAAGI,QAAQ,IAAI,GADtG,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,uCAAuC;IACvC,MAAMrB,OAAOmB,QAAQnB,IAAI,GACrBsB,IAAAA,wBAAY,EAACH,QAAQnB,IAAI,EAAE,CAAC,eAAe,EAAEiB,GAAGI,QAAQ,IAAI,IAC5D,EAAE;IAEN,wEAAwE;IACxE,yEAAyE;IACzE,+BAA+B;IAC/B,MAAMpB,aAAasB,IAAAA,8BAAkB,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MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAalB,GAAG,CAAC4B,MAAM,EAC9CnE,IAAI,CAAC;YAER,OAAO,GAAGwD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOzD,UAAUkE,KAAK;QACxB;YACE,OAAO/D;IACX;AACF","ignoreList":[0]}

@@ -35,3 +35,2 @@ "use strict";

return;
case 'prerender-ppr':
case 'prerender-legacy':

@@ -38,0 +37,0 @@ case 'request':

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-no-store.ts"],"sourcesContent":["import { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'\n\n/**\n * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.\n *\n * It marks the current scope as dynamic.\n *\n * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render\n * halt and mark the page as dynamic.\n * - In PPR cases this will postpone the render at this location.\n *\n * If we are inside a cache scope then this function does nothing.\n *\n * @note It expects to be called within App Router and will error otherwise.\n *\n * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)\n */\nexport function unstable_noStore() {\n const callingExpression = 'unstable_noStore()'\n const store = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!store) {\n // This generally implies we are being called in Pages router. We should probably not support\n // unstable_noStore in contexts outside of `react-server` condition but since we historically\n // have not errored here previously, we maintain that behavior for now.\n return\n } else if (store.forceStatic) {\n return\n } else {\n store.isUnstableNoStore = true\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n // unstable_noStore() is a noop in Dynamic I/O.\n return\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)\n }\n}\n"],"names":["unstable_noStore","callingExpression","store","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","forceStatic","isUnstableNoStore","type","markCurrentScopeAsDynamic"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;0CAnBiB;8CACI;kCACK;AAiBnC,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,QAAQC,0CAAgB,CAACC,QAAQ;IACvC,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAI,CAACF,OAAO;QACV,6FAA6F;QAC7F,6FAA6F;QAC7F,uEAAuE;QACvE;IACF,OAAO,IAAIA,MAAMK,WAAW,EAAE;QAC5B;IACF,OAAO;QACLL,MAAMM,iBAAiB,GAAG;QAC1B,IAAIH,eAAe;YACjB,OAAQA,cAAcI,IAAI;gBACxB,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH,+CAA+C;oBAC/C;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH;gBACF;oBACEJ;YACJ;QACF;QACAK,IAAAA,2CAAyB,EAACR,OAAOG,eAAeJ;IAClD;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-no-store.ts"],"sourcesContent":["import { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'\n\n/**\n * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.\n *\n * It marks the current scope as dynamic.\n *\n * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render\n * halt and mark the page as dynamic.\n * - In PPR cases this will postpone the render at this location.\n *\n * If we are inside a cache scope then this function does nothing.\n *\n * @note It expects to be called within App Router and will error otherwise.\n *\n * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)\n */\nexport function unstable_noStore() {\n const callingExpression = 'unstable_noStore()'\n const store = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!store) {\n // This generally implies we are being called in Pages router. We should probably not support\n // unstable_noStore in contexts outside of `react-server` condition but since we historically\n // have not errored here previously, we maintain that behavior for now.\n return\n } else if (store.forceStatic) {\n return\n } else {\n store.isUnstableNoStore = true\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n // unstable_noStore() is a noop in Dynamic I/O.\n return\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)\n }\n}\n"],"names":["unstable_noStore","callingExpression","store","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","forceStatic","isUnstableNoStore","type","markCurrentScopeAsDynamic"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;0CAnBiB;8CACI;kCACK;AAiBnC,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,QAAQC,0CAAgB,CAACC,QAAQ;IACvC,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAI,CAACF,OAAO;QACV,6FAA6F;QAC7F,6FAA6F;QAC7F,uEAAuE;QACvE;IACF,OAAO,IAAIA,MAAMK,WAAW,EAAE;QAC5B;IACF,OAAO;QACLL,MAAMM,iBAAiB,GAAG;QAC1B,IAAIH,eAAe;YACjB,OAAQA,cAAcI,IAAI;gBACxB,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH,+CAA+C;oBAC/C;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH;gBACF;oBACEJ;YACJ;QACF;QACAK,IAAAA,2CAAyB,EAACR,OAAOG,eAAeJ;IAClD;AACF","ignoreList":[0]}

@@ -24,3 +24,3 @@ "use strict";

function isStableBuild() {
return !"16.3.1-canary.11"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV;
return !"16.3.1-canary.12"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV;
}

@@ -27,0 +27,0 @@ class CanaryOnlyConfigError extends Error {

@@ -85,3 +85,3 @@ "use strict";

ciName: _ciinfo.isCI && _ciinfo.name || null,
nextVersion: "16.3.1-canary.11",
nextVersion: "16.3.1-canary.12",
agentName: await (0, _agentname.getAgentName)()

@@ -88,0 +88,0 @@ };

@@ -96,3 +96,3 @@ import type { TelemetryPlugin } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin';

export type EventBuildFeatureUsage = {
featureName: 'next/image' | 'next/legacy/image' | 'next/future/image' | 'next/script' | 'next/dynamic' | '@next/font/google' | '@next/font/local' | 'next/font/google' | 'next/font/local' | 'experimental/nextScriptWorkers' | 'experimental/cacheComponents' | 'experimental/optimizeCss' | 'experimental/ppr' | 'swcLoader' | 'swcRelay' | 'swcStyledComponents' | 'swcReactRemoveProperties' | 'swcExperimentalDecorators' | 'swcRemoveConsole' | 'swcImportSource' | 'swcEmotion' | `swc/target/${SWC_TARGET_TRIPLE}` | 'turbotrace' | 'vercelImageGeneration' | 'transpilePackages' | 'skipProxyUrlNormalize' | 'skipTrailingSlashRedirect' | 'modularizeImports' | 'esmExternals' | 'webpackPlugins' | UseCacheTrackerKey | 'turbopackFileSystemCache' | 'runAfterProductionCompile';
featureName: 'next/image' | 'next/legacy/image' | 'next/future/image' | 'next/script' | 'next/dynamic' | '@next/font/google' | '@next/font/local' | 'next/font/google' | 'next/font/local' | 'experimental/nextScriptWorkers' | 'experimental/cacheComponents' | 'experimental/optimizeCss' | 'swcLoader' | 'swcRelay' | 'swcStyledComponents' | 'swcReactRemoveProperties' | 'swcExperimentalDecorators' | 'swcRemoveConsole' | 'swcImportSource' | 'swcEmotion' | `swc/target/${SWC_TARGET_TRIPLE}` | 'turbotrace' | 'vercelImageGeneration' | 'transpilePackages' | 'skipProxyUrlNormalize' | 'skipTrailingSlashRedirect' | 'modularizeImports' | 'esmExternals' | 'webpackPlugins' | UseCacheTrackerKey | 'turbopackFileSystemCache' | 'runAfterProductionCompile';
invocationCount: number;

@@ -99,0 +99,0 @@ };

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../../src/telemetry/events/build.ts"],"sourcesContent":["import type { TelemetryPlugin } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'\nimport type { SWC_TARGET_TRIPLE } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'\nimport type { UseCacheTrackerKey } from '../../build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils'\nimport { extractNextErrorCode } from '../../lib/error-telemetry-utils'\n\nconst REGEXP_DIRECTORY_DUNDER =\n /[\\\\/]__[^\\\\/]+(?<![\\\\/]__(?:tests|mocks))__[\\\\/]/i\nconst REGEXP_DIRECTORY_TESTS = /[\\\\/]__(tests|mocks)__[\\\\/]/i\nconst REGEXP_FILE_TEST = /\\.(?:spec|test)\\.[^.]+$/i\n\nconst EVENT_TYPE_CHECK_COMPLETED = 'NEXT_TYPE_CHECK_COMPLETED'\ntype EventTypeCheckCompleted = {\n durationInSeconds: number\n typescriptVersion: string | null\n inputFilesCount?: number\n totalFilesCount?: number\n incremental?: boolean\n typeCheckMode: 'typescript-api' | 'typescript-cli'\n}\n\nexport function eventTypeCheckCompleted(event: EventTypeCheckCompleted): {\n eventName: string\n payload: EventTypeCheckCompleted\n} {\n return {\n eventName: EVENT_TYPE_CHECK_COMPLETED,\n payload: event,\n }\n}\n\nconst EVENT_LINT_CHECK_COMPLETED = 'NEXT_LINT_CHECK_COMPLETED'\nexport type EventLintCheckCompleted = {\n durationInSeconds: number\n eslintVersion: string | null\n lintedFilesCount?: number\n lintFix?: boolean\n buildLint?: boolean\n nextEslintPluginVersion?: string | null\n nextEslintPluginErrorsCount?: number\n nextEslintPluginWarningsCount?: number\n nextRulesEnabled: {\n [ruleName: `@next/next/${string}`]: 'off' | 'warn' | 'error'\n }\n}\n\nexport function eventLintCheckCompleted(event: EventLintCheckCompleted): {\n eventName: string\n payload: EventLintCheckCompleted\n} {\n return {\n eventName: EVENT_LINT_CHECK_COMPLETED,\n payload: event,\n }\n}\n\nconst EVENT_ANALYZE_COMPLETED = 'NEXT_ANALYZE_COMPLETED'\ntype AnalyzeEventCompleted =\n | {\n durationInSeconds: number\n success: true\n totalPageCount: number\n }\n | {\n success: false\n }\n\nexport function eventAnalyzeCompleted(event: AnalyzeEventCompleted): {\n eventName: string\n payload: AnalyzeEventCompleted\n} {\n return {\n eventName: EVENT_ANALYZE_COMPLETED,\n payload: event,\n }\n}\n\nconst EVENT_BUILD_COMPLETED = 'NEXT_BUILD_COMPLETED'\ntype EventBuildCompleted = {\n bundler: 'webpack' | 'rspack' | 'turbopack'\n durationInSeconds: number\n totalPageCount: number\n hasDunderPages: boolean\n hasTestPages: boolean\n totalAppPagesCount?: number\n}\n\nexport function eventBuildCompleted(\n pagePaths: string[],\n event: Omit<\n EventBuildCompleted,\n 'totalPageCount' | 'hasDunderPages' | 'hasTestPages'\n >\n): { eventName: string; payload: EventBuildCompleted } {\n return {\n eventName: EVENT_BUILD_COMPLETED,\n payload: {\n ...event,\n totalPageCount: pagePaths.length,\n hasDunderPages: pagePaths.some((path) =>\n REGEXP_DIRECTORY_DUNDER.test(path)\n ),\n hasTestPages: pagePaths.some(\n (path) =>\n REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)\n ),\n totalAppPagesCount: event.totalAppPagesCount,\n },\n }\n}\n\nconst EVENT_BUILD_FAILED = 'NEXT_BUILD_FAILED'\ntype EventBuildFailed = {\n bundler: 'webpack' | 'rspack' | 'turbopack'\n errorCode: string\n durationInSeconds: number\n}\n\nexport function eventBuildFailed(event: EventBuildFailed) {\n return {\n eventName: EVENT_BUILD_FAILED,\n payload: event,\n }\n}\n\nconst EVENT_BUILD_OPTIMIZED = 'NEXT_BUILD_OPTIMIZED'\ntype EventBuildOptimized = {\n durationInSeconds: number\n totalPageCount: number\n staticPageCount: number\n staticPropsPageCount: number\n serverPropsPageCount: number\n ssrPageCount: number\n hasDunderPages: boolean\n hasTestPages: boolean\n hasStatic404: boolean\n hasReportWebVitals: boolean\n headersCount: number\n rewritesCount: number\n redirectsCount: number\n headersWithHasCount: number\n rewritesWithHasCount: number\n redirectsWithHasCount: number\n middlewareCount: number\n isRspack: boolean\n totalAppPagesCount?: number\n staticAppPagesCount?: number\n serverAppPagesCount?: number\n edgeRuntimeAppCount?: number\n edgeRuntimePagesCount?: number\n}\n\nexport function eventBuildOptimize(\n pagePaths: string[],\n event: Omit<\n EventBuildOptimized,\n 'totalPageCount' | 'hasDunderPages' | 'hasTestPages' | 'isRspack'\n >\n): { eventName: string; payload: EventBuildOptimized } {\n return {\n eventName: EVENT_BUILD_OPTIMIZED,\n payload: {\n ...event,\n totalPageCount: pagePaths.length,\n hasDunderPages: pagePaths.some((path) =>\n REGEXP_DIRECTORY_DUNDER.test(path)\n ),\n hasTestPages: pagePaths.some(\n (path) =>\n REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)\n ),\n totalAppPagesCount: event.totalAppPagesCount,\n staticAppPagesCount: event.staticAppPagesCount,\n serverAppPagesCount: event.serverAppPagesCount,\n edgeRuntimeAppCount: event.edgeRuntimeAppCount,\n edgeRuntimePagesCount: event.edgeRuntimePagesCount,\n isRspack: process.env.NEXT_RSPACK !== undefined,\n },\n }\n}\n\nexport const EVENT_BUILD_FEATURE_USAGE = 'NEXT_BUILD_FEATURE_USAGE'\nexport type EventBuildFeatureUsage = {\n // NOTE: If you are adding features, make sure to update the `enum` field\n // for `featureName` in https://github.com/vercel/next-telemetry/blob/master/events/v1/featureUsage.ts\n // *before* you make changes here.\n featureName:\n | 'next/image'\n | 'next/legacy/image'\n | 'next/future/image'\n | 'next/script'\n | 'next/dynamic'\n | '@next/font/google'\n | '@next/font/local'\n | 'next/font/google'\n | 'next/font/local'\n | 'experimental/nextScriptWorkers'\n | 'experimental/cacheComponents'\n | 'experimental/optimizeCss'\n | 'experimental/ppr'\n | 'swcLoader'\n | 'swcRelay'\n | 'swcStyledComponents'\n | 'swcReactRemoveProperties'\n | 'swcExperimentalDecorators'\n | 'swcRemoveConsole'\n | 'swcImportSource'\n | 'swcEmotion'\n | `swc/target/${SWC_TARGET_TRIPLE}`\n | 'turbotrace'\n | 'vercelImageGeneration'\n | 'transpilePackages'\n | 'skipProxyUrlNormalize'\n | 'skipTrailingSlashRedirect'\n | 'modularizeImports'\n | 'esmExternals'\n | 'webpackPlugins'\n | UseCacheTrackerKey\n | 'turbopackFileSystemCache'\n | 'runAfterProductionCompile'\n invocationCount: number\n}\nexport function eventBuildFeatureUsage(\n usages: ReturnType<TelemetryPlugin['usages']>\n): Array<{ eventName: string; payload: EventBuildFeatureUsage }> {\n return usages.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: {\n featureName,\n invocationCount,\n },\n }))\n}\n\n/**\n * Converts aggregated Turbopack feature-usage diagnostics (emitted by the\n * Rust side from `FeatureUsageTelemetry` and aggregated per-feature by\n * `get_diagnostics`) into `EVENT_BUILD_FEATURE_USAGE` telemetry events.\n */\nexport function eventBuildFeatureUsageFromTurbopack(\n diagnostics: ReadonlyArray<{\n featureName: string\n invocationCount: number\n }>\n): Array<{ eventName: string; payload: EventBuildFeatureUsage }> {\n return diagnostics.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: {\n featureName: featureName as EventBuildFeatureUsage['featureName'],\n invocationCount,\n },\n }))\n}\n\nexport const EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS =\n 'NEXT_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS'\n\nexport type EventPackageUsedInGetServerSideProps = {\n package: string\n}\n\nexport function eventPackageUsedInGetServerSideProps(\n packagesUsedInServerSideProps: ReturnType<\n TelemetryPlugin['packagesUsedInServerSideProps']\n >\n): Array<{ eventName: string; payload: EventPackageUsedInGetServerSideProps }> {\n return packagesUsedInServerSideProps.map((packageName) => ({\n eventName: EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS,\n payload: {\n package: packageName,\n },\n }))\n}\n\nexport const EVENT_MCP_TOOL_USAGE = 'NEXT_MCP_TOOL_USAGE'\n\nexport type McpToolName =\n | 'mcp/get_errors'\n | 'mcp/get_logs'\n | 'mcp/get_page_metadata'\n | 'mcp/get_project_metadata'\n | 'mcp/get_routes'\n | 'mcp/get_request_insights'\n | 'mcp/get_server_action_by_id'\n | 'mcp/get_compilation_issues'\n | 'mcp/compile_route'\n\nexport type EventMcpToolUsage = {\n toolName: McpToolName\n invocationCount: number\n}\n\nexport function eventMcpToolUsage(\n usages: Array<{ featureName: McpToolName; invocationCount: number }>\n): Array<{ eventName: string; payload: EventMcpToolUsage }> {\n return usages.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: featureName,\n invocationCount,\n },\n }))\n}\n\nexport const ERROR_THROWN_EVENT = 'NEXT_ERROR_THROWN'\ntype ErrorThrownEvent = {\n eventName: typeof ERROR_THROWN_EVENT\n payload: {\n errorCode: string | undefined\n location: string | undefined\n }\n}\n\n// Creates a Telemetry event for errors. For privacy, only includes the error code and not the error\n// message.\n//\n// `location` may be included if it's a location internal to the next.js source tree (i.e. a\n// non-absolute path).\nexport function eventErrorThrown(\n error: Error,\n anonymizedLocation: string | undefined\n): ErrorThrownEvent {\n return {\n eventName: ERROR_THROWN_EVENT,\n payload: {\n errorCode: extractNextErrorCode(error) || 'Unknown',\n location: anonymizedLocation,\n },\n }\n}\n"],"names":["ERROR_THROWN_EVENT","EVENT_BUILD_FEATURE_USAGE","EVENT_MCP_TOOL_USAGE","EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS","eventAnalyzeCompleted","eventBuildCompleted","eventBuildFailed","eventBuildFeatureUsage","eventBuildFeatureUsageFromTurbopack","eventBuildOptimize","eventErrorThrown","eventLintCheckCompleted","eventMcpToolUsage","eventPackageUsedInGetServerSideProps","eventTypeCheckCompleted","REGEXP_DIRECTORY_DUNDER","REGEXP_DIRECTORY_TESTS","REGEXP_FILE_TEST","EVENT_TYPE_CHECK_COMPLETED","event","eventName","payload","EVENT_LINT_CHECK_COMPLETED","EVENT_ANALYZE_COMPLETED","EVENT_BUILD_COMPLETED","pagePaths","totalPageCount","length","hasDunderPages","some","path","test","hasTestPages","totalAppPagesCount","EVENT_BUILD_FAILED","EVENT_BUILD_OPTIMIZED","staticAppPagesCount","serverAppPagesCount","edgeRuntimeAppCount","edgeRuntimePagesCount","isRspack","process","env","NEXT_RSPACK","undefined","usages","map","featureName","invocationCount","diagnostics","packagesUsedInServerSideProps","packageName","package","toolName","error","anonymizedLocation","errorCode","extractNextErrorCode","location"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+SaA,kBAAkB;eAAlBA;;IA3HAC,yBAAyB;eAAzBA;;IA6FAC,oBAAoB;eAApBA;;IApBAC,gDAAgD;eAAhDA;;IA3LGC,qBAAqB;eAArBA;;IAoBAC,mBAAmB;eAAnBA;;IA+BAC,gBAAgB;eAAhBA;;IAwGAC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LnC,WAAWpB;QACXqB,SAAS;YACPmC,WAAWC,IAAAA,yCAAoB,EAACH,UAAU;YAC1CI,UAAUH;QACZ;IACF;AACF","ignoreList":[0]}
{"version":3,"sources":["../../../src/telemetry/events/build.ts"],"sourcesContent":["import type { TelemetryPlugin } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'\nimport type { SWC_TARGET_TRIPLE } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin'\nimport type { UseCacheTrackerKey } from '../../build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils'\nimport { extractNextErrorCode } from '../../lib/error-telemetry-utils'\n\nconst REGEXP_DIRECTORY_DUNDER =\n /[\\\\/]__[^\\\\/]+(?<![\\\\/]__(?:tests|mocks))__[\\\\/]/i\nconst REGEXP_DIRECTORY_TESTS = /[\\\\/]__(tests|mocks)__[\\\\/]/i\nconst REGEXP_FILE_TEST = /\\.(?:spec|test)\\.[^.]+$/i\n\nconst EVENT_TYPE_CHECK_COMPLETED = 'NEXT_TYPE_CHECK_COMPLETED'\ntype EventTypeCheckCompleted = {\n durationInSeconds: number\n typescriptVersion: string | null\n inputFilesCount?: number\n totalFilesCount?: number\n incremental?: boolean\n typeCheckMode: 'typescript-api' | 'typescript-cli'\n}\n\nexport function eventTypeCheckCompleted(event: EventTypeCheckCompleted): {\n eventName: string\n payload: EventTypeCheckCompleted\n} {\n return {\n eventName: EVENT_TYPE_CHECK_COMPLETED,\n payload: event,\n }\n}\n\nconst EVENT_LINT_CHECK_COMPLETED = 'NEXT_LINT_CHECK_COMPLETED'\nexport type EventLintCheckCompleted = {\n durationInSeconds: number\n eslintVersion: string | null\n lintedFilesCount?: number\n lintFix?: boolean\n buildLint?: boolean\n nextEslintPluginVersion?: string | null\n nextEslintPluginErrorsCount?: number\n nextEslintPluginWarningsCount?: number\n nextRulesEnabled: {\n [ruleName: `@next/next/${string}`]: 'off' | 'warn' | 'error'\n }\n}\n\nexport function eventLintCheckCompleted(event: EventLintCheckCompleted): {\n eventName: string\n payload: EventLintCheckCompleted\n} {\n return {\n eventName: EVENT_LINT_CHECK_COMPLETED,\n payload: event,\n }\n}\n\nconst EVENT_ANALYZE_COMPLETED = 'NEXT_ANALYZE_COMPLETED'\ntype AnalyzeEventCompleted =\n | {\n durationInSeconds: number\n success: true\n totalPageCount: number\n }\n | {\n success: false\n }\n\nexport function eventAnalyzeCompleted(event: AnalyzeEventCompleted): {\n eventName: string\n payload: AnalyzeEventCompleted\n} {\n return {\n eventName: EVENT_ANALYZE_COMPLETED,\n payload: event,\n }\n}\n\nconst EVENT_BUILD_COMPLETED = 'NEXT_BUILD_COMPLETED'\ntype EventBuildCompleted = {\n bundler: 'webpack' | 'rspack' | 'turbopack'\n durationInSeconds: number\n totalPageCount: number\n hasDunderPages: boolean\n hasTestPages: boolean\n totalAppPagesCount?: number\n}\n\nexport function eventBuildCompleted(\n pagePaths: string[],\n event: Omit<\n EventBuildCompleted,\n 'totalPageCount' | 'hasDunderPages' | 'hasTestPages'\n >\n): { eventName: string; payload: EventBuildCompleted } {\n return {\n eventName: EVENT_BUILD_COMPLETED,\n payload: {\n ...event,\n totalPageCount: pagePaths.length,\n hasDunderPages: pagePaths.some((path) =>\n REGEXP_DIRECTORY_DUNDER.test(path)\n ),\n hasTestPages: pagePaths.some(\n (path) =>\n REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)\n ),\n totalAppPagesCount: event.totalAppPagesCount,\n },\n }\n}\n\nconst EVENT_BUILD_FAILED = 'NEXT_BUILD_FAILED'\ntype EventBuildFailed = {\n bundler: 'webpack' | 'rspack' | 'turbopack'\n errorCode: string\n durationInSeconds: number\n}\n\nexport function eventBuildFailed(event: EventBuildFailed) {\n return {\n eventName: EVENT_BUILD_FAILED,\n payload: event,\n }\n}\n\nconst EVENT_BUILD_OPTIMIZED = 'NEXT_BUILD_OPTIMIZED'\ntype EventBuildOptimized = {\n durationInSeconds: number\n totalPageCount: number\n staticPageCount: number\n staticPropsPageCount: number\n serverPropsPageCount: number\n ssrPageCount: number\n hasDunderPages: boolean\n hasTestPages: boolean\n hasStatic404: boolean\n hasReportWebVitals: boolean\n headersCount: number\n rewritesCount: number\n redirectsCount: number\n headersWithHasCount: number\n rewritesWithHasCount: number\n redirectsWithHasCount: number\n middlewareCount: number\n isRspack: boolean\n totalAppPagesCount?: number\n staticAppPagesCount?: number\n serverAppPagesCount?: number\n edgeRuntimeAppCount?: number\n edgeRuntimePagesCount?: number\n}\n\nexport function eventBuildOptimize(\n pagePaths: string[],\n event: Omit<\n EventBuildOptimized,\n 'totalPageCount' | 'hasDunderPages' | 'hasTestPages' | 'isRspack'\n >\n): { eventName: string; payload: EventBuildOptimized } {\n return {\n eventName: EVENT_BUILD_OPTIMIZED,\n payload: {\n ...event,\n totalPageCount: pagePaths.length,\n hasDunderPages: pagePaths.some((path) =>\n REGEXP_DIRECTORY_DUNDER.test(path)\n ),\n hasTestPages: pagePaths.some(\n (path) =>\n REGEXP_DIRECTORY_TESTS.test(path) || REGEXP_FILE_TEST.test(path)\n ),\n totalAppPagesCount: event.totalAppPagesCount,\n staticAppPagesCount: event.staticAppPagesCount,\n serverAppPagesCount: event.serverAppPagesCount,\n edgeRuntimeAppCount: event.edgeRuntimeAppCount,\n edgeRuntimePagesCount: event.edgeRuntimePagesCount,\n isRspack: process.env.NEXT_RSPACK !== undefined,\n },\n }\n}\n\nexport const EVENT_BUILD_FEATURE_USAGE = 'NEXT_BUILD_FEATURE_USAGE'\nexport type EventBuildFeatureUsage = {\n // NOTE: If you are adding features, make sure to update the `enum` field\n // for `featureName` in https://github.com/vercel/next-telemetry/blob/master/events/v1/featureUsage.ts\n // *before* you make changes here.\n featureName:\n | 'next/image'\n | 'next/legacy/image'\n | 'next/future/image'\n | 'next/script'\n | 'next/dynamic'\n | '@next/font/google'\n | '@next/font/local'\n | 'next/font/google'\n | 'next/font/local'\n | 'experimental/nextScriptWorkers'\n | 'experimental/cacheComponents'\n | 'experimental/optimizeCss'\n | 'swcLoader'\n | 'swcRelay'\n | 'swcStyledComponents'\n | 'swcReactRemoveProperties'\n | 'swcExperimentalDecorators'\n | 'swcRemoveConsole'\n | 'swcImportSource'\n | 'swcEmotion'\n | `swc/target/${SWC_TARGET_TRIPLE}`\n | 'turbotrace'\n | 'vercelImageGeneration'\n | 'transpilePackages'\n | 'skipProxyUrlNormalize'\n | 'skipTrailingSlashRedirect'\n | 'modularizeImports'\n | 'esmExternals'\n | 'webpackPlugins'\n | UseCacheTrackerKey\n | 'turbopackFileSystemCache'\n | 'runAfterProductionCompile'\n invocationCount: number\n}\nexport function eventBuildFeatureUsage(\n usages: ReturnType<TelemetryPlugin['usages']>\n): Array<{ eventName: string; payload: EventBuildFeatureUsage }> {\n return usages.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: {\n featureName,\n invocationCount,\n },\n }))\n}\n\n/**\n * Converts aggregated Turbopack feature-usage diagnostics (emitted by the\n * Rust side from `FeatureUsageTelemetry` and aggregated per-feature by\n * `get_diagnostics`) into `EVENT_BUILD_FEATURE_USAGE` telemetry events.\n */\nexport function eventBuildFeatureUsageFromTurbopack(\n diagnostics: ReadonlyArray<{\n featureName: string\n invocationCount: number\n }>\n): Array<{ eventName: string; payload: EventBuildFeatureUsage }> {\n return diagnostics.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_BUILD_FEATURE_USAGE,\n payload: {\n featureName: featureName as EventBuildFeatureUsage['featureName'],\n invocationCount,\n },\n }))\n}\n\nexport const EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS =\n 'NEXT_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS'\n\nexport type EventPackageUsedInGetServerSideProps = {\n package: string\n}\n\nexport function eventPackageUsedInGetServerSideProps(\n packagesUsedInServerSideProps: ReturnType<\n TelemetryPlugin['packagesUsedInServerSideProps']\n >\n): Array<{ eventName: string; payload: EventPackageUsedInGetServerSideProps }> {\n return packagesUsedInServerSideProps.map((packageName) => ({\n eventName: EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS,\n payload: {\n package: packageName,\n },\n }))\n}\n\nexport const EVENT_MCP_TOOL_USAGE = 'NEXT_MCP_TOOL_USAGE'\n\nexport type McpToolName =\n | 'mcp/get_errors'\n | 'mcp/get_logs'\n | 'mcp/get_page_metadata'\n | 'mcp/get_project_metadata'\n | 'mcp/get_routes'\n | 'mcp/get_request_insights'\n | 'mcp/get_server_action_by_id'\n | 'mcp/get_compilation_issues'\n | 'mcp/compile_route'\n\nexport type EventMcpToolUsage = {\n toolName: McpToolName\n invocationCount: number\n}\n\nexport function eventMcpToolUsage(\n usages: Array<{ featureName: McpToolName; invocationCount: number }>\n): Array<{ eventName: string; payload: EventMcpToolUsage }> {\n return usages.map(({ featureName, invocationCount }) => ({\n eventName: EVENT_MCP_TOOL_USAGE,\n payload: {\n toolName: featureName,\n invocationCount,\n },\n }))\n}\n\nexport const ERROR_THROWN_EVENT = 'NEXT_ERROR_THROWN'\ntype ErrorThrownEvent = {\n eventName: typeof ERROR_THROWN_EVENT\n payload: {\n errorCode: string | undefined\n location: string | undefined\n }\n}\n\n// Creates a Telemetry event for errors. For privacy, only includes the error code and not the error\n// message.\n//\n// `location` may be included if it's a location internal to the next.js source tree (i.e. a\n// non-absolute path).\nexport function eventErrorThrown(\n error: Error,\n anonymizedLocation: string | undefined\n): ErrorThrownEvent {\n return {\n eventName: ERROR_THROWN_EVENT,\n payload: {\n errorCode: extractNextErrorCode(error) || 'Unknown',\n location: anonymizedLocation,\n },\n }\n}\n"],"names":["ERROR_THROWN_EVENT","EVENT_BUILD_FEATURE_USAGE","EVENT_MCP_TOOL_USAGE","EVENT_NAME_PACKAGE_USED_IN_GET_SERVER_SIDE_PROPS","eventAnalyzeCompleted","eventBuildCompleted","eventBuildFailed","eventBuildFeatureUsage","eventBuildFeatureUsageFromTurbopack","eventBuildOptimize","eventErrorThrown","eventLintCheckCompleted","eventMcpToolUsage","eventPackageUsedInGetServerSideProps","eventTypeCheckCompleted","REGEXP_DIRECTORY_DUNDER","REGEXP_DIRECTORY_TESTS","REGEXP_FILE_TEST","EVENT_TYPE_CHECK_COMPLETED","event","eventName","payload","EVENT_LINT_CHECK_COMPLETED","EVENT_ANALYZE_COMPLETED","EVENT_BUILD_COMPLETED","pagePaths","totalPageCount","length","hasDunderPages","some","path","test","hasTestPages","totalAppPagesCount","EVENT_BUILD_FAILED","EVENT_BUILD_OPTIMIZED","staticAppPagesCount","serverAppPagesCount","edgeRuntimeAppCount","edgeRuntimePagesCount","isRspack","process","env","NEXT_RSPACK","undefined","usages","map","featureName","invocationCount","diagnostics","packagesUsedInServerSideProps","packageName","package","toolName","error","anonymizedLocation","errorCode","extractNextErrorCode","location"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IA8SaA,kBAAkB;eAAlBA;;IA1HAC,yBAAyB;eAAzBA;;IA4FAC,oBAAoB;eAApBA;;IApBAC,gDAAgD;eAAhDA;;IA1LGC,qBAAqB;eAArBA;;IAoBAC,mBAAmB;eAAnBA;;IA+BAC,gBAAgB;eAAhBA;;IAuGAC,sBAAsB;eAAtBA;;IAiBAC,mCAAmC;eAAnCA;;IAtFAC,kBAAkB;eAAlBA;;IAqKAC,gBAAgB;eAAhBA;;IA/QAC,uBAAuB;eAAvBA;;IAqPAC,iBAAiB;eAAjBA;;IA/BAC,oCAAoC;eAApCA;;IA/OAC,uBAAuB;eAAvBA;;;qCAjBqB;AAErC,MAAMC,0BACJ;AACF,MAAMC,yBAAyB;AAC/B,MAAMC,mBAAmB;AAEzB,MAAMC,6BAA6B;AAU5B,SAASJ,wBAAwBK,KAA8B;IAIpE,OAAO;QACLC,WAAWF;QACXG,SAASF;IACX;AACF;AAEA,MAAMG,6BAA6B;AAe5B,SAASX,wBAAwBQ,KAA8B;IAIpE,OAAO;QACLC,WAAWE;QACXD,SAASF;IACX;AACF;AAEA,MAAMI,0BAA0B;AAWzB,SAASnB,sBAAsBe,KAA4B;IAIhE,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XoB,SAAS;gBACP0B;gBACAC;YACF;QACF,CAAA;AACF;AAOO,SAASxC,oCACdyC,WAGE;IAEF,OAAOA,YAAYH,GAAG,CAAC,CAAC,EAAEC,WAAW,EAAEC,eAAe,EAAE,GAAM,CAAA;YAC5D5B,WAAWnB;YACXoB,SAAS;gBACP0B,aAAaA;gBACbC;YACF;QACF,CAAA;AACF;AAEO,MAAM7C,mDACX;AAMK,SAASU,qCACdqC,6BAEC;IAED,OAAOA,8BAA8BJ,GAAG,CAAC,CAACK,cAAiB,CAAA;YACzD/B,WAAWjB;YACXkB,SAAS;gBACP+B,SAASD;YACX;QACF,CAAA;AACF;AAEO,MAAMjD,uBAAuB;AAkB7B,SAASU,kBACdiC,MAAoE;IAEpE,OAAOA,OAAOC,GAAG,CAAC,CAAC,EAAEC,WAAW,EAAEC,eAAe,EAAE,GAAM,CAAA;YACvD5B,WAAWlB;YACXmB,SAAS;gBACPgC,UAAUN;gBACVC;YACF;QACF,CAAA;AACF;AAEO,MAAMhD,qBAAqB;AAc3B,SAASU,iBACd4C,KAAY,EACZC,kBAAsC;IAEtC,OAAO;QACLnC,WAAWpB;QACXqB,SAAS;YACPmC,WAAWC,IAAAA,yCAAoB,EAACH,UAAU;YAC1CI,UAAUH;QACZ;IACF;AACF","ignoreList":[0]}

@@ -14,7 +14,7 @@ "use strict";

// This should be an invariant, if it fails our build tooling is broken.
if (typeof "16.3.1-canary.11" !== 'string') {
if (typeof "16.3.1-canary.12" !== 'string') {
return [];
}
const payload = {
nextVersion: "16.3.1-canary.11",
nextVersion: "16.3.1-canary.12",
nodeVersion: process.version,

@@ -21,0 +21,0 @@ cliCommand: event.cliCommand,

@@ -41,3 +41,3 @@ "use strict";

payload: {
nextVersion: "16.3.1-canary.11",
nextVersion: "16.3.1-canary.12",
glibcVersion,

@@ -44,0 +44,0 @@ installedSwcPackages,

@@ -15,3 +15,3 @@ "use strict";

// This should be an invariant, if it fails our build tooling is broken.
if (typeof "16.3.1-canary.11" !== 'string') {
if (typeof "16.3.1-canary.12" !== 'string') {
return [];

@@ -21,3 +21,3 @@ }

const payload = {
nextVersion: "16.3.1-canary.11",
nextVersion: "16.3.1-canary.12",
nodeVersion: process.version,

@@ -24,0 +24,0 @@ cliCommand: event.cliCommand,

{
"name": "next",
"version": "16.3.1-canary.11",
"version": "16.3.1-canary.12",
"description": "The React Framework",

@@ -84,3 +84,3 @@ "main": "./dist/server/next.js",

"dependencies": {
"@next/env": "16.3.1-canary.11",
"@next/env": "16.3.1-canary.12",
"@swc/helpers": "0.5.23",

@@ -116,10 +116,10 @@ "baseline-browser-mapping": "^2.9.19",

"sharp": "^0.35.3",
"@next/swc-darwin-arm64": "16.3.1-canary.11",
"@next/swc-darwin-x64": "16.3.1-canary.11",
"@next/swc-linux-arm64-gnu": "16.3.1-canary.11",
"@next/swc-linux-arm64-musl": "16.3.1-canary.11",
"@next/swc-linux-x64-gnu": "16.3.1-canary.11",
"@next/swc-linux-x64-musl": "16.3.1-canary.11",
"@next/swc-win32-arm64-msvc": "16.3.1-canary.11",
"@next/swc-win32-x64-msvc": "16.3.1-canary.11"
"@next/swc-darwin-arm64": "16.3.1-canary.12",
"@next/swc-darwin-x64": "16.3.1-canary.12",
"@next/swc-linux-arm64-gnu": "16.3.1-canary.12",
"@next/swc-linux-arm64-musl": "16.3.1-canary.12",
"@next/swc-linux-x64-gnu": "16.3.1-canary.12",
"@next/swc-linux-x64-musl": "16.3.1-canary.12",
"@next/swc-win32-arm64-msvc": "16.3.1-canary.12",
"@next/swc-win32-x64-msvc": "16.3.1-canary.12"
},

@@ -126,0 +126,0 @@ "keywords": [

@@ -133,15 +133,18 @@ /// <reference types="node" />

* const modules = import.meta.glob('./dir/*.js', { eager: true })
*
* // The module type can be provided
* const modules = import.meta.glob<{ name: string }>('./dir/*.js')
*/
glob(
glob<M = unknown>(
pattern: string | string[],
options: ImportMetaGlobOptions & { eager: true }
): Record<string, unknown>
glob(
): Record<string, M>
glob<M = unknown>(
pattern: string | string[],
options?: ImportMetaGlobOptions & { eager?: false | undefined }
): Record<string, () => Promise<unknown>>
glob(
): Record<string, () => Promise<M>>
glob<M = unknown>(
pattern: string | string[],
options?: ImportMetaGlobOptions
): Record<string, unknown> | Record<string, () => Promise<unknown>>
): Record<string, M> | Record<string, () => Promise<M>>
}

@@ -148,0 +151,0 @@

self.__BUILD_MANIFEST = {
"__rewrites": {
"afterFiles": [],
"beforeFiles": [],
"fallback": []
},
"sortedPages": [
"/_app",
"/_error"
]
};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()
self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()
self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()
/*
Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/ // When postpone is available in canary React we can switch to importing it directly
export { Postpone } from '../dynamic-rendering';
//# sourceMappingURL=postpone.js.map
{"version":3,"sources":["../../../../../src/server/app-render/rsc/postpone.ts"],"sourcesContent":["/*\n\nFiles in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.\n\n*/\n\n// When postpone is available in canary React we can switch to importing it directly\nexport { Postpone } from '../dynamic-rendering'\n"],"names":["Postpone"],"mappings":"AAAA;;;;AAIA,GAEA,oFAAoF;AACpF,SAASA,QAAQ,QAAQ,uBAAsB","ignoreList":[0]}
/**
* If set to `incremental`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, the options for
* `experimental_ppr` will be ignored.
*/ /**
* Returns true if partial prerendering is enabled for the application. It does
* not tell you if a given route has PPR enabled, as that requires analysis of
* the route's configuration.
*
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
*/ export function checkIsAppPPREnabled(config) {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false;
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config;
// If the config is a string, it must be 'incremental' to enable partial
// prerendering.
if (config === 'incremental') return true;
return false;
}
/**
* Returns true if partial prerendering is supported for the current page with
* the provided app configuration. If the application doesn't have partial
* prerendering enabled, this function will always return false. If you want to
* check if the application has partial prerendering enabled
*
* @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.
*/ export function checkIsRoutePPREnabled(config) {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false;
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config;
return false;
}
//# sourceMappingURL=ppr.js.map
{"version":3,"sources":["../../../../../src/server/lib/experimental/ppr.ts"],"sourcesContent":["/**\n * If set to `incremental`, only those leaf pages that export\n * `experimental_ppr = true` will have partial prerendering enabled. If any\n * page exports this value as `false` or does not export it at all will not\n * have partial prerendering enabled. If set to a boolean, the options for\n * `experimental_ppr` will be ignored.\n */\n\nexport type ExperimentalPPRConfig = boolean | 'incremental'\n\n/**\n * Returns true if partial prerendering is enabled for the application. It does\n * not tell you if a given route has PPR enabled, as that requires analysis of\n * the route's configuration.\n *\n * @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.\n */\nexport function checkIsAppPPREnabled(\n config: ExperimentalPPRConfig | undefined\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n // If the config is a string, it must be 'incremental' to enable partial\n // prerendering.\n if (config === 'incremental') return true\n\n return false\n}\n\n/**\n * Returns true if partial prerendering is supported for the current page with\n * the provided app configuration. If the application doesn't have partial\n * prerendering enabled, this function will always return false. If you want to\n * check if the application has partial prerendering enabled\n *\n * @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.\n */\nexport function checkIsRoutePPREnabled(\n config: ExperimentalPPRConfig | undefined\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n return false\n}\n"],"names":["checkIsAppPPREnabled","config","checkIsRoutePPREnabled"],"mappings":"AAAA;;;;;;CAMC,GAID;;;;;;CAMC,GACD,OAAO,SAASA,qBACdC,MAAyC;IAEzC,gEAAgE;IAChE,IAAI,OAAOA,WAAW,aAAa,OAAO;IAE1C,+CAA+C;IAC/C,IAAI,OAAOA,WAAW,WAAW,OAAOA;IAExC,wEAAwE;IACxE,gBAAgB;IAChB,IAAIA,WAAW,eAAe,OAAO;IAErC,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,uBACdD,MAAyC;IAEzC,gEAAgE;IAChE,IAAI,OAAOA,WAAW,aAAa,OAAO;IAE1C,+CAA+C;IAC/C,IAAI,OAAOA,WAAW,WAAW,OAAOA;IAExC,OAAO;AACT","ignoreList":[0]}
const REACT_POSTPONE_TYPE = Symbol.for('react.postpone');
export function isPostpone(error) {
return typeof error === 'object' && error !== null && error.$$typeof === REACT_POSTPONE_TYPE;
}
//# sourceMappingURL=is-postpone.js.map
{"version":3,"sources":["../../../../../src/server/lib/router-utils/is-postpone.ts"],"sourcesContent":["const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')\n\nexport function isPostpone(error: any): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n error.$$typeof === REACT_POSTPONE_TYPE\n )\n}\n"],"names":["REACT_POSTPONE_TYPE","Symbol","for","isPostpone","error","$$typeof"],"mappings":"AAAA,MAAMA,sBAA8BC,OAAOC,GAAG,CAAC;AAE/C,OAAO,SAASC,WAAWC,KAAU;IACnC,OACE,OAAOA,UAAU,YACjBA,UAAU,QACVA,MAAMC,QAAQ,KAAKL;AAEvB","ignoreList":[0]}
import { InvariantError } from './invariant-error';
/**
* Throws an InvariantError indicating that a prerender-ppr code path was
* reached. The prerender-ppr work unit type has been removed and all code
* handling it is dead. Use this in exhaustive switch cases while the
* prerender-ppr type is being cleaned up.
*/ export function throwPrerenderPPRRemovedError() {
throw Object.defineProperty(new InvariantError('The prerender-ppr work unit type has been removed. This code path should be unreachable.'), "__NEXT_ERROR_CODE", {
value: "E1158",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=ppr-removed-error.js.map
{"version":3,"sources":["../../../../src/shared/lib/ppr-removed-error.ts"],"sourcesContent":["import { InvariantError } from './invariant-error'\n\n/**\n * Throws an InvariantError indicating that a prerender-ppr code path was\n * reached. The prerender-ppr work unit type has been removed and all code\n * handling it is dead. Use this in exhaustive switch cases while the\n * prerender-ppr type is being cleaned up.\n */\nexport function throwPrerenderPPRRemovedError(): never {\n throw new InvariantError(\n 'The prerender-ppr work unit type has been removed. This code path should be unreachable.'\n )\n}\n"],"names":["InvariantError","throwPrerenderPPRRemovedError"],"mappings":"AAAA,SAASA,cAAc,QAAQ,oBAAmB;AAElD;;;;;CAKC,GACD,OAAO,SAASC;IACd,MAAM,qBAEL,CAFK,IAAID,eACR,6FADI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF","ignoreList":[0]}
export { Postpone } from '../dynamic-rendering';
/*
Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/ // When postpone is available in canary React we can switch to importing it directly
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Postpone", {
enumerable: true,
get: function() {
return _dynamicrendering.Postpone;
}
});
const _dynamicrendering = require("../dynamic-rendering");
//# sourceMappingURL=postpone.js.map
{"version":3,"sources":["../../../../src/server/app-render/rsc/postpone.ts"],"sourcesContent":["/*\n\nFiles in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.\n\n*/\n\n// When postpone is available in canary React we can switch to importing it directly\nexport { Postpone } from '../dynamic-rendering'\n"],"names":["Postpone"],"mappings":"AAAA;;;;AAIA,GAEA,oFAAoF;;;;;+BAC3EA;;;eAAAA,0BAAQ;;;kCAAQ","ignoreList":[0]}
/**
* If set to `incremental`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, the options for
* `experimental_ppr` will be ignored.
*/
export type ExperimentalPPRConfig = boolean | 'incremental';
/**
* Returns true if partial prerendering is enabled for the application. It does
* not tell you if a given route has PPR enabled, as that requires analysis of
* the route's configuration.
*
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
*/
export declare function checkIsAppPPREnabled(config: ExperimentalPPRConfig | undefined): boolean;
/**
* Returns true if partial prerendering is supported for the current page with
* the provided app configuration. If the application doesn't have partial
* prerendering enabled, this function will always return false. If you want to
* check if the application has partial prerendering enabled
*
* @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.
*/
export declare function checkIsRoutePPREnabled(config: ExperimentalPPRConfig | undefined): boolean;
/**
* If set to `incremental`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, the options for
* `experimental_ppr` will be ignored.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
checkIsAppPPREnabled: null,
checkIsRoutePPREnabled: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
checkIsAppPPREnabled: function() {
return checkIsAppPPREnabled;
},
checkIsRoutePPREnabled: function() {
return checkIsRoutePPREnabled;
}
});
function checkIsAppPPREnabled(config) {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false;
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config;
// If the config is a string, it must be 'incremental' to enable partial
// prerendering.
if (config === 'incremental') return true;
return false;
}
function checkIsRoutePPREnabled(config) {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false;
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config;
return false;
}
//# sourceMappingURL=ppr.js.map
{"version":3,"sources":["../../../../src/server/lib/experimental/ppr.ts"],"sourcesContent":["/**\n * If set to `incremental`, only those leaf pages that export\n * `experimental_ppr = true` will have partial prerendering enabled. If any\n * page exports this value as `false` or does not export it at all will not\n * have partial prerendering enabled. If set to a boolean, the options for\n * `experimental_ppr` will be ignored.\n */\n\nexport type ExperimentalPPRConfig = boolean | 'incremental'\n\n/**\n * Returns true if partial prerendering is enabled for the application. It does\n * not tell you if a given route has PPR enabled, as that requires analysis of\n * the route's configuration.\n *\n * @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.\n */\nexport function checkIsAppPPREnabled(\n config: ExperimentalPPRConfig | undefined\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n // If the config is a string, it must be 'incremental' to enable partial\n // prerendering.\n if (config === 'incremental') return true\n\n return false\n}\n\n/**\n * Returns true if partial prerendering is supported for the current page with\n * the provided app configuration. If the application doesn't have partial\n * prerendering enabled, this function will always return false. If you want to\n * check if the application has partial prerendering enabled\n *\n * @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.\n */\nexport function checkIsRoutePPREnabled(\n config: ExperimentalPPRConfig | undefined\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n return false\n}\n"],"names":["checkIsAppPPREnabled","checkIsRoutePPREnabled","config"],"mappings":"AAAA;;;;;;CAMC;;;;;;;;;;;;;;;IAWeA,oBAAoB;eAApBA;;IAwBAC,sBAAsB;eAAtBA;;;AAxBT,SAASD,qBACdE,MAAyC;IAEzC,gEAAgE;IAChE,IAAI,OAAOA,WAAW,aAAa,OAAO;IAE1C,+CAA+C;IAC/C,IAAI,OAAOA,WAAW,WAAW,OAAOA;IAExC,wEAAwE;IACxE,gBAAgB;IAChB,IAAIA,WAAW,eAAe,OAAO;IAErC,OAAO;AACT;AAUO,SAASD,uBACdC,MAAyC;IAEzC,gEAAgE;IAChE,IAAI,OAAOA,WAAW,aAAa,OAAO;IAE1C,+CAA+C;IAC/C,IAAI,OAAOA,WAAW,WAAW,OAAOA;IAExC,OAAO;AACT","ignoreList":[0]}
export declare function isPostpone(error: any): boolean;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isPostpone", {
enumerable: true,
get: function() {
return isPostpone;
}
});
const REACT_POSTPONE_TYPE = Symbol.for('react.postpone');
function isPostpone(error) {
return typeof error === 'object' && error !== null && error.$$typeof === REACT_POSTPONE_TYPE;
}
//# sourceMappingURL=is-postpone.js.map
{"version":3,"sources":["../../../../src/server/lib/router-utils/is-postpone.ts"],"sourcesContent":["const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')\n\nexport function isPostpone(error: any): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n error.$$typeof === REACT_POSTPONE_TYPE\n )\n}\n"],"names":["isPostpone","REACT_POSTPONE_TYPE","Symbol","for","error","$$typeof"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAFhB,MAAMC,sBAA8BC,OAAOC,GAAG,CAAC;AAExC,SAASH,WAAWI,KAAU;IACnC,OACE,OAAOA,UAAU,YACjBA,UAAU,QACVA,MAAMC,QAAQ,KAAKJ;AAEvB","ignoreList":[0]}
/**
* Throws an InvariantError indicating that a prerender-ppr code path was
* reached. The prerender-ppr work unit type has been removed and all code
* handling it is dead. Use this in exhaustive switch cases while the
* prerender-ppr type is being cleaned up.
*/
export declare function throwPrerenderPPRRemovedError(): never;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "throwPrerenderPPRRemovedError", {
enumerable: true,
get: function() {
return throwPrerenderPPRRemovedError;
}
});
const _invarianterror = require("./invariant-error");
function throwPrerenderPPRRemovedError() {
throw Object.defineProperty(new _invarianterror.InvariantError('The prerender-ppr work unit type has been removed. This code path should be unreachable.'), "__NEXT_ERROR_CODE", {
value: "E1158",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=ppr-removed-error.js.map
{"version":3,"sources":["../../../src/shared/lib/ppr-removed-error.ts"],"sourcesContent":["import { InvariantError } from './invariant-error'\n\n/**\n * Throws an InvariantError indicating that a prerender-ppr code path was\n * reached. The prerender-ppr work unit type has been removed and all code\n * handling it is dead. Use this in exhaustive switch cases while the\n * prerender-ppr type is being cleaned up.\n */\nexport function throwPrerenderPPRRemovedError(): never {\n throw new InvariantError(\n 'The prerender-ppr work unit type has been removed. This code path should be unreachable.'\n )\n}\n"],"names":["throwPrerenderPPRRemovedError","InvariantError"],"mappings":";;;;+BAQgBA;;;eAAAA;;;gCARe;AAQxB,SAASA;IACd,MAAM,qBAEL,CAFK,IAAIC,8BAAc,CACtB,6FADI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF","ignoreList":[0]}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display