Unverified Commit 7958c79b authored by Sebastian Markbåge's avatar Sebastian Markbåge Committed by GitHub

Rename StaticGenerationStore to WorkStore (#70721)

This has long been a misnomer since it's not just used for static
generation but it's the outer context of all the "Work" we're currently
doing.

A follow up will merge the other contexts into a "WorkUnitStore".
parent 39e06c75
...@@ -34,14 +34,14 @@ const routeModule = new AppRouteRouteModule({ ...@@ -34,14 +34,14 @@ const routeModule = new AppRouteRouteModule({
// are used to hook into the route. // are used to hook into the route.
const { const {
requestAsyncStorage, requestAsyncStorage,
staticGenerationAsyncStorage, workAsyncStorage,
prerenderAsyncStorage, prerenderAsyncStorage,
serverHooks, serverHooks,
} = routeModule } = routeModule
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
staticGenerationAsyncStorage, workAsyncStorage,
requestAsyncStorage, requestAsyncStorage,
prerenderAsyncStorage, prerenderAsyncStorage,
}) })
...@@ -50,7 +50,7 @@ function patchFetch() { ...@@ -50,7 +50,7 @@ function patchFetch() {
export { export {
routeModule, routeModule,
requestAsyncStorage, requestAsyncStorage,
staticGenerationAsyncStorage, workAsyncStorage,
serverHooks, serverHooks,
patchFetch, patchFetch,
} }
...@@ -75,7 +75,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa ...@@ -75,7 +75,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getRuntimeContext } from '../server/web/sandbox' import { getRuntimeContext } from '../server/web/sandbox'
import { isClientReference } from '../lib/client-reference' import { isClientReference } from '../lib/client-reference'
import { withStaticGenerationStore } from '../server/async-storage/with-static-generation-store' import { withWorkStore } from '../server/async-storage/with-work-store'
import type { CacheHandler } from '../server/lib/incremental-cache' import type { CacheHandler } from '../server/lib/incremental-cache'
import { IncrementalCache } from '../server/lib/incremental-cache' import { IncrementalCache } from '../server/lib/incremental-cache'
import { nodeFs } from '../server/lib/node-fs-methods' import { nodeFs } from '../server/lib/node-fs-methods'
...@@ -1294,8 +1294,8 @@ export async function buildAppStaticPaths({ ...@@ -1294,8 +1294,8 @@ export async function buildAppStaticPaths({
} }
} }
const routeParams = await withStaticGenerationStore( const routeParams = await withWorkStore(
ComponentMod.staticGenerationAsyncStorage, ComponentMod.workAsyncStorage,
{ {
page, page,
// We're discovering the parameters here, so we don't have any unknown // We're discovering the parameters here, so we don't have any unknown
......
...@@ -130,7 +130,7 @@ const browserNonTranspileModules = [ ...@@ -130,7 +130,7 @@ const browserNonTranspileModules = [
const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/ const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/
const asyncStoragesRegex = const asyncStoragesRegex =
/next[\\/]dist[\\/](esm[\\/])?client[\\/]components[\\/](static-generation-async-storage|action-async-storage|request-async-storage)/ /next[\\/]dist[\\/](esm[\\/])?client[\\/]components[\\/](work-async-storage|action-async-storage|request-async-storage)/
// Support for NODE_PATH // Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '') const nodePathList = (process.env.NODE_PATH || '')
......
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external' import { workAsyncStorage } from './work-async-storage.external'
export function bailoutToClientRendering(reason: string): void | never { export function bailoutToClientRendering(reason: string): void | never {
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if (staticGenerationStore?.forceStatic) return if (workStore?.forceStatic) return
if (staticGenerationStore?.isStaticGeneration) if (workStore?.isStaticGeneration) throw new BailoutToCSRError(reason)
throw new BailoutToCSRError(reason)
} }
...@@ -26,17 +26,17 @@ export function ClientPageRoot({ ...@@ -26,17 +26,17 @@ export function ClientPageRoot({
promises?: Array<Promise<any>> promises?: Array<Promise<any>>
}) { }) {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { staticGenerationAsyncStorage } = const { workAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external') require('./work-async-storage.external') as typeof import('./work-async-storage.external')
let clientSearchParams: Promise<ParsedUrlQuery> let clientSearchParams: Promise<ParsedUrlQuery>
let clientParams: Promise<Params> let clientParams: Promise<Params>
// We are going to instrument the searchParams prop with tracking for the // We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering // appropriate context. We wrap differently in prerendering vs rendering
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (!store) { if (!store) {
throw new InvariantError( throw new InvariantError(
'Expected staticGenerationStore to exist when handling searchParams in a client Page.' 'Expected workStore to exist when handling searchParams in a client Page.'
) )
} }
......
...@@ -25,16 +25,16 @@ export function ClientSegmentRoot({ ...@@ -25,16 +25,16 @@ export function ClientSegmentRoot({
promise?: Promise<any> promise?: Promise<any>
}) { }) {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { staticGenerationAsyncStorage } = const { workAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external') require('./work-async-storage.external') as typeof import('./work-async-storage.external')
let clientParams: Promise<Params> let clientParams: Promise<Params>
// We are going to instrument the searchParams prop with tracking for the // We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering // appropriate context. We wrap differently in prerendering vs rendering
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (!store) { if (!store) {
throw new InvariantError( throw new InvariantError(
'Expected staticGenerationStore to exist when handling params in a client segment such as a Layout or Template.' 'Expected workStore to exist when handling params in a client segment such as a Layout or Template.'
) )
} }
......
...@@ -4,7 +4,7 @@ import React, { type JSX } from 'react' ...@@ -4,7 +4,7 @@ import React, { type JSX } from 'react'
import { useUntrackedPathname } from './navigation-untracked' import { useUntrackedPathname } from './navigation-untracked'
import { isNextRouterError } from './is-next-router-error' import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler' import { handleHardNavError } from './nav-failure-handler'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external' import { workAsyncStorage } from './work-async-storage.external'
const styles = { const styles = {
error: { error: {
...@@ -52,7 +52,7 @@ interface ErrorBoundaryHandlerState { ...@@ -52,7 +52,7 @@ interface ErrorBoundaryHandlerState {
// function crashes so we can maintain our previous cache // function crashes so we can maintain our previous cache
// instead of caching the error page // instead of caching the error page
function HandleISRError({ error }: { error: any }) { function HandleISRError({ error }: { error: any }) {
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (store?.isRevalidate || store?.isStaticGeneration) { if (store?.isRevalidate || store?.isStaticGeneration) {
console.error(error) console.error(error)
throw error throw error
......
...@@ -10,13 +10,13 @@ import { PathnameContext } from '../../shared/lib/hooks-client-context.shared-ru ...@@ -10,13 +10,13 @@ import { PathnameContext } from '../../shared/lib/hooks-client-context.shared-ru
function hasFallbackRouteParams() { function hasFallbackRouteParams() {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
// AsyncLocalStorage should not be included in the client bundle. // AsyncLocalStorage should not be included in the client bundle.
const { staticGenerationAsyncStorage } = const { workAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external') require('./work-async-storage.external') as typeof import('./work-async-storage.external')
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if (!staticGenerationStore) return false if (!workStore) return false
const { fallbackRouteParams } = staticGenerationStore const { fallbackRouteParams } = workStore
if (!fallbackRouteParams || fallbackRouteParams.size === 0) return false if (!fallbackRouteParams || fallbackRouteParams.size === 0) return false
return true return true
......
import type { StaticGenerationAsyncStorage } from './static-generation-async-storage.external'
import { createAsyncLocalStorage } from './async-local-storage'
export const staticGenerationAsyncStorage: StaticGenerationAsyncStorage =
createAsyncLocalStorage()
import type { WorkAsyncStorage } from './work-async-storage.external'
import { createAsyncLocalStorage } from './async-local-storage'
export const workAsyncStorage: WorkAsyncStorage = createAsyncLocalStorage()
...@@ -6,10 +6,10 @@ import type { Revalidate } from '../../server/lib/revalidate' ...@@ -6,10 +6,10 @@ import type { Revalidate } from '../../server/lib/revalidate'
import type { FallbackRouteParams } from '../../server/request/fallback-params' import type { FallbackRouteParams } from '../../server/request/fallback-params'
// Share the instance module in the next-shared layer // Share the instance module in the next-shared layer
import { staticGenerationAsyncStorage } from './static-generation-async-storage-instance' with { 'turbopack-transition': 'next-shared' } import { workAsyncStorage } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import type { AppSegmentConfig } from '../../build/app-segments/app-segment-config' import type { AppSegmentConfig } from '../../build/app-segments/app-segment-config'
export interface StaticGenerationStore { export interface WorkStore {
readonly isStaticGeneration: boolean readonly isStaticGeneration: boolean
/** /**
...@@ -65,7 +65,6 @@ export interface StaticGenerationStore { ...@@ -65,7 +65,6 @@ export interface StaticGenerationStore {
buildId: string buildId: string
} }
export type StaticGenerationAsyncStorage = export type WorkAsyncStorage = AsyncLocalStorage<WorkStore>
AsyncLocalStorage<StaticGenerationStore>
export { staticGenerationAsyncStorage } export { workAsyncStorage }
...@@ -21,7 +21,7 @@ import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-cs ...@@ -21,7 +21,7 @@ import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-cs
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node' import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers' import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers'
import type { FetchMetrics } from '../../server/base-http' import type { FetchMetrics } from '../../server/base-http'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { FallbackRouteParams } from '../../server/request/fallback-params' import type { FallbackRouteParams } from '../../server/request/fallback-params'
export const enum ExportedAppPageFiles { export const enum ExportedAppPageFiles {
...@@ -205,7 +205,7 @@ export async function exportAppPage( ...@@ -205,7 +205,7 @@ export async function exportAppPage(
let fetchMetrics: FetchMetrics | undefined let fetchMetrics: FetchMetrics | undefined
if (debugOutput) { if (debugOutput) {
const store = (renderOpts as any).store as StaticGenerationStore const store = (renderOpts as any).store as WorkStore
const { dynamicUsageDescription, dynamicUsageStack } = store const { dynamicUsageDescription, dynamicUsageStack } = store
fetchMetrics = store.fetchMetrics fetchMetrics = store.fetchMetrics
......
import type { AppRenderContext } from '../../server/app-render/app-render' import type { AppRenderContext } from '../../server/app-render/app-render'
import type { MetadataContext } from './types/resolvers' import type { MetadataContext } from './types/resolvers'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering' import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering'
export function createMetadataContext( export function createMetadataContext(
...@@ -17,7 +17,7 @@ export function createMetadataContext( ...@@ -17,7 +17,7 @@ export function createMetadataContext(
export function createTrackedMetadataContext( export function createTrackedMetadataContext(
pathname: string, pathname: string,
renderOpts: AppRenderContext['renderOpts'], renderOpts: AppRenderContext['renderOpts'],
staticGenerationStore: StaticGenerationStore | null workStore: WorkStore | null
): MetadataContext { ): MetadataContext {
return { return {
// Use the regular metadata context, but we trap the pathname access. // Use the regular metadata context, but we trap the pathname access.
...@@ -29,15 +29,12 @@ export function createTrackedMetadataContext( ...@@ -29,15 +29,12 @@ export function createTrackedMetadataContext(
// to provide it, and instead we should error. // to provide it, and instead we should error.
get pathname() { get pathname() {
if ( if (
staticGenerationStore && workStore &&
staticGenerationStore.isStaticGeneration && workStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams && workStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0 workStore.fallbackRouteParams.size > 0
) { ) {
trackFallbackParamAccessed( trackFallbackParamAccessed(workStore, 'metadata relative url resolving')
staticGenerationStore,
'metadata relative url resolving'
)
} }
return pathname return pathname
......
...@@ -32,7 +32,7 @@ import type { ...@@ -32,7 +32,7 @@ import type {
} from './types/metadata-interface' } from './types/metadata-interface'
import { isNotFoundError } from '../../client/components/not-found' import { isNotFoundError } from '../../client/components/not-found'
import type { MetadataContext } from './types/resolvers' import type { MetadataContext } from './types/resolvers'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
// Use a promise to share the status of the metadata resolving, // Use a promise to share the status of the metadata resolving,
// returning two components `MetadataTree` and `MetadataOutlet` // returning two components `MetadataTree` and `MetadataOutlet`
...@@ -48,7 +48,7 @@ export function createMetadataComponents({ ...@@ -48,7 +48,7 @@ export function createMetadataComponents({
appUsingSizeAdjustment, appUsingSizeAdjustment,
errorType, errorType,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore, workStore,
}: { }: {
tree: LoaderTree tree: LoaderTree
searchParams: Promise<ParsedUrlQuery> searchParams: Promise<ParsedUrlQuery>
...@@ -57,7 +57,7 @@ export function createMetadataComponents({ ...@@ -57,7 +57,7 @@ export function createMetadataComponents({
appUsingSizeAdjustment: boolean appUsingSizeAdjustment: boolean
errorType?: 'not-found' | 'redirect' errorType?: 'not-found' | 'redirect'
createServerParamsForMetadata: CreateServerParamsForMetadata createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore workStore: WorkStore
}): [React.ComponentType, () => Promise<void>] { }): [React.ComponentType, () => Promise<void>] {
function MetadataRoot() { function MetadataRoot() {
return ( return (
...@@ -75,7 +75,7 @@ export function createMetadataComponents({ ...@@ -75,7 +75,7 @@ export function createMetadataComponents({
searchParams, searchParams,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore, workStore,
errorType errorType
) )
} }
...@@ -91,7 +91,7 @@ export function createMetadataComponents({ ...@@ -91,7 +91,7 @@ export function createMetadataComponents({
searchParams, searchParams,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
} catch {} } catch {}
} }
...@@ -110,7 +110,7 @@ export function createMetadataComponents({ ...@@ -110,7 +110,7 @@ export function createMetadataComponents({
getDynamicParamFromSegment, getDynamicParamFromSegment,
metadataContext, metadataContext,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore, workStore,
errorType errorType
) )
} }
...@@ -127,7 +127,7 @@ export function createMetadataComponents({ ...@@ -127,7 +127,7 @@ export function createMetadataComponents({
getDynamicParamFromSegment, getDynamicParamFromSegment,
metadataContext, metadataContext,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
} catch {} } catch {}
} }
...@@ -155,7 +155,7 @@ async function getResolvedMetadataImpl( ...@@ -155,7 +155,7 @@ async function getResolvedMetadataImpl(
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext, metadataContext: MetadataContext,
createServerParamsForMetadata: CreateServerParamsForMetadata, createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
errorType?: 'not-found' | 'redirect' errorType?: 'not-found' | 'redirect'
): Promise<React.ReactNode> { ): Promise<React.ReactNode> {
const errorConvention = errorType === 'redirect' ? undefined : errorType const errorConvention = errorType === 'redirect' ? undefined : errorType
...@@ -166,7 +166,7 @@ async function getResolvedMetadataImpl( ...@@ -166,7 +166,7 @@ async function getResolvedMetadataImpl(
errorConvention, errorConvention,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
const elements: Array<React.ReactNode> = createMetadataElements( const elements: Array<React.ReactNode> = createMetadataElements(
await accumulateMetadata(metadataItems, metadataContext) await accumulateMetadata(metadataItems, metadataContext)
...@@ -187,7 +187,7 @@ async function getNotFoundMetadataImpl( ...@@ -187,7 +187,7 @@ async function getNotFoundMetadataImpl(
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext, metadataContext: MetadataContext,
createServerParamsForMetadata: CreateServerParamsForMetadata, createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<React.ReactNode> { ): Promise<React.ReactNode> {
const notFoundErrorConvention = 'not-found' const notFoundErrorConvention = 'not-found'
const notFoundMetadataItems = await resolveMetadataItems( const notFoundMetadataItems = await resolveMetadataItems(
...@@ -196,7 +196,7 @@ async function getNotFoundMetadataImpl( ...@@ -196,7 +196,7 @@ async function getNotFoundMetadataImpl(
notFoundErrorConvention, notFoundErrorConvention,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
const elements: Array<React.ReactNode> = createMetadataElements( const elements: Array<React.ReactNode> = createMetadataElements(
...@@ -217,7 +217,7 @@ async function getResolvedViewportImpl( ...@@ -217,7 +217,7 @@ async function getResolvedViewportImpl(
searchParams: Promise<ParsedUrlQuery>, searchParams: Promise<ParsedUrlQuery>,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata, createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
errorType?: 'not-found' | 'redirect' errorType?: 'not-found' | 'redirect'
): Promise<React.ReactNode> { ): Promise<React.ReactNode> {
const errorConvention = errorType === 'redirect' ? undefined : errorType const errorConvention = errorType === 'redirect' ? undefined : errorType
...@@ -228,7 +228,7 @@ async function getResolvedViewportImpl( ...@@ -228,7 +228,7 @@ async function getResolvedViewportImpl(
errorConvention, errorConvention,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
const elements: Array<React.ReactNode> = createViewportElements( const elements: Array<React.ReactNode> = createViewportElements(
await accumulateViewport(metadataItems) await accumulateViewport(metadataItems)
...@@ -248,7 +248,7 @@ async function getNotFoundViewportImpl( ...@@ -248,7 +248,7 @@ async function getNotFoundViewportImpl(
searchParams: Promise<ParsedUrlQuery>, searchParams: Promise<ParsedUrlQuery>,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata, createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<React.ReactNode> { ): Promise<React.ReactNode> {
const notFoundErrorConvention = 'not-found' const notFoundErrorConvention = 'not-found'
const notFoundMetadataItems = await resolveMetadataItems( const notFoundMetadataItems = await resolveMetadataItems(
...@@ -257,7 +257,7 @@ async function getNotFoundViewportImpl( ...@@ -257,7 +257,7 @@ async function getNotFoundViewportImpl(
notFoundErrorConvention, notFoundErrorConvention,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
const elements: Array<React.ReactNode> = createViewportElements( const elements: Array<React.ReactNode> = createViewportElements(
......
...@@ -53,7 +53,7 @@ import { getTracer } from '../../server/lib/trace/tracer' ...@@ -53,7 +53,7 @@ import { getTracer } from '../../server/lib/trace/tracer'
import { ResolveMetadataSpan } from '../../server/lib/trace/constants' import { ResolveMetadataSpan } from '../../server/lib/trace/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { import type {
Params, Params,
CreateServerParamsForMetadata, CreateServerParamsForMetadata,
...@@ -489,7 +489,7 @@ async function resolveMetadataItems( ...@@ -489,7 +489,7 @@ async function resolveMetadataItems(
errorConvention: 'not-found' | undefined, errorConvention: 'not-found' | undefined,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata, createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
const parentParams = {} const parentParams = {}
const metadataItems: MetadataItems = [] const metadataItems: MetadataItems = []
...@@ -505,7 +505,7 @@ async function resolveMetadataItems( ...@@ -505,7 +505,7 @@ async function resolveMetadataItems(
errorMetadataItem, errorMetadataItem,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
} }
...@@ -520,7 +520,7 @@ async function resolveMetadataItemsImpl( ...@@ -520,7 +520,7 @@ async function resolveMetadataItemsImpl(
errorMetadataItem: MetadataItems[number], errorMetadataItem: MetadataItems[number],
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata, createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<MetadataItems> { ): Promise<MetadataItems> {
const [segment, parallelRoutes, { page }] = tree const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix = const currentTreePrefix =
...@@ -540,10 +540,7 @@ async function resolveMetadataItemsImpl( ...@@ -540,10 +540,7 @@ async function resolveMetadataItemsImpl(
} }
} }
const params = createServerParamsForMetadata( const params = createServerParamsForMetadata(currentParams, workStore)
currentParams,
staticGenerationStore
)
let layerProps: LayoutProps | PageProps let layerProps: LayoutProps | PageProps
if (isPage) { if (isPage) {
...@@ -581,7 +578,7 @@ async function resolveMetadataItemsImpl( ...@@ -581,7 +578,7 @@ async function resolveMetadataItemsImpl(
errorMetadataItem, errorMetadataItem,
getDynamicParamFromSegment, getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore workStore
) )
} }
......
...@@ -8,7 +8,7 @@ import type { RequestLifecycleOpts } from '../base-server' ...@@ -8,7 +8,7 @@ import type { RequestLifecycleOpts } from '../base-server'
import type { AfterCallback, AfterTask } from './after' import type { AfterCallback, AfterTask } from './after'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { isThenable } from '../../shared/lib/is-thenable' import { isThenable } from '../../shared/lib/is-thenable'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { withExecuteRevalidates } from './revalidation-utils' import { withExecuteRevalidates } from './revalidation-utils'
export type AfterContextOpts = { export type AfterContextOpts = {
...@@ -107,9 +107,9 @@ export class AfterContext { ...@@ -107,9 +107,9 @@ export class AfterContext {
const readonlyRequestStore: RequestStore = const readonlyRequestStore: RequestStore =
wrapRequestStoreForAfterCallbacks(requestStore) wrapRequestStoreForAfterCallbacks(requestStore)
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
return withExecuteRevalidates(staticGenerationStore, () => return withExecuteRevalidates(workStore, () =>
requestAsyncStorage.run(readonlyRequestStore, async () => { requestAsyncStorage.run(readonlyRequestStore, async () => {
this.callbackQueue.start() this.callbackQueue.start()
await this.callbackQueue.onIdle() await this.callbackQueue.onIdle()
......
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external' import { getExpectedRequestStore } from '../../client/components/request-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering' import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'
...@@ -22,15 +22,15 @@ export function unstable_after<T>(task: AfterTask<T>) { ...@@ -22,15 +22,15 @@ export function unstable_after<T>(task: AfterTask<T>) {
) )
} }
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if (staticGenerationStore) { if (workStore) {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${staticGenerationStore.route} with \`dynamic = "force-static"\` couldn't be rendered statically because it used \`${callingExpression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${workStore.route} with \`dynamic = "force-static"\` couldn't be rendered statically because it used \`${callingExpression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
) )
} else { } else {
markCurrentScopeAsDynamic(staticGenerationStore, callingExpression) markCurrentScopeAsDynamic(workStore, callingExpression)
} }
} }
......
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
/** Run a callback, and execute any *new* revalidations added during its runtime. */ /** Run a callback, and execute any *new* revalidations added during its runtime. */
export async function withExecuteRevalidates<T>( export async function withExecuteRevalidates<T>(
store: StaticGenerationStore | undefined, store: WorkStore | undefined,
callback: () => Promise<T> callback: () => Promise<T>
): Promise<T> { ): Promise<T> {
if (!store) { if (!store) {
...@@ -25,14 +25,12 @@ export async function withExecuteRevalidates<T>( ...@@ -25,14 +25,12 @@ export async function withExecuteRevalidates<T>(
type RevalidationState = Required< type RevalidationState = Required<
Pick< Pick<
StaticGenerationStore, WorkStore,
'revalidatedTags' | 'pendingRevalidates' | 'pendingRevalidateWrites' 'revalidatedTags' | 'pendingRevalidates' | 'pendingRevalidateWrites'
> >
> >
function cloneRevalidationState( function cloneRevalidationState(store: WorkStore): RevalidationState {
store: StaticGenerationStore
): RevalidationState {
return { return {
revalidatedTags: store.revalidatedTags ? [...store.revalidatedTags] : [], revalidatedTags: store.revalidatedTags ? [...store.revalidatedTags] : [],
pendingRevalidates: { ...store.pendingRevalidates }, pendingRevalidates: { ...store.pendingRevalidates },
...@@ -62,7 +60,7 @@ function diffRevalidationState( ...@@ -62,7 +60,7 @@ function diffRevalidationState(
} }
async function executeRevalidates( async function executeRevalidates(
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
{ {
revalidatedTags, revalidatedTags,
pendingRevalidates, pendingRevalidates,
...@@ -70,7 +68,7 @@ async function executeRevalidates( ...@@ -70,7 +68,7 @@ async function executeRevalidates(
}: RevalidationState }: RevalidationState
) { ) {
return Promise.all([ return Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(revalidatedTags), workStore.incrementalCache?.revalidateTag(revalidatedTags),
...Object.values(pendingRevalidates), ...Object.values(pendingRevalidates),
...pendingRevalidateWrites, ...pendingRevalidateWrites,
]) ])
......
...@@ -20,7 +20,7 @@ import { ...@@ -20,7 +20,7 @@ import {
type RedirectType, type RedirectType,
} from '../../client/components/redirect' } from '../../client/components/redirect'
import RenderResult from '../render-result' import RenderResult from '../render-result'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import { FlightRenderResult } from './flight-render-result' import { FlightRenderResult } from './flight-render-result'
import { import {
filterReqHeaders, filterReqHeaders,
...@@ -110,19 +110,17 @@ function getForwardedHeaders( ...@@ -110,19 +110,17 @@ function getForwardedHeaders(
async function addRevalidationHeader( async function addRevalidationHeader(
res: BaseNextResponse, res: BaseNextResponse,
{ {
staticGenerationStore, workStore,
requestStore, requestStore,
}: { }: {
staticGenerationStore: StaticGenerationStore workStore: WorkStore
requestStore: RequestStore requestStore: RequestStore
} }
) { ) {
await Promise.all([ await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag( workStore.incrementalCache?.revalidateTag(workStore.revalidatedTags || []),
staticGenerationStore.revalidatedTags || [] ...Object.values(workStore.pendingRevalidates || {}),
), ...(workStore.pendingRevalidateWrites || []),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
...(staticGenerationStore.pendingRevalidateWrites || []),
]) ])
// If a tag was revalidated, the client router needs to invalidate all the // If a tag was revalidated, the client router needs to invalidate all the
...@@ -138,7 +136,7 @@ async function addRevalidationHeader( ...@@ -138,7 +136,7 @@ async function addRevalidationHeader(
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple // TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty. // is always empty.
const isTagRevalidated = staticGenerationStore.revalidatedTags?.length ? 1 : 0 const isTagRevalidated = workStore.revalidatedTags?.length ? 1 : 0
const isCookieRevalidated = getModifiedCookieValues( const isCookieRevalidated = getModifiedCookieValues(
requestStore.mutableCookies requestStore.mutableCookies
).length ).length
...@@ -160,7 +158,7 @@ async function createForwardedActionResponse( ...@@ -160,7 +158,7 @@ async function createForwardedActionResponse(
host: Host, host: Host,
workerPathname: string, workerPathname: string,
basePath: string, basePath: string,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
if (!host) { if (!host) {
throw new Error( throw new Error(
...@@ -175,8 +173,7 @@ async function createForwardedActionResponse( ...@@ -175,8 +173,7 @@ async function createForwardedActionResponse(
// with the response from the forwarded worker // with the response from the forwarded worker
forwardedHeaders.set('x-action-forwarded', '1') forwardedHeaders.set('x-action-forwarded', '1')
const proto = const proto = workStore.incrementalCache?.requestProtocol || 'https'
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
// For standalone or the serverful mode, use the internal origin directly // For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request. // other than the host headers from the request.
...@@ -281,7 +278,7 @@ async function createRedirectRenderResult( ...@@ -281,7 +278,7 @@ async function createRedirectRenderResult(
redirectUrl: string, redirectUrl: string,
redirectType: RedirectType, redirectType: RedirectType,
basePath: string, basePath: string,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`) res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`)
...@@ -306,8 +303,7 @@ async function createRedirectRenderResult( ...@@ -306,8 +303,7 @@ async function createRedirectRenderResult(
const forwardedHeaders = getForwardedHeaders(req, res) const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC_HEADER, '1') forwardedHeaders.set(RSC_HEADER, '1')
const proto = const proto = workStore.incrementalCache?.requestProtocol || 'https'
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
// For standalone or the serverful mode, use the internal origin directly // For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request. // other than the host headers from the request.
...@@ -318,15 +314,15 @@ async function createRedirectRenderResult( ...@@ -318,15 +314,15 @@ async function createRedirectRenderResult(
`${origin}${appRelativeRedirectUrl.pathname}${appRelativeRedirectUrl.search}` `${origin}${appRelativeRedirectUrl.pathname}${appRelativeRedirectUrl.search}`
) )
if (staticGenerationStore.revalidatedTags) { if (workStore.revalidatedTags) {
forwardedHeaders.set( forwardedHeaders.set(
NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER,
staticGenerationStore.revalidatedTags.join(',') workStore.revalidatedTags.join(',')
) )
forwardedHeaders.set( forwardedHeaders.set(
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
staticGenerationStore.incrementalCache?.prerenderManifest?.preview workStore.incrementalCache?.prerenderManifest?.preview?.previewModeId ||
?.previewModeId || '' ''
) )
} }
...@@ -416,7 +412,7 @@ export async function handleAction({ ...@@ -416,7 +412,7 @@ export async function handleAction({
ComponentMod, ComponentMod,
serverModuleMap, serverModuleMap,
generateFlight, generateFlight,
staticGenerationStore, workStore,
requestStore, requestStore,
serverActions, serverActions,
ctx, ctx,
...@@ -426,7 +422,7 @@ export async function handleAction({ ...@@ -426,7 +422,7 @@ export async function handleAction({
ComponentMod: AppPageModule ComponentMod: AppPageModule
serverModuleMap: ServerModuleMap serverModuleMap: ServerModuleMap
generateFlight: GenerateFlight generateFlight: GenerateFlight
staticGenerationStore: StaticGenerationStore workStore: WorkStore
requestStore: RequestStore requestStore: RequestStore
serverActions?: ServerActionsConfig serverActions?: ServerActionsConfig
ctx: AppRenderContext ctx: AppRenderContext
...@@ -457,14 +453,14 @@ export async function handleAction({ ...@@ -457,14 +453,14 @@ export async function handleAction({
return return
} }
if (staticGenerationStore.isStaticGeneration) { if (workStore.isStaticGeneration) {
throw new Error( throw new Error(
"Invariant: server actions can't be handled during static rendering" "Invariant: server actions can't be handled during static rendering"
) )
} }
// When running actions the default is no-store, you can still `cache: 'force-cache'` // When running actions the default is no-store, you can still `cache: 'force-cache'`
staticGenerationStore.fetchCache = 'default-no-store' workStore.fetchCache = 'default-no-store'
const originDomain = const originDomain =
typeof req.headers['origin'] === 'string' typeof req.headers['origin'] === 'string'
...@@ -530,11 +526,11 @@ export async function handleAction({ ...@@ -530,11 +526,11 @@ export async function handleAction({
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 res.statusCode = 500
await Promise.all([ await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag( workStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || [] workStore.revalidatedTags || []
), ),
...Object.values(staticGenerationStore.pendingRevalidates || {}), ...Object.values(workStore.pendingRevalidates || {}),
...(staticGenerationStore.pendingRevalidateWrites || []), ...(workStore.pendingRevalidateWrites || []),
]) ])
const promise = Promise.reject(error) const promise = Promise.reject(error)
...@@ -553,7 +549,7 @@ export async function handleAction({ ...@@ -553,7 +549,7 @@ export async function handleAction({
result: await generateFlight(req, ctx, { result: await generateFlight(req, ctx, {
actionResult: promise, actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree // if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated, skipFlight: !workStore.pathWasRevalidated,
}), }),
} }
} }
...@@ -595,7 +591,7 @@ export async function handleAction({ ...@@ -595,7 +591,7 @@ export async function handleAction({
host, host,
forwardedWorker, forwardedWorker,
ctx.renderOpts.basePath, ctx.renderOpts.basePath,
staticGenerationStore workStore
), ),
} }
} }
...@@ -839,15 +835,14 @@ export async function handleAction({ ...@@ -839,15 +835,14 @@ export async function handleAction({
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { if (isFetchAction) {
await addRevalidationHeader(res, { await addRevalidationHeader(res, {
staticGenerationStore, workStore,
requestStore, requestStore,
}) })
actionResult = await generateFlight(req, ctx, { actionResult = await generateFlight(req, ctx, {
actionResult: Promise.resolve(returnVal), actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree // if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
!staticGenerationStore.pathWasRevalidated || actionWasForwarded,
}) })
} }
}) })
...@@ -864,7 +859,7 @@ export async function handleAction({ ...@@ -864,7 +859,7 @@ export async function handleAction({
const redirectType = getRedirectTypeFromError(err) const redirectType = getRedirectTypeFromError(err)
await addRevalidationHeader(res, { await addRevalidationHeader(res, {
staticGenerationStore, workStore,
requestStore, requestStore,
}) })
...@@ -882,7 +877,7 @@ export async function handleAction({ ...@@ -882,7 +877,7 @@ export async function handleAction({
redirectUrl, redirectUrl,
redirectType, redirectType,
ctx.renderOpts.basePath, ctx.renderOpts.basePath,
staticGenerationStore workStore
), ),
} }
} }
...@@ -906,7 +901,7 @@ export async function handleAction({ ...@@ -906,7 +901,7 @@ export async function handleAction({
res.statusCode = 404 res.statusCode = 404
await addRevalidationHeader(res, { await addRevalidationHeader(res, {
staticGenerationStore, workStore,
requestStore, requestStore,
}) })
...@@ -937,11 +932,11 @@ export async function handleAction({ ...@@ -937,11 +932,11 @@ export async function handleAction({
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 res.statusCode = 500
await Promise.all([ await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag( workStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || [] workStore.revalidatedTags || []
), ),
...Object.values(staticGenerationStore.pendingRevalidates || {}), ...Object.values(workStore.pendingRevalidates || {}),
...(staticGenerationStore.pendingRevalidateWrites || []), ...(workStore.pendingRevalidateWrites || []),
]) ])
const promise = Promise.reject(err) const promise = Promise.reject(err)
try { try {
...@@ -959,8 +954,7 @@ export async function handleAction({ ...@@ -959,8 +954,7 @@ export async function handleAction({
result: await generateFlight(req, ctx, { result: await generateFlight(req, ctx, {
actionResult: promise, actionResult: promise,
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree // if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
!staticGenerationStore.pathWasRevalidated || actionWasForwarded,
}), }),
} }
} }
......
...@@ -87,7 +87,7 @@ async function createComponentTreeInternal({ ...@@ -87,7 +87,7 @@ async function createComponentTreeInternal({
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
const { const {
renderOpts: { nextConfigOutput, experimental }, renderOpts: { nextConfigOutput, experimental },
staticGenerationStore, workStore,
componentMod: { componentMod: {
NotFoundBoundary, NotFoundBoundary,
LayoutRouter, LayoutRouter,
...@@ -209,69 +209,66 @@ async function createComponentTreeInternal({ ...@@ -209,69 +209,66 @@ async function createComponentTreeInternal({
// if it's configured above any parent that configured // if it's configured above any parent that configured
// otherwise // otherwise
if (dynamic === 'error') { if (dynamic === 'error') {
staticGenerationStore.dynamicShouldError = true workStore.dynamicShouldError = true
} else if (dynamic === 'force-dynamic') { } else if (dynamic === 'force-dynamic') {
staticGenerationStore.forceDynamic = true workStore.forceDynamic = true
// TODO: (PPR) remove this bailout once PPR is the default // TODO: (PPR) remove this bailout once PPR is the default
if ( if (workStore.isStaticGeneration && !experimental.isRoutePPREnabled) {
staticGenerationStore.isStaticGeneration &&
!experimental.isRoutePPREnabled
) {
// If the postpone API isn't available, we can't postpone the render and // If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API. // therefore we can't use the dynamic API.
const err = new DynamicServerError( const err = new DynamicServerError(
`Page with \`dynamic = "force-dynamic"\` won't be rendered statically.` `Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`
) )
staticGenerationStore.dynamicUsageDescription = err.message workStore.dynamicUsageDescription = err.message
staticGenerationStore.dynamicUsageStack = err.stack workStore.dynamicUsageStack = err.stack
throw err throw err
} }
} else { } else {
staticGenerationStore.dynamicShouldError = false workStore.dynamicShouldError = false
staticGenerationStore.forceStatic = dynamic === 'force-static' workStore.forceStatic = dynamic === 'force-static'
} }
} }
if (typeof layoutOrPageMod?.fetchCache === 'string') { if (typeof layoutOrPageMod?.fetchCache === 'string') {
staticGenerationStore.fetchCache = layoutOrPageMod?.fetchCache workStore.fetchCache = layoutOrPageMod?.fetchCache
} }
if (typeof layoutOrPageMod?.revalidate !== 'undefined') { if (typeof layoutOrPageMod?.revalidate !== 'undefined') {
validateRevalidate(layoutOrPageMod?.revalidate, staticGenerationStore.route) validateRevalidate(layoutOrPageMod?.revalidate, workStore.route)
} }
if (typeof layoutOrPageMod?.revalidate === 'number') { if (typeof layoutOrPageMod?.revalidate === 'number') {
ctx.defaultRevalidate = layoutOrPageMod.revalidate as number ctx.defaultRevalidate = layoutOrPageMod.revalidate as number
if ( if (
typeof staticGenerationStore.revalidate === 'undefined' || typeof workStore.revalidate === 'undefined' ||
(typeof staticGenerationStore.revalidate === 'number' && (typeof workStore.revalidate === 'number' &&
staticGenerationStore.revalidate > ctx.defaultRevalidate) workStore.revalidate > ctx.defaultRevalidate)
) { ) {
staticGenerationStore.revalidate = ctx.defaultRevalidate workStore.revalidate = ctx.defaultRevalidate
} }
if ( if (
!staticGenerationStore.forceStatic && !workStore.forceStatic &&
staticGenerationStore.isStaticGeneration && workStore.isStaticGeneration &&
ctx.defaultRevalidate === 0 && ctx.defaultRevalidate === 0 &&
// If the postpone API isn't available, we can't postpone the render and // If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API. // therefore we can't use the dynamic API.
!experimental.isRoutePPREnabled !experimental.isRoutePPREnabled
) { ) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}` const dynamicUsageDescription = `revalidate: 0 configured ${segment}`
staticGenerationStore.dynamicUsageDescription = dynamicUsageDescription workStore.dynamicUsageDescription = dynamicUsageDescription
throw new DynamicServerError(dynamicUsageDescription) throw new DynamicServerError(dynamicUsageDescription)
} }
} }
const isStaticGeneration = staticGenerationStore.isStaticGeneration const isStaticGeneration = workStore.isStaticGeneration
// If there's a dynamic usage error attached to the store, throw it. // If there's a dynamic usage error attached to the store, throw it.
if (staticGenerationStore.dynamicUsageErr) { if (workStore.dynamicUsageErr) {
throw staticGenerationStore.dynamicUsageErr throw workStore.dynamicUsageErr
} }
const LayoutOrPage: React.ComponentType<any> | undefined = layoutOrPageMod const LayoutOrPage: React.ComponentType<any> | undefined = layoutOrPageMod
...@@ -491,8 +488,8 @@ async function createComponentTreeInternal({ ...@@ -491,8 +488,8 @@ async function createComponentTreeInternal({
// render force-dynamic. We should refactor this function so that we can correctly track which segments // render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic // need to be dynamic
if ( if (
staticGenerationStore.isStaticGeneration && workStore.isStaticGeneration &&
staticGenerationStore.forceDynamic && workStore.forceDynamic &&
experimental.isRoutePPREnabled experimental.isRoutePPREnabled
) { ) {
return [ return [
...@@ -505,7 +502,7 @@ async function createComponentTreeInternal({ ...@@ -505,7 +502,7 @@ async function createComponentTreeInternal({
> >
<Postpone <Postpone
reason='dynamic = "force-dynamic" was used' reason='dynamic = "force-dynamic" was used'
route={staticGenerationStore.route} route={workStore.route}
/> />
{layerAssets} {layerAssets}
</Segment>, </Segment>,
...@@ -534,11 +531,10 @@ async function createComponentTreeInternal({ ...@@ -534,11 +531,10 @@ async function createComponentTreeInternal({
if (isStaticGeneration) { if (isStaticGeneration) {
const promiseOfParams = createPrerenderParamsForClientSegment( const promiseOfParams = createPrerenderParamsForClientSegment(
currentParams, currentParams,
staticGenerationStore workStore
)
const promiseOfSearchParams = createPrerenderSearchParamsForClientPage(
staticGenerationStore
) )
const promiseOfSearchParams =
createPrerenderSearchParamsForClientPage(workStore)
pageElement = ( pageElement = (
<ClientPageRoot <ClientPageRoot
Component={PageComponent} Component={PageComponent}
...@@ -561,11 +557,11 @@ async function createComponentTreeInternal({ ...@@ -561,11 +557,11 @@ async function createComponentTreeInternal({
// the current render mode tracks dynamic API usage. // the current render mode tracks dynamic API usage.
const params = createServerParamsForServerSegment( const params = createServerParamsForServerSegment(
currentParams, currentParams,
staticGenerationStore workStore
) )
const searchParams = createServerSearchParamsForServerPage( const searchParams = createServerSearchParamsForServerPage(
query, query,
staticGenerationStore workStore
) )
pageElement = ( pageElement = (
<PageComponent params={params} searchParams={searchParams} /> <PageComponent params={params} searchParams={searchParams} />
...@@ -603,7 +599,7 @@ async function createComponentTreeInternal({ ...@@ -603,7 +599,7 @@ async function createComponentTreeInternal({
if (isStaticGeneration) { if (isStaticGeneration) {
const promiseOfParams = createPrerenderParamsForClientSegment( const promiseOfParams = createPrerenderParamsForClientSegment(
currentParams, currentParams,
staticGenerationStore workStore
) )
clientSegment = ( clientSegment = (
...@@ -696,7 +692,7 @@ async function createComponentTreeInternal({ ...@@ -696,7 +692,7 @@ async function createComponentTreeInternal({
} else { } else {
const params = createServerParamsForServerSegment( const params = createServerParamsForServerSegment(
currentParams, currentParams,
staticGenerationStore workStore
) )
let serverSegment = ( let serverSegment = (
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
* read that data outside the cache and pass it in as an argument to the cached function. * read that data outside the cache and pass it in as an argument to the cached function.
*/ */
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly // Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react' import React from 'react'
...@@ -32,7 +32,7 @@ import { ...@@ -32,7 +32,7 @@ import {
prerenderAsyncStorage, prerenderAsyncStorage,
type PrerenderStore, type PrerenderStore,
} from './prerender-async-storage.external' } from './prerender-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
const hasPostpone = typeof React.unstable_postpone === 'function' const hasPostpone = typeof React.unstable_postpone === 'function'
...@@ -87,7 +87,7 @@ export function getFirstDynamicReason( ...@@ -87,7 +87,7 @@ export function getFirstDynamicReason(
* it during a normal prerender will cause the entire prerender to abort * it during a normal prerender will cause the entire prerender to abort
*/ */
export function markCurrentScopeAsDynamic( export function markCurrentScopeAsDynamic(
store: StaticGenerationStore, store: WorkStore,
expression: string expression: string
): void { ): void {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope // inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
...@@ -152,7 +152,7 @@ export function markCurrentScopeAsDynamic( ...@@ -152,7 +152,7 @@ export function markCurrentScopeAsDynamic(
* @param expression The expression that was accessed dynamically * @param expression The expression that was accessed dynamically
*/ */
export function trackFallbackParamAccessed( export function trackFallbackParamAccessed(
store: StaticGenerationStore, store: WorkStore,
expression: string expression: string
): void { ): void {
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
...@@ -171,7 +171,7 @@ export function trackFallbackParamAccessed( ...@@ -171,7 +171,7 @@ export function trackFallbackParamAccessed(
* Also during a PPR Prerender we postpone * Also during a PPR Prerender we postpone
*/ */
export function trackDynamicDataAccessed( export function trackDynamicDataAccessed(
store: StaticGenerationStore, store: WorkStore,
expression: string expression: string
): void { ): void {
if (store.isUnstableCacheCallback) { if (store.isUnstableCacheCallback) {
...@@ -229,7 +229,7 @@ export function trackDynamicDataAccessed( ...@@ -229,7 +229,7 @@ export function trackDynamicDataAccessed(
*/ */
export function throwToInterruptStaticGeneration( export function throwToInterruptStaticGeneration(
expression: string, expression: string,
store: StaticGenerationStore store: WorkStore
): never { ): never {
store.revalidate = 0 store.revalidate = 0
...@@ -250,7 +250,7 @@ export function throwToInterruptStaticGeneration( ...@@ -250,7 +250,7 @@ export function throwToInterruptStaticGeneration(
* *
* @internal * @internal
*/ */
export function trackDynamicDataInDynamicRender(store: StaticGenerationStore) { export function trackDynamicDataInDynamicRender(store: WorkStore) {
store.revalidate = 0 store.revalidate = 0
} }
...@@ -523,13 +523,13 @@ export function annotateDynamicAccess( ...@@ -523,13 +523,13 @@ export function annotateDynamicAccess(
export function useDynamicRouteParams(expression: string) { export function useDynamicRouteParams(expression: string) {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if ( if (
staticGenerationStore && workStore &&
staticGenerationStore.isStaticGeneration && workStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams && workStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0 workStore.fallbackRouteParams.size > 0
) { ) {
// There are fallback route params, we should track these as dynamic // There are fallback route params, we should track these as dynamic
// accesses. // accesses.
...@@ -544,14 +544,14 @@ export function useDynamicRouteParams(expression: string) { ...@@ -544,14 +544,14 @@ export function useDynamicRouteParams(expression: string) {
} else { } else {
// We're prerendering with PPR // We're prerendering with PPR
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} }
} else { } else {
// We're prerendering in legacy mode // We're prerendering in legacy mode
throwToInterruptStaticGeneration(expression, staticGenerationStore) throwToInterruptStaticGeneration(expression, workStore)
} }
} }
} }
......
...@@ -11,7 +11,7 @@ export { prerender } from 'react-server-dom-webpack/static.edge' ...@@ -11,7 +11,7 @@ export { prerender } from 'react-server-dom-webpack/static.edge'
import LayoutRouter from '../../client/components/layout-router' import LayoutRouter from '../../client/components/layout-router'
import RenderFromTemplateContext from '../../client/components/render-from-template-context' import RenderFromTemplateContext from '../../client/components/render-from-template-context'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { requestAsyncStorage } from '../../client/components/request-async-storage.external' import { requestAsyncStorage } from '../../client/components/request-async-storage.external'
import { prerenderAsyncStorage } from './prerender-async-storage.external' import { prerenderAsyncStorage } from './prerender-async-storage.external'
import { actionAsyncStorage } from '../../client/components/action-async-storage.external' import { actionAsyncStorage } from '../../client/components/action-async-storage.external'
...@@ -42,7 +42,7 @@ import { taintObjectReference } from './rsc/taint' ...@@ -42,7 +42,7 @@ import { taintObjectReference } from './rsc/taint'
// in the experimental channel of React, so export it from here so that it comes from the bundled runtime // in the experimental channel of React, so export it from here so that it comes from the bundled runtime
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
staticGenerationAsyncStorage, workAsyncStorage,
requestAsyncStorage, requestAsyncStorage,
prerenderAsyncStorage, prerenderAsyncStorage,
}) })
...@@ -51,7 +51,7 @@ function patchFetch() { ...@@ -51,7 +51,7 @@ function patchFetch() {
export { export {
LayoutRouter, LayoutRouter,
RenderFromTemplateContext, RenderFromTemplateContext,
staticGenerationAsyncStorage, workAsyncStorage,
requestAsyncStorage, requestAsyncStorage,
actionAsyncStorage, actionAsyncStorage,
createServerSearchParamsForServerPage, createServerSearchParamsForServerPage,
......
import type { WithStore } from './with-store' import type { WithStore } from './with-store'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import type { IncrementalCache } from '../lib/incremental-cache' import type { IncrementalCache } from '../lib/incremental-cache'
import type { RenderOptsPartial } from '../app-render/types' import type { RenderOptsPartial } from '../app-render/types'
import type { FetchMetric } from '../base-http' import type { FetchMetric } from '../base-http'
import type { RequestLifecycleOpts } from '../base-server' import type { RequestLifecycleOpts } from '../base-server'
import type { FallbackRouteParams } from '../../server/request/fallback-params' import type { FallbackRouteParams } from '../request/fallback-params'
import type { AppSegmentConfig } from '../../build/app-segments/app-segment-config' import type { AppSegmentConfig } from '../../build/app-segments/app-segment-config'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
export type StaticGenerationContext = { export type WorkStoreContext = {
/** /**
* The page that is being rendered. This relates to the path to the page file. * The page that is being rendered. This relates to the path to the page file.
*/ */
...@@ -47,7 +47,7 @@ export type StaticGenerationContext = { ...@@ -47,7 +47,7 @@ export type StaticGenerationContext = {
* @deprecated should only be used as a temporary workaround * @deprecated should only be used as a temporary workaround
*/ */
// TODO: remove this when we resolve accessing the store outside the execution context // TODO: remove this when we resolve accessing the store outside the execution context
store?: StaticGenerationStore store?: WorkStore
} & Pick< } & Pick<
// Pull some properties from RenderOptsPartial so that the docs are also // Pull some properties from RenderOptsPartial so that the docs are also
// mirrored. // mirrored.
...@@ -62,19 +62,16 @@ export type StaticGenerationContext = { ...@@ -62,19 +62,16 @@ export type StaticGenerationContext = {
Partial<RequestLifecycleOpts> Partial<RequestLifecycleOpts>
} }
export const withStaticGenerationStore: WithStore< export const withWorkStore: WithStore<WorkStore, WorkStoreContext> = <Result>(
StaticGenerationStore, storage: AsyncLocalStorage<WorkStore>,
StaticGenerationContext
> = <Result>(
storage: AsyncLocalStorage<StaticGenerationStore>,
{ {
page, page,
fallbackRouteParams, fallbackRouteParams,
renderOpts, renderOpts,
requestEndedState, requestEndedState,
isPrefetchRequest, isPrefetchRequest,
}: StaticGenerationContext, }: WorkStoreContext,
callback: (store: StaticGenerationStore) => Result callback: (store: WorkStore) => Result
): Result => { ): Result => {
/** /**
* Rules of Static & Dynamic HTML: * Rules of Static & Dynamic HTML:
...@@ -98,7 +95,7 @@ export const withStaticGenerationStore: WithStore< ...@@ -98,7 +95,7 @@ export const withStaticGenerationStore: WithStore<
!renderOpts.isDraftMode && !renderOpts.isDraftMode &&
!renderOpts.isServerAction !renderOpts.isServerAction
const store: StaticGenerationStore = { const store: WorkStore = {
isStaticGeneration, isStaticGeneration,
page, page,
fallbackRouteParams, fallbackRouteParams,
......
import { AsyncLocalStorage } from 'node:async_hooks' import { AsyncLocalStorage } from 'node:async_hooks'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type { RequestStore } from '../../client/components/request-async-storage.external'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { IncrementalCache } from './incremental-cache' import type { IncrementalCache } from './incremental-cache'
import { createPatchedFetcher } from './patch-fetch' import { createPatchedFetcher } from './patch-fetch'
import type { PrerenderStore } from '../app-render/prerender-async-storage.external' import type { PrerenderStore } from '../app-render/prerender-async-storage.external'
...@@ -22,15 +22,14 @@ describe('createPatchedFetcher', () => { ...@@ -22,15 +22,14 @@ describe('createPatchedFetcher', () => {
mockFetch.mockResolvedValue(new Response(readableStream)) mockFetch.mockResolvedValue(new Response(readableStream))
const staticGenerationAsyncStorage = const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
new AsyncLocalStorage<StaticGenerationStore>()
const prerenderAsyncStorage = new AsyncLocalStorage<PrerenderStore>() const prerenderAsyncStorage = new AsyncLocalStorage<PrerenderStore>()
const patchedFetch = createPatchedFetcher(mockFetch, { const patchedFetch = createPatchedFetcher(mockFetch, {
// requestAsyncStorage does not need to provide a store for this test. // requestAsyncStorage does not need to provide a store for this test.
requestAsyncStorage: new AsyncLocalStorage<RequestStore>(), requestAsyncStorage: new AsyncLocalStorage<RequestStore>(),
staticGenerationAsyncStorage, workAsyncStorage,
prerenderAsyncStorage, prerenderAsyncStorage,
}) })
...@@ -47,56 +46,53 @@ describe('createPatchedFetcher', () => { ...@@ -47,56 +46,53 @@ describe('createPatchedFetcher', () => {
lock: jest.fn(() => resolveIncrementalCacheSet), lock: jest.fn(() => resolveIncrementalCacheSet),
} as unknown as IncrementalCache } as unknown as IncrementalCache
// We only need to provide a few of the StaticGenerationStore properties. // We only need to provide a few of the WorkStore properties.
const staticGenerationStore: Partial<StaticGenerationStore> = { const workStore: Partial<WorkStore> = {
page: '/', page: '/',
route: '/', route: '/',
incrementalCache, incrementalCache,
} }
await staticGenerationAsyncStorage.run( await workAsyncStorage.run(workStore as WorkStore, async () => {
staticGenerationStore as StaticGenerationStore, const response = await patchedFetch('https://example.com', {
async () => { cache: 'force-cache',
const response = await patchedFetch('https://example.com', { })
cache: 'force-cache',
})
if (!response.body) { if (!response.body) {
throw new Error(`Response body is ${JSON.stringify(response.body)}.`) throw new Error(`Response body is ${JSON.stringify(response.body)}.`)
} }
const reader = response.body.getReader() const reader = response.body.getReader()
let result = await reader.read() let result = await reader.read()
const textDecoder = new TextDecoder() const textDecoder = new TextDecoder()
expect(textDecoder.decode(result.value)).toBe('stream start') expect(textDecoder.decode(result.value)).toBe('stream start')
streamChunk() streamChunk()
result = await reader.read() result = await reader.read()
expect(textDecoder.decode(result.value)).toBe('stream end') expect(textDecoder.decode(result.value)).toBe('stream end')
await incrementalCacheSetPromise await incrementalCacheSetPromise
expect(incrementalCache.set).toHaveBeenCalledWith( expect(incrementalCache.set).toHaveBeenCalledWith(
'test-cache-key', 'test-cache-key',
{ {
data: { data: {
body: btoa('stream startstream end'), body: btoa('stream startstream end'),
headers: {}, headers: {},
status: 200, status: 200,
url: '', // the mocked response does not have a URL url: '', // the mocked response does not have a URL
},
kind: 'FETCH',
revalidate: 31536000, // default of one year
}, },
{ kind: 'FETCH',
fetchCache: true, revalidate: 31536000, // default of one year
fetchIdx: 1, },
fetchUrl: 'https://example.com/', {
revalidate: false, fetchCache: true,
tags: [], fetchIdx: 1,
} fetchUrl: 'https://example.com/',
) revalidate: false,
} tags: [],
) }
)
})
// Setting a lower timeout than default, because the test will fail with a // Setting a lower timeout than default, because the test will fail with a
// timeout when we regress and buffer the response. // timeout when we regress and buffer the response.
}, 1000) }, 1000)
......
This diff is collapsed.
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, prerenderAsyncStorage,
...@@ -17,23 +17,23 @@ import { makeHangingPromise } from '../dynamic-rendering-utils' ...@@ -17,23 +17,23 @@ import { makeHangingPromise } from '../dynamic-rendering-utils'
* During prerendering it will never resolve and during rendering it resolves immediately. * During prerendering it will never resolve and during rendering it resolves immediately.
*/ */
export function connection(): Promise<void> { export function connection(): Promise<void> {
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
if (staticGenerationStore) { if (workStore) {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
// headers object without tracking // headers object without tracking
return Promise.resolve(undefined) return Promise.resolve(undefined)
} }
if (staticGenerationStore.isUnstableCacheCallback) { if (workStore.isUnstableCacheCallback) {
throw new Error( throw new Error(
`Route ${staticGenerationStore.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` `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`
) )
} else if (staticGenerationStore.dynamicShouldError) { } else if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${staticGenerationStore.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` `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`
) )
} }
...@@ -53,19 +53,19 @@ export function connection(): Promise<void> { ...@@ -53,19 +53,19 @@ export function connection(): Promise<void> {
// to keep continuity with how headers has worked in PPR without dynamicIO. // to keep continuity with how headers has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access intead // TODO consider switching the semantic to throw on property access intead
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
'connection', 'connection',
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} }
} else if (staticGenerationStore.isStaticGeneration) { } else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We treat this function call as a bailout of static generation // We treat this function call as a bailout of static generation
throwToInterruptStaticGeneration('connection', staticGenerationStore) throwToInterruptStaticGeneration('connection', workStore)
} }
// We fall through to the dynamic context below but we still track dynamic access // We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context // because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(staticGenerationStore) trackDynamicDataInDynamicRender(workStore)
} }
return Promise.resolve(undefined) return Promise.resolve(undefined)
......
...@@ -4,7 +4,7 @@ import { ...@@ -4,7 +4,7 @@ import {
RequestCookiesAdapter, RequestCookiesAdapter,
} from '../../server/web/spec-extension/adapters/request-cookies' } from '../../server/web/spec-extension/adapters/request-cookies'
import { RequestCookies } from '../../server/web/spec-extension/cookies' import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, prerenderAsyncStorage,
...@@ -51,24 +51,24 @@ export type UnsafeUnwrappedCookies = ReadonlyRequestCookies ...@@ -51,24 +51,24 @@ export type UnsafeUnwrappedCookies = ReadonlyRequestCookies
export function cookies(): Promise<ReadonlyRequestCookies> { export function cookies(): Promise<ReadonlyRequestCookies> {
const callingExpression = 'cookies' const callingExpression = 'cookies'
const requestStore = getExpectedRequestStore(callingExpression) const requestStore = getExpectedRequestStore(callingExpression)
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
if (staticGenerationStore) { if (workStore) {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
// cookies object without tracking // cookies object without tracking
const underlyingCookies = createEmptyCookies() const underlyingCookies = createEmptyCookies()
return makeUntrackedExoticCookies(underlyingCookies) return makeUntrackedExoticCookies(underlyingCookies)
} }
if (staticGenerationStore.isUnstableCacheCallback) { if (workStore.isUnstableCacheCallback) {
throw new Error( throw new Error(
`Route ${staticGenerationStore.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` `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`
) )
} else if (staticGenerationStore.dynamicShouldError) { } else if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${staticGenerationStore.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` `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`
) )
} }
...@@ -83,7 +83,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -83,7 +83,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
// We don't track dynamic access here because access will be tracked when you access // We don't track dynamic access here because access will be tracked when you access
// one of the properties of the cookies object. // one of the properties of the cookies object.
return makeDynamicallyTrackedExoticCookies( return makeDynamicallyTrackedExoticCookies(
staticGenerationStore.route, workStore.route,
prerenderStore prerenderStore
) )
} else { } else {
...@@ -91,20 +91,20 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -91,20 +91,20 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
// to keep continuity with how cookies has worked in PPR without dynamicIO. // to keep continuity with how cookies has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access instead // TODO consider switching the semantic to throw on property access instead
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
callingExpression, callingExpression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} }
} else if (staticGenerationStore.isStaticGeneration) { } else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the cookies in // We track dynamic access here so we don't need to wrap the cookies in
// individual property access tracking. // individual property access tracking.
throwToInterruptStaticGeneration(callingExpression, staticGenerationStore) throwToInterruptStaticGeneration(callingExpression, workStore)
} }
// We fall through to the dynamic context below but we still track dynamic access // We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using cookies inside a cache context // because in dev we can still error for things like using cookies inside a cache context
trackDynamicDataInDynamicRender(staticGenerationStore) trackDynamicDataInDynamicRender(workStore)
} }
// cookies is being called in a dynamic context // cookies is being called in a dynamic context
...@@ -126,13 +126,10 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -126,13 +126,10 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
underlyingCookies = requestStore.cookies underlyingCookies = requestStore.cookies
} }
if ( if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
process.env.NODE_ENV === 'development' &&
!staticGenerationStore?.isPrefetchRequest
) {
return makeUntrackedExoticCookiesWithDevWarnings( return makeUntrackedExoticCookiesWithDevWarnings(
underlyingCookies, underlyingCookies,
staticGenerationStore?.route workStore?.route
) )
} else { } else {
return makeUntrackedExoticCookies(underlyingCookies) return makeUntrackedExoticCookies(underlyingCookies)
......
...@@ -2,7 +2,7 @@ import { getExpectedRequestStore } from '../../client/components/request-async-s ...@@ -2,7 +2,7 @@ import { getExpectedRequestStore } from '../../client/components/request-async-s
import type { DraftModeProvider } from '../../server/async-storage/draft-mode-provider' import type { DraftModeProvider } from '../../server/async-storage/draft-mode-provider'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering' import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering'
/** /**
...@@ -34,13 +34,10 @@ export type UnsafeUnwrappedDraftMode = DraftMode ...@@ -34,13 +34,10 @@ export type UnsafeUnwrappedDraftMode = DraftMode
export function draftMode(): Promise<DraftMode> { export function draftMode(): Promise<DraftMode> {
const callingExpression = 'draftMode' const callingExpression = 'draftMode'
const requestStore = getExpectedRequestStore(callingExpression) const requestStore = getExpectedRequestStore(callingExpression)
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if ( if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
process.env.NODE_ENV === 'development' && const route = workStore?.route
!staticGenerationStore?.isPrefetchRequest
) {
const route = staticGenerationStore?.route
return createExoticDraftModeWithDevWarnings(requestStore.draftMode, route) return createExoticDraftModeWithDevWarnings(requestStore.draftMode, route)
} else { } else {
return createExoticDraftMode(requestStore.draftMode) return createExoticDraftMode(requestStore.draftMode)
...@@ -144,7 +141,7 @@ class DraftMode { ...@@ -144,7 +141,7 @@ class DraftMode {
return this._provider.isEnabled return this._provider.isEnabled
} }
public enable() { public enable() {
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (store) { if (store) {
// We we have a store we want to track dynamic data access to ensure we // We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode. // don't statically generate routes that manipulate draft mode.
...@@ -153,7 +150,7 @@ class DraftMode { ...@@ -153,7 +150,7 @@ class DraftMode {
return this._provider.enable() return this._provider.enable()
} }
public disable() { public disable() {
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (store) { if (store) {
// We we have a store we want to track dynamic data access to ensure we // We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode. // don't statically generate routes that manipulate draft mode.
......
...@@ -2,7 +2,7 @@ import { ...@@ -2,7 +2,7 @@ import {
HeadersAdapter, HeadersAdapter,
type ReadonlyHeaders, type ReadonlyHeaders,
} from '../../server/web/spec-extension/adapters/headers' } from '../../server/web/spec-extension/adapters/headers'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external' import { getExpectedRequestStore } from '../../client/components/request-async-storage.external'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
...@@ -56,24 +56,24 @@ export type UnsafeUnwrappedHeaders = ReadonlyHeaders ...@@ -56,24 +56,24 @@ export type UnsafeUnwrappedHeaders = ReadonlyHeaders
*/ */
export function headers(): Promise<ReadonlyHeaders> { export function headers(): Promise<ReadonlyHeaders> {
const requestStore = getExpectedRequestStore('headers') const requestStore = getExpectedRequestStore('headers')
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
if (staticGenerationStore) { if (workStore) {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
// headers object without tracking // headers object without tracking
const underlyingHeaders = HeadersAdapter.seal(new Headers({})) const underlyingHeaders = HeadersAdapter.seal(new Headers({}))
return makeUntrackedExoticHeaders(underlyingHeaders) return makeUntrackedExoticHeaders(underlyingHeaders)
} }
if (staticGenerationStore.isUnstableCacheCallback) { if (workStore.isUnstableCacheCallback) {
throw new Error( throw new Error(
`Route ${staticGenerationStore.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` `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`
) )
} else if (staticGenerationStore.dynamicShouldError) { } else if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${staticGenerationStore.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` `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`
) )
} }
...@@ -88,7 +88,7 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -88,7 +88,7 @@ export function headers(): Promise<ReadonlyHeaders> {
// We don't track dynamic access here because access will be tracked when you access // We don't track dynamic access here because access will be tracked when you access
// one of the properties of the headers object. // one of the properties of the headers object.
return makeDynamicallyTrackedExoticHeaders( return makeDynamicallyTrackedExoticHeaders(
staticGenerationStore.route, workStore.route,
prerenderStore prerenderStore
) )
} else { } else {
...@@ -96,29 +96,26 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -96,29 +96,26 @@ export function headers(): Promise<ReadonlyHeaders> {
// to keep continuity with how headers has worked in PPR without dynamicIO. // to keep continuity with how headers has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access instead // TODO consider switching the semantic to throw on property access instead
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
'headers', 'headers',
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} }
} else if (staticGenerationStore.isStaticGeneration) { } else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the headers in // We track dynamic access here so we don't need to wrap the headers in
// individual property access tracking. // individual property access tracking.
throwToInterruptStaticGeneration('headers', staticGenerationStore) throwToInterruptStaticGeneration('headers', workStore)
} }
// We fall through to the dynamic context below but we still track dynamic access // We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context // because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(staticGenerationStore) trackDynamicDataInDynamicRender(workStore)
} }
if ( if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
process.env.NODE_ENV === 'development' &&
!staticGenerationStore?.isPrefetchRequest
) {
return makeUntrackedExoticHeadersWithDevWarnings( return makeUntrackedExoticHeadersWithDevWarnings(
requestStore.headers, requestStore.headers,
staticGenerationStore?.route workStore?.route
) )
} else { } else {
return makeUntrackedExoticHeaders(requestStore.headers) return makeUntrackedExoticHeaders(requestStore.headers)
......
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { FallbackRouteParams } from './fallback-params' import type { FallbackRouteParams } from './fallback-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
...@@ -49,16 +49,16 @@ export type UnsafeUnwrappedParams<P> = ...@@ -49,16 +49,16 @@ export type UnsafeUnwrappedParams<P> =
export function createPrerenderParamsFromClient( export function createPrerenderParamsFromClient(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
return createPrerenderParams(underlyingParams, staticGenerationStore) return createPrerenderParams(underlyingParams, workStore)
} }
export function createRenderParamsFromClient( export function createRenderParamsFromClient(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
return createRenderParams(underlyingParams, staticGenerationStore) return createRenderParams(underlyingParams, workStore)
} }
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component // generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
...@@ -68,34 +68,34 @@ export const createServerParamsForMetadata = createServerParamsForServerSegment ...@@ -68,34 +68,34 @@ export const createServerParamsForMetadata = createServerParamsForServerSegment
// routes always runs in RSC context so it is equivalent to a Server Page Component // routes always runs in RSC context so it is equivalent to a Server Page Component
export function createServerParamsForRoute( export function createServerParamsForRoute(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
if (staticGenerationStore.isStaticGeneration) { if (workStore.isStaticGeneration) {
return createPrerenderParams(underlyingParams, staticGenerationStore) return createPrerenderParams(underlyingParams, workStore)
} else { } else {
return createRenderParams(underlyingParams, staticGenerationStore) return createRenderParams(underlyingParams, workStore)
} }
} }
export function createServerParamsForServerSegment( export function createServerParamsForServerSegment(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
if (staticGenerationStore.isStaticGeneration) { if (workStore.isStaticGeneration) {
return createPrerenderParams(underlyingParams, staticGenerationStore) return createPrerenderParams(underlyingParams, workStore)
} else { } else {
return createRenderParams(underlyingParams, staticGenerationStore) return createRenderParams(underlyingParams, workStore)
} }
} }
export function createPrerenderParamsForClientSegment( export function createPrerenderParamsForClientSegment(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
if (prerenderStore) { if (prerenderStore) {
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
const fallbackParams = staticGenerationStore.fallbackRouteParams const fallbackParams = workStore.fallbackRouteParams
if (fallbackParams) { if (fallbackParams) {
for (let key in underlyingParams) { for (let key in underlyingParams) {
if (fallbackParams.has(key)) { if (fallbackParams.has(key)) {
...@@ -116,9 +116,9 @@ export function createPrerenderParamsForClientSegment( ...@@ -116,9 +116,9 @@ export function createPrerenderParamsForClientSegment(
function createPrerenderParams( function createPrerenderParams(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
const fallbackParams = staticGenerationStore.fallbackRouteParams const fallbackParams = workStore.fallbackRouteParams
if (fallbackParams) { if (fallbackParams) {
let hasSomeFallbackParams = false let hasSomeFallbackParams = false
for (const key in underlyingParams) { for (const key in underlyingParams) {
...@@ -136,7 +136,7 @@ function createPrerenderParams( ...@@ -136,7 +136,7 @@ function createPrerenderParams(
// We are in a dynamicIO (PPR or otherwise) prerender // We are in a dynamicIO (PPR or otherwise) prerender
return makeAbortingExoticParams( return makeAbortingExoticParams(
underlyingParams, underlyingParams,
staticGenerationStore.route, workStore.route,
prerenderStore prerenderStore
) )
} }
...@@ -147,7 +147,7 @@ function createPrerenderParams( ...@@ -147,7 +147,7 @@ function createPrerenderParams(
return makeErroringExoticParams( return makeErroringExoticParams(
underlyingParams, underlyingParams,
fallbackParams, fallbackParams,
staticGenerationStore, workStore,
prerenderStore prerenderStore
) )
} }
...@@ -159,15 +159,12 @@ function createPrerenderParams( ...@@ -159,15 +159,12 @@ function createPrerenderParams(
function createRenderParams( function createRenderParams(
underlyingParams: Params, underlyingParams: Params,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
if ( if (process.env.NODE_ENV === 'development' && !workStore.isPrefetchRequest) {
process.env.NODE_ENV === 'development' &&
!staticGenerationStore.isPrefetchRequest
) {
return makeDynamicallyTrackedExoticParamsWithDevWarnings( return makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams, underlyingParams,
staticGenerationStore workStore
) )
} else { } else {
return makeUntrackedExoticParams(underlyingParams) return makeUntrackedExoticParams(underlyingParams)
...@@ -249,7 +246,7 @@ function makeAbortingExoticParams( ...@@ -249,7 +246,7 @@ function makeAbortingExoticParams(
function makeErroringExoticParams( function makeErroringExoticParams(
underlyingParams: Params, underlyingParams: Params,
fallbackParams: FallbackRouteParams, fallbackParams: FallbackRouteParams,
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
prerenderStore: undefined | PrerenderStore prerenderStore: undefined | PrerenderStore
): Promise<Params> { ): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams) const cachedParams = CachedParams.get(underlyingParams)
...@@ -307,15 +304,12 @@ function makeErroringExoticParams( ...@@ -307,15 +304,12 @@ function makeErroringExoticParams(
// will be no `dynamic = "error"` // will be no `dynamic = "error"`
if (prerenderStore) { if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration( throwToInterruptStaticGeneration(expression, workStore)
expression,
staticGenerationStore
)
} }
}, },
enumerable: true, enumerable: true,
...@@ -331,15 +325,12 @@ function makeErroringExoticParams( ...@@ -331,15 +325,12 @@ function makeErroringExoticParams(
// will be no `dynamic = "error"` // will be no `dynamic = "error"`
if (prerenderStore) { if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration( throwToInterruptStaticGeneration(expression, workStore)
expression,
staticGenerationStore
)
} }
}, },
set(newValue) { set(newValue) {
...@@ -414,7 +405,7 @@ function makeUntrackedExoticParams(underlyingParams: Params): Promise<Params> { ...@@ -414,7 +405,7 @@ function makeUntrackedExoticParams(underlyingParams: Params): Promise<Params> {
function makeDynamicallyTrackedExoticParamsWithDevWarnings( function makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams: Params, underlyingParams: Params,
store: StaticGenerationStore store: WorkStore
): Promise<Params> { ): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams) const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) { if (cachedParams) {
......
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
...@@ -52,17 +52,15 @@ export type SearchParams = { [key: string]: string | string[] | undefined } ...@@ -52,17 +52,15 @@ export type SearchParams = { [key: string]: string | string[] | undefined }
export type UnsafeUnwrappedSearchParams<P> = export type UnsafeUnwrappedSearchParams<P> =
P extends Promise<infer U> ? Omit<U, 'then' | 'status' | 'value'> : never P extends Promise<infer U> ? Omit<U, 'then' | 'status' | 'value'> : never
export function createPrerenderSearchParamsFromClient( export function createPrerenderSearchParamsFromClient(workStore: WorkStore) {
staticGenerationStore: StaticGenerationStore return createPrerenderSearchParams(workStore)
) {
return createPrerenderSearchParams(staticGenerationStore)
} }
export function createRenderSearchParamsFromClient( export function createRenderSearchParamsFromClient(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
) { ) {
return createRenderSearchParams(underlyingSearchParams, staticGenerationStore) return createRenderSearchParams(underlyingSearchParams, workStore)
} }
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component // generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
...@@ -71,22 +69,19 @@ export const createServerSearchParamsForMetadata = ...@@ -71,22 +69,19 @@ export const createServerSearchParamsForMetadata =
export function createServerSearchParamsForServerPage( export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
if (staticGenerationStore.isStaticGeneration) { if (workStore.isStaticGeneration) {
return createPrerenderSearchParams(staticGenerationStore) return createPrerenderSearchParams(workStore)
} else { } else {
return createRenderSearchParams( return createRenderSearchParams(underlyingSearchParams, workStore)
underlyingSearchParams,
staticGenerationStore
)
} }
} }
export function createPrerenderSearchParamsForClientPage( export function createPrerenderSearchParamsForClientPage(
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
// dictionary object. // dictionary object.
return Promise.resolve({}) return Promise.resolve({})
...@@ -107,9 +102,9 @@ export function createPrerenderSearchParamsForClientPage( ...@@ -107,9 +102,9 @@ export function createPrerenderSearchParamsForClientPage(
} }
function createPrerenderSearchParams( function createPrerenderSearchParams(
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
// dictionary object. // dictionary object.
return Promise.resolve({}) return Promise.resolve({})
...@@ -119,40 +114,34 @@ function createPrerenderSearchParams( ...@@ -119,40 +114,34 @@ function createPrerenderSearchParams(
if (prerenderStore) { if (prerenderStore) {
if (prerenderStore.controller || prerenderStore.cacheSignal) { if (prerenderStore.controller || prerenderStore.cacheSignal) {
// We are in a dynamicIO (PPR or otherwise) prerender // We are in a dynamicIO (PPR or otherwise) prerender
return makeAbortingExoticSearchParams( return makeAbortingExoticSearchParams(workStore.route, prerenderStore)
staticGenerationStore.route,
prerenderStore
)
} }
} }
// We are in a legacy static generation and need to interrupt the prerender // We are in a legacy static generation and need to interrupt the prerender
// when search params are accessed. // when search params are accessed.
return makeErroringExoticSearchParams(staticGenerationStore, prerenderStore) return makeErroringExoticSearchParams(workStore, prerenderStore)
} }
function createRenderSearchParams( function createRenderSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
staticGenerationStore: StaticGenerationStore workStore: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
if (staticGenerationStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
// dictionary object. // dictionary object.
return Promise.resolve({}) return Promise.resolve({})
} else { } else {
if ( if (
process.env.NODE_ENV === 'development' && process.env.NODE_ENV === 'development' &&
!staticGenerationStore.isPrefetchRequest !workStore.isPrefetchRequest
) { ) {
return makeDynamicallyTrackedExoticSearchParamsWithDevWarnings( return makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams, underlyingSearchParams,
staticGenerationStore workStore
) )
} else { } else {
return makeUntrackedExoticSearchParams( return makeUntrackedExoticSearchParams(underlyingSearchParams, workStore)
underlyingSearchParams,
staticGenerationStore
)
} }
} }
} }
...@@ -266,10 +255,10 @@ function makeAbortingExoticSearchParams( ...@@ -266,10 +255,10 @@ function makeAbortingExoticSearchParams(
} }
function makeErroringExoticSearchParams( function makeErroringExoticSearchParams(
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
prerenderStore: undefined | PrerenderStore prerenderStore: undefined | PrerenderStore
): Promise<SearchParams> { ): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(staticGenerationStore) const cachedSearchParams = CachedSearchParams.get(workStore)
if (cachedSearchParams) { if (cachedSearchParams) {
return cachedSearchParams return cachedSearchParams
} }
...@@ -315,38 +304,38 @@ function makeErroringExoticSearchParams( ...@@ -315,38 +304,38 @@ function makeErroringExoticSearchParams(
case 'then': { case 'then': {
const expression = const expression =
'`await searchParams`, `searchParams.then`, or similar' '`await searchParams`, `searchParams.then`, or similar'
if (staticGenerationStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError( throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route, workStore.route,
expression expression
) )
} else if (prerenderStore) { } else if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration(expression, staticGenerationStore) throwToInterruptStaticGeneration(expression, workStore)
} }
return return
} }
case 'status': { case 'status': {
const expression = const expression =
'`use(searchParams)`, `searchParams.status`, or similar' '`use(searchParams)`, `searchParams.status`, or similar'
if (staticGenerationStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError( throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route, workStore.route,
expression expression
) )
} else if (prerenderStore) { } else if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration(expression, staticGenerationStore) throwToInterruptStaticGeneration(expression, workStore)
} }
return return
} }
...@@ -356,22 +345,19 @@ function makeErroringExoticSearchParams( ...@@ -356,22 +345,19 @@ function makeErroringExoticSearchParams(
'searchParams', 'searchParams',
prop prop
) )
if (staticGenerationStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError( throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route, workStore.route,
expression expression
) )
} else if (prerenderStore) { } else if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration( throwToInterruptStaticGeneration(expression, workStore)
expression,
staticGenerationStore
)
} }
} }
return ReflectAdapter.get(target, prop, receiver) return ReflectAdapter.get(target, prop, receiver)
...@@ -388,19 +374,19 @@ function makeErroringExoticSearchParams( ...@@ -388,19 +374,19 @@ function makeErroringExoticSearchParams(
'searchParams', 'searchParams',
prop prop
) )
if (staticGenerationStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError( throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route, workStore.route,
expression expression
) )
} else if (prerenderStore) { } else if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration(expression, staticGenerationStore) throwToInterruptStaticGeneration(expression, workStore)
} }
return false return false
} }
...@@ -409,30 +395,30 @@ function makeErroringExoticSearchParams( ...@@ -409,30 +395,30 @@ function makeErroringExoticSearchParams(
ownKeys() { ownKeys() {
const expression = const expression =
'`{...searchParams}`, `Object.keys(searchParams)`, or similar' '`{...searchParams}`, `Object.keys(searchParams)`, or similar'
if (staticGenerationStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError( throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route, workStore.route,
expression expression
) )
} else if (prerenderStore) { } else if (prerenderStore) {
postponeWithTracking( postponeWithTracking(
staticGenerationStore.route, workStore.route,
expression, expression,
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration(expression, staticGenerationStore) throwToInterruptStaticGeneration(expression, workStore)
} }
}, },
}) })
CachedSearchParams.set(staticGenerationStore, proxiedPromise) CachedSearchParams.set(workStore, proxiedPromise)
return proxiedPromise return proxiedPromise
} }
function makeUntrackedExoticSearchParams( function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
store: StaticGenerationStore store: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams) const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) { if (cachedSearchParams) {
...@@ -499,7 +485,7 @@ function makeUntrackedExoticSearchParams( ...@@ -499,7 +485,7 @@ function makeUntrackedExoticSearchParams(
function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings( function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
store: StaticGenerationStore store: WorkStore
): Promise<SearchParams> { ): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams) const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) { if (cachedSearchParams) {
......
...@@ -12,8 +12,8 @@ import { ...@@ -12,8 +12,8 @@ import {
createTemporaryReferenceSet as createClientTemporaryReferenceSet, createTemporaryReferenceSet as createClientTemporaryReferenceSet,
} from 'react-server-dom-webpack/client.edge' } from 'react-server-dom-webpack/client.edge'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import type { CacheStore } from '../app-render/cache-async-storage.external' import type { CacheStore } from '../app-render/cache-async-storage.external'
import { cacheAsyncStorage } from '../app-render/cache-async-storage.external' import { cacheAsyncStorage } from '../app-render/cache-async-storage.external'
import { runInCleanSnapshot } from '../app-render/clean-async-snapshot.external' import { runInCleanSnapshot } from '../app-render/clean-async-snapshot.external'
...@@ -76,7 +76,7 @@ cacheHandlerMap.set('default', { ...@@ -76,7 +76,7 @@ cacheHandlerMap.set('default', {
}) })
function generateCacheEntry( function generateCacheEntry(
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler, cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer, serializedCacheKey: string | ArrayBuffer,
...@@ -89,8 +89,8 @@ function generateCacheEntry( ...@@ -89,8 +89,8 @@ function generateCacheEntry(
// Note: It is important that we await at least once before this because it lets us // Note: It is important that we await at least once before this because it lets us
// pop out of any stack specific contexts as well - aka "Sync" Local Storage. // pop out of any stack specific contexts as well - aka "Sync" Local Storage.
return runInCleanSnapshot( return runInCleanSnapshot(
generateCacheEntryWithRestoredStaticGenerationStore, generateCacheEntryWithRestoredWorkStore,
staticGenerationStore, workStore,
clientReferenceManifest, clientReferenceManifest,
cacheHandler, cacheHandler,
serializedCacheKey, serializedCacheKey,
...@@ -99,25 +99,25 @@ function generateCacheEntry( ...@@ -99,25 +99,25 @@ function generateCacheEntry(
) )
} }
function generateCacheEntryWithRestoredStaticGenerationStore( function generateCacheEntryWithRestoredWorkStore(
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler, cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer, serializedCacheKey: string | ArrayBuffer,
encodedArguments: FormData | string, encodedArguments: FormData | string,
fn: any fn: any
) { ) {
// Since we cleared the AsyncLocalStorage we need to restore the staticGenerationStore. // Since we cleared the AsyncLocalStorage we need to restore the workStore.
// Note: We explicitly don't restore the RequestStore nor the PrerenderStore. // Note: We explicitly don't restore the RequestStore nor the PrerenderStore.
// We don't want any request specific information leaking an we don't want to create a // We don't want any request specific information leaking an we don't want to create a
// bloated fake request mock for every cache call. So any feature that currently lives // bloated fake request mock for every cache call. So any feature that currently lives
// in RequestStore but should be available to Caches need to move to StaticGenerationStore. // in RequestStore but should be available to Caches need to move to WorkStore.
// PrerenderStore is not needed inside the cache scope because the outer most one will // PrerenderStore is not needed inside the cache scope because the outer most one will
// be the one to report its result to the outer Prerender. // be the one to report its result to the outer Prerender.
return staticGenerationAsyncStorage.run( return workAsyncStorage.run(
staticGenerationStore, workStore,
generateCacheEntryWithCacheContext, generateCacheEntryWithCacheContext,
staticGenerationStore, workStore,
clientReferenceManifest, clientReferenceManifest,
cacheHandler, cacheHandler,
serializedCacheKey, serializedCacheKey,
...@@ -127,7 +127,7 @@ function generateCacheEntryWithRestoredStaticGenerationStore( ...@@ -127,7 +127,7 @@ function generateCacheEntryWithRestoredStaticGenerationStore(
} }
function generateCacheEntryWithCacheContext( function generateCacheEntryWithCacheContext(
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler, cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer, serializedCacheKey: string | ArrayBuffer,
...@@ -139,7 +139,7 @@ function generateCacheEntryWithCacheContext( ...@@ -139,7 +139,7 @@ function generateCacheEntryWithCacheContext(
return cacheAsyncStorage.run( return cacheAsyncStorage.run(
cacheStore, cacheStore,
generateCacheEntryImpl, generateCacheEntryImpl,
staticGenerationStore, workStore,
clientReferenceManifest, clientReferenceManifest,
cacheHandler, cacheHandler,
serializedCacheKey, serializedCacheKey,
...@@ -149,7 +149,7 @@ function generateCacheEntryWithCacheContext( ...@@ -149,7 +149,7 @@ function generateCacheEntryWithCacheContext(
} }
async function generateCacheEntryImpl( async function generateCacheEntryImpl(
staticGenerationStore: StaticGenerationStore, workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler, cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer, serializedCacheKey: string | ArrayBuffer,
...@@ -219,13 +219,13 @@ async function generateCacheEntryImpl( ...@@ -219,13 +219,13 @@ async function generateCacheEntryImpl(
}, },
}) })
if (!staticGenerationStore.pendingRevalidateWrites) { if (!workStore.pendingRevalidateWrites) {
staticGenerationStore.pendingRevalidateWrites = [] workStore.pendingRevalidateWrites = []
} }
const promise = cacheHandler.set(serializedCacheKey, erroringSavedStream) const promise = cacheHandler.set(serializedCacheKey, erroringSavedStream)
staticGenerationStore.pendingRevalidateWrites.push(promise) workStore.pendingRevalidateWrites.push(promise)
// Return the stream as we're creating it. This means that if it ends up // Return the stream as we're creating it. This means that if it ends up
// erroring we cannot return a stale-while-error version but it allows // erroring we cannot return a stale-while-error version but it allows
...@@ -246,10 +246,10 @@ export function cache(kind: string, id: string, fn: any) { ...@@ -246,10 +246,10 @@ export function cache(kind: string, id: string, fn: any) {
const name = fn.name const name = fn.name
const cachedFn = { const cachedFn = {
[name]: async function (...args: any[]) { [name]: async function (...args: any[]) {
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if (staticGenerationStore === undefined) { if (workStore === undefined) {
throw new Error( throw new Error(
'"use cache" cannot be used outside of App Router. Expected a StaticGenerationStore.' '"use cache" cannot be used outside of App Router. Expected a WorkStore.'
) )
} }
...@@ -257,7 +257,7 @@ export function cache(kind: string, id: string, fn: any) { ...@@ -257,7 +257,7 @@ export function cache(kind: string, id: string, fn: any) {
// safely reuse the results across builds yet. In the meantime we add the buildId to the // safely reuse the results across builds yet. In the meantime we add the buildId to the
// arguments as a seed to ensure they're not reused. Remove this once Action IDs hash // arguments as a seed to ensure they're not reused. Remove this once Action IDs hash
// the implementation. // the implementation.
const buildId = staticGenerationStore.buildId const buildId = workStore.buildId
const temporaryReferences = createClientTemporaryReferenceSet() const temporaryReferences = createClientTemporaryReferenceSet()
const encodedArguments: FormData | string = await encodeReply( const encodedArguments: FormData | string = await encodeReply(
...@@ -283,7 +283,7 @@ export function cache(kind: string, id: string, fn: any) { ...@@ -283,7 +283,7 @@ export function cache(kind: string, id: string, fn: any) {
let stream let stream
if ( if (
entry === undefined || entry === undefined ||
(entry.stale && staticGenerationStore.isStaticGeneration) (entry.stale && workStore.isStaticGeneration)
) { ) {
// Miss. Generate a new result. // Miss. Generate a new result.
...@@ -303,7 +303,7 @@ export function cache(kind: string, id: string, fn: any) { ...@@ -303,7 +303,7 @@ export function cache(kind: string, id: string, fn: any) {
getClientReferenceManifestSingleton() getClientReferenceManifestSingleton()
stream = await generateCacheEntry( stream = await generateCacheEntry(
staticGenerationStore, workStore,
clientReferenceManifestSingleton, clientReferenceManifestSingleton,
cacheHandler, cacheHandler,
serializedCacheKey, serializedCacheKey,
...@@ -318,7 +318,7 @@ export function cache(kind: string, id: string, fn: any) { ...@@ -318,7 +318,7 @@ export function cache(kind: string, id: string, fn: any) {
const clientReferenceManifestSingleton = const clientReferenceManifestSingleton =
getClientReferenceManifestSingleton() getClientReferenceManifestSingleton()
const ignoredStream = await generateCacheEntry( const ignoredStream = await generateCacheEntry(
staticGenerationStore, workStore,
clientReferenceManifestSingleton, clientReferenceManifestSingleton,
cacheHandler, cacheHandler,
serializedCacheKey, serializedCacheKey,
......
...@@ -2,7 +2,7 @@ import type { RequestCookies } from '../cookies' ...@@ -2,7 +2,7 @@ import type { RequestCookies } from '../cookies'
import { ResponseCookies } from '../cookies' import { ResponseCookies } from '../cookies'
import { ReflectAdapter } from './reflect' import { ReflectAdapter } from './reflect'
import { staticGenerationAsyncStorage } from '../../../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../../../client/components/work-async-storage.external'
/** /**
* @internal * @internal
...@@ -108,10 +108,10 @@ export class MutableRequestCookiesAdapter { ...@@ -108,10 +108,10 @@ export class MutableRequestCookiesAdapter {
let modifiedValues: ResponseCookie[] = [] let modifiedValues: ResponseCookie[] = []
const modifiedCookies = new Set<string>() const modifiedCookies = new Set<string>()
const updateResponseCookies = () => { const updateResponseCookies = () => {
// TODO-APP: change method of getting staticGenerationAsyncStore // TODO-APP: change method of getting workStore
const staticGenerationAsyncStore = staticGenerationAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if (staticGenerationAsyncStore) { if (workStore) {
staticGenerationAsyncStore.pathWasRevalidated = true workStore.pathWasRevalidated = true
} }
const allCookies = responseCookies.getAll() const allCookies = responseCookies.getAll()
......
...@@ -4,7 +4,7 @@ import { ...@@ -4,7 +4,7 @@ import {
NEXT_CACHE_IMPLICIT_TAG_ID, NEXT_CACHE_IMPLICIT_TAG_ID,
NEXT_CACHE_SOFT_TAG_MAX_LENGTH, NEXT_CACHE_SOFT_TAG_MAX_LENGTH,
} from '../../../lib/constants' } from '../../../lib/constants'
import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
/** /**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag. * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
...@@ -41,7 +41,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') { ...@@ -41,7 +41,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
} }
function revalidate(tag: string, expression: string) { function revalidate(tag: string, expression: string) {
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (!store || !store.incrementalCache) { if (!store || !store.incrementalCache) {
throw new Error( throw new Error(
`Invariant: static generation store missing in ${expression}` `Invariant: static generation store missing in ${expression}`
......
import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external' import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering' import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
/** /**
...@@ -18,7 +18,7 @@ import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering' ...@@ -18,7 +18,7 @@ import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
*/ */
export function unstable_noStore() { export function unstable_noStore() {
const callingExpression = 'unstable_noStore()' const callingExpression = 'unstable_noStore()'
const store = staticGenerationAsyncStorage.getStore() const store = workAsyncStorage.getStore()
if (!store) { if (!store) {
// This generally implies we are being called in Pages router. We should probably not support // This generally implies we are being called in Pages router. We should probably not support
// unstable_noStore in contexts outside of `react-server` condition but since we historically // unstable_noStore in contexts outside of `react-server` condition but since we historically
......
...@@ -20,12 +20,12 @@ const routeModule = new AppRouteRouteModule({ ...@@ -20,12 +20,12 @@ const routeModule = new AppRouteRouteModule({
// Pull out the exports that we need to expose from the module. This should // Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These // be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route. // are used to hook into the route.
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule; const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
const originalPathname = 'VAR_ORIGINAL_PATHNAME'; const originalPathname = 'VAR_ORIGINAL_PATHNAME';
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
serverHooks, serverHooks,
staticGenerationAsyncStorage workAsyncStorage
}); });
} }
export { routeModule, requestAsyncStorage, staticGenerationAsyncStorage, serverHooks, originalPathname, patchFetch, }; export { routeModule, requestAsyncStorage, workAsyncStorage, serverHooks, originalPathname, patchFetch, };
...@@ -108,13 +108,13 @@ const routeModule = new AppRouteRouteModule({ ...@@ -108,13 +108,13 @@ const routeModule = new AppRouteRouteModule({
## Item 10: Stmt 5, `VarDeclarator(0)` ## Item 10: Stmt 5, `VarDeclarator(0)`
```js ```js
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule; const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
``` ```
- Declares: `requestAsyncStorage`, `staticGenerationAsyncStorage`, `serverHooks` - Declares: `requestAsyncStorage`, `workAsyncStorage`, `serverHooks`
- Reads: `routeModule` - Reads: `routeModule`
- Write: `requestAsyncStorage`, `staticGenerationAsyncStorage`, `serverHooks` - Write: `requestAsyncStorage`, `workAsyncStorage`, `serverHooks`
## Item 11: Stmt 6, `VarDeclarator(0)` ## Item 11: Stmt 6, `VarDeclarator(0)`
...@@ -132,7 +132,7 @@ const originalPathname = 'VAR_ORIGINAL_PATHNAME'; ...@@ -132,7 +132,7 @@ const originalPathname = 'VAR_ORIGINAL_PATHNAME';
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
serverHooks, serverHooks,
staticGenerationAsyncStorage workAsyncStorage
}); });
} }
...@@ -140,9 +140,9 @@ function patchFetch() { ...@@ -140,9 +140,9 @@ function patchFetch() {
- Hoisted - Hoisted
- Declares: `patchFetch` - Declares: `patchFetch`
- Reads (eventual): `_patchFetch`, `serverHooks`, `staticGenerationAsyncStorage` - Reads (eventual): `_patchFetch`, `serverHooks`, `workAsyncStorage`
- Write: `patchFetch` - Write: `patchFetch`
- Write (eventual): `serverHooks`, `staticGenerationAsyncStorage` - Write (eventual): `serverHooks`, `workAsyncStorage`
# Phase 1 # Phase 1
```mermaid ```mermaid
...@@ -166,7 +166,7 @@ graph TD ...@@ -166,7 +166,7 @@ graph TD
Item15; Item15;
Item15["export requestAsyncStorage"]; Item15["export requestAsyncStorage"];
Item16; Item16;
Item16["export staticGenerationAsyncStorage"]; Item16["export workAsyncStorage"];
Item17; Item17;
Item17["export serverHooks"]; Item17["export serverHooks"];
Item18; Item18;
...@@ -202,7 +202,7 @@ graph TD ...@@ -202,7 +202,7 @@ graph TD
Item15; Item15;
Item15["export requestAsyncStorage"]; Item15["export requestAsyncStorage"];
Item16; Item16;
Item16["export staticGenerationAsyncStorage"]; Item16["export workAsyncStorage"];
Item17; Item17;
Item17["export serverHooks"]; Item17["export serverHooks"];
Item18; Item18;
...@@ -253,7 +253,7 @@ graph TD ...@@ -253,7 +253,7 @@ graph TD
Item15; Item15;
Item15["export requestAsyncStorage"]; Item15["export requestAsyncStorage"];
Item16; Item16;
Item16["export staticGenerationAsyncStorage"]; Item16["export workAsyncStorage"];
Item17; Item17;
Item17["export serverHooks"]; Item17["export serverHooks"];
Item18; Item18;
...@@ -308,7 +308,7 @@ graph TD ...@@ -308,7 +308,7 @@ graph TD
Item15; Item15;
Item15["export requestAsyncStorage"]; Item15["export requestAsyncStorage"];
Item16; Item16;
Item16["export staticGenerationAsyncStorage"]; Item16["export workAsyncStorage"];
Item17; Item17;
Item17["export serverHooks"]; Item17["export serverHooks"];
Item18; Item18;
...@@ -364,7 +364,7 @@ graph TD ...@@ -364,7 +364,7 @@ graph TD
N12["Items: [ItemId(Export((&quot;routeModule&quot;, #2), &quot;routeModule&quot;))]"]; N12["Items: [ItemId(Export((&quot;routeModule&quot;, #2), &quot;routeModule&quot;))]"];
N13["Items: [ItemId(5, VarDeclarator(0))]"]; N13["Items: [ItemId(5, VarDeclarator(0))]"];
N14["Items: [ItemId(Export((&quot;serverHooks&quot;, #2), &quot;serverHooks&quot;))]"]; N14["Items: [ItemId(Export((&quot;serverHooks&quot;, #2), &quot;serverHooks&quot;))]"];
N15["Items: [ItemId(Export((&quot;staticGenerationAsyncStorage&quot;, #2), &quot;staticGenerationAsyncStorage&quot;))]"]; N15["Items: [ItemId(Export((&quot;workAsyncStorage&quot;, #2), &quot;workAsyncStorage&quot;))]"];
N16["Items: [ItemId(7, Normal)]"]; N16["Items: [ItemId(7, Normal)]"];
N17["Items: [ItemId(Export((&quot;patchFetch&quot;, #2), &quot;patchFetch&quot;))]"]; N17["Items: [ItemId(Export((&quot;patchFetch&quot;, #2), &quot;patchFetch&quot;))]"];
N18["Items: [ItemId(Export((&quot;requestAsyncStorage&quot;, #2), &quot;requestAsyncStorage&quot;))]"]; N18["Items: [ItemId(Export((&quot;requestAsyncStorage&quot;, #2), &quot;requestAsyncStorage&quot;))]"];
...@@ -410,9 +410,6 @@ graph TD ...@@ -410,9 +410,6 @@ graph TD
Export( Export(
"patchFetch", "patchFetch",
): 17, ): 17,
Export(
"staticGenerationAsyncStorage",
): 15,
Export( Export(
"requestAsyncStorage", "requestAsyncStorage",
): 18, ): 18,
...@@ -420,6 +417,9 @@ graph TD ...@@ -420,6 +417,9 @@ graph TD
"routeModule", "routeModule",
): 12, ): 12,
Exports: 19, Exports: 19,
Export(
"workAsyncStorage",
): 15,
Export( Export(
"originalPathname", "originalPathname",
): 1, ): 1,
...@@ -608,11 +608,11 @@ import "__TURBOPACK_PART__" assert { ...@@ -608,11 +608,11 @@ import "__TURBOPACK_PART__" assert {
import { f as routeModule } from "__TURBOPACK_PART__" assert { import { f as routeModule } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 10 __turbopack_part__: 10
}; };
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule; const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
export { requestAsyncStorage as g } from "__TURBOPACK_VAR__" assert { export { requestAsyncStorage as g } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true __turbopack_var__: true
}; };
export { staticGenerationAsyncStorage as h } from "__TURBOPACK_VAR__" assert { export { workAsyncStorage as h } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true __turbopack_var__: true
}; };
export { serverHooks as i } from "__TURBOPACK_VAR__" assert { export { serverHooks as i } from "__TURBOPACK_VAR__" assert {
...@@ -636,10 +636,10 @@ export { serverHooks }; ...@@ -636,10 +636,10 @@ export { serverHooks };
import "__TURBOPACK_PART__" assert { import "__TURBOPACK_PART__" assert {
__turbopack_part__: 13 __turbopack_part__: 13
}; };
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert { import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 13 __turbopack_part__: 13
}; };
export { staticGenerationAsyncStorage }; export { workAsyncStorage };
``` ```
## Part 16 ## Part 16
...@@ -656,7 +656,7 @@ import "__TURBOPACK_PART__" assert { ...@@ -656,7 +656,7 @@ import "__TURBOPACK_PART__" assert {
import "__TURBOPACK_PART__" assert { import "__TURBOPACK_PART__" assert {
__turbopack_part__: 15 __turbopack_part__: 15
}; };
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert { import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 13 __turbopack_part__: 13
}; };
import { b as _patchFetch } from "__TURBOPACK_PART__" assert { import { b as _patchFetch } from "__TURBOPACK_PART__" assert {
...@@ -668,7 +668,7 @@ import { i as serverHooks } from "__TURBOPACK_PART__" assert { ...@@ -668,7 +668,7 @@ import { i as serverHooks } from "__TURBOPACK_PART__" assert {
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
serverHooks, serverHooks,
staticGenerationAsyncStorage workAsyncStorage
}); });
} }
export { patchFetch as j } from "__TURBOPACK_VAR__" assert { export { patchFetch as j } from "__TURBOPACK_VAR__" assert {
...@@ -709,8 +709,8 @@ export { routeModule } from "__TURBOPACK_PART__" assert { ...@@ -709,8 +709,8 @@ export { routeModule } from "__TURBOPACK_PART__" assert {
export { serverHooks } from "__TURBOPACK_PART__" assert { export { serverHooks } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export serverHooks" __turbopack_part__: "export serverHooks"
}; };
export { staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert { export { workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export staticGenerationAsyncStorage" __turbopack_part__: "export workAsyncStorage"
}; };
export { patchFetch } from "__TURBOPACK_PART__" assert { export { patchFetch } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export patchFetch" __turbopack_part__: "export patchFetch"
...@@ -751,9 +751,6 @@ import "__TURBOPACK_PART__" assert { ...@@ -751,9 +751,6 @@ import "__TURBOPACK_PART__" assert {
Export( Export(
"serverHooks", "serverHooks",
): 15, ): 15,
Export(
"staticGenerationAsyncStorage",
): 16,
Export( Export(
"requestAsyncStorage", "requestAsyncStorage",
): 17, ): 17,
...@@ -761,6 +758,9 @@ import "__TURBOPACK_PART__" assert { ...@@ -761,6 +758,9 @@ import "__TURBOPACK_PART__" assert {
"routeModule", "routeModule",
): 11, ): 11,
Exports: 19, Exports: 19,
Export(
"workAsyncStorage",
): 16,
Export( Export(
"originalPathname", "originalPathname",
): 1, ): 1,
...@@ -926,11 +926,11 @@ import "__TURBOPACK_PART__" assert { ...@@ -926,11 +926,11 @@ import "__TURBOPACK_PART__" assert {
import { f as routeModule } from "__TURBOPACK_PART__" assert { import { f as routeModule } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 10 __turbopack_part__: 10
}; };
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule; const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
export { requestAsyncStorage as g } from "__TURBOPACK_VAR__" assert { export { requestAsyncStorage as g } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true __turbopack_var__: true
}; };
export { staticGenerationAsyncStorage as h } from "__TURBOPACK_VAR__" assert { export { workAsyncStorage as h } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true __turbopack_var__: true
}; };
export { serverHooks as i } from "__TURBOPACK_VAR__" assert { export { serverHooks as i } from "__TURBOPACK_VAR__" assert {
...@@ -946,7 +946,7 @@ import "__TURBOPACK_PART__" assert { ...@@ -946,7 +946,7 @@ import "__TURBOPACK_PART__" assert {
import "__TURBOPACK_PART__" assert { import "__TURBOPACK_PART__" assert {
__turbopack_part__: 12 __turbopack_part__: 12
}; };
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert { import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 12 __turbopack_part__: 12
}; };
import { b as _patchFetch } from "__TURBOPACK_PART__" assert { import { b as _patchFetch } from "__TURBOPACK_PART__" assert {
...@@ -958,7 +958,7 @@ import { i as serverHooks } from "__TURBOPACK_PART__" assert { ...@@ -958,7 +958,7 @@ import { i as serverHooks } from "__TURBOPACK_PART__" assert {
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
serverHooks, serverHooks,
staticGenerationAsyncStorage workAsyncStorage
}); });
} }
export { patchFetch as j } from "__TURBOPACK_VAR__" assert { export { patchFetch as j } from "__TURBOPACK_VAR__" assert {
...@@ -993,10 +993,10 @@ export { serverHooks }; ...@@ -993,10 +993,10 @@ export { serverHooks };
import "__TURBOPACK_PART__" assert { import "__TURBOPACK_PART__" assert {
__turbopack_part__: 12 __turbopack_part__: 12
}; };
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert { import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 12 __turbopack_part__: 12
}; };
export { staticGenerationAsyncStorage }; export { workAsyncStorage };
``` ```
## Part 17 ## Part 17
...@@ -1044,8 +1044,8 @@ export { patchFetch } from "__TURBOPACK_PART__" assert { ...@@ -1044,8 +1044,8 @@ export { patchFetch } from "__TURBOPACK_PART__" assert {
export { serverHooks } from "__TURBOPACK_PART__" assert { export { serverHooks } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export serverHooks" __turbopack_part__: "export serverHooks"
}; };
export { staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert { export { workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export staticGenerationAsyncStorage" __turbopack_part__: "export workAsyncStorage"
}; };
export { requestAsyncStorage } from "__TURBOPACK_PART__" assert { export { requestAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export requestAsyncStorage" __turbopack_part__: "export requestAsyncStorage"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment