{"version":3,"sources":["../../../src/server/async-storage/work-store.ts"],"sourcesContent":["import type { WorkStore } from '../app-render/work-async-storage.external'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { RenderOpts } from '../app-render/types'\nimport type { FetchMetric } from '../base-http'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'\nimport type {\n  ValidationLevel,\n  ResolvedCacheLifeProfiles,\n} from '../config-shared'\n\nimport { AfterContext } from '../after/after-context'\n\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { createLazyResult, type LazyResult } from '../lib/lazy-result'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { createSnapshot } from '../app-render/async-local-storage'\n\nexport type WorkStoreContext = {\n  /**\n   * The page that is being rendered. This relates to the path to the page file.\n   */\n  page: string\n\n  isPrefetchRequest?: boolean\n  nonce?: string\n  renderOpts: {\n    cacheLifeProfiles: ResolvedCacheLifeProfiles\n    staticPageGenerationTimeout: number\n    incrementalCache?: IncrementalCache\n    /**\n     * The hash of the most recent server component change (dev only). Included\n     * in `\"use cache\"` cache keys so that cached entries are revalidated after\n     * an edit, for every client, regardless of whether it runs the HMR client.\n     */\n    hmrRefreshHash?: string\n    isOnDemandRevalidate?: boolean\n    cacheComponents: boolean\n    validationLevel: ValidationLevel\n    fetchCache?: AppSegmentConfig['fetchCache']\n    isPossibleServerAction?: boolean\n    pendingWaitUntil?: Promise<any>\n    experimental: Pick<\n      RenderOpts['experimental'],\n      'isRoutePPREnabled' | 'authInterrupts' | 'useCacheTimeout'\n    >\n\n    /**\n     * Fetch metrics attached in patch-fetch.ts\n     **/\n    fetchMetrics?: FetchMetric[]\n\n    /**\n     * A hack around accessing the store value outside the context of the\n     * request.\n     *\n     * @internal\n     * @deprecated should only be used as a temporary workaround\n     */\n    // TODO: remove this when we resolve accessing the store outside the execution context\n    store?: WorkStore\n  } & Pick<\n    // Pull some properties from RenderOpts so that the docs are also\n    // mirrored.\n    RenderOpts,\n    | 'assetPrefix'\n    | 'supportsDynamicResponse'\n    | 'isBuildTimePrerendering'\n    | 'isDraftMode'\n    | 'isDebugDynamicAccesses'\n  > &\n    RequestLifecycleOpts &\n    Partial<Pick<RenderOpts, 'reactLoadableManifest'>>\n\n  /**\n   * The deployment ID of the current build.\n   */\n  deploymentId: string\n\n  /**\n   * The build ID of the current build.\n   */\n  buildId: string\n\n  // Tags that were previously revalidated (e.g. by a redirecting server action)\n  // and have already been sent to cache handlers.\n  previouslyRevalidatedTags: string[]\n}\n\nexport function createWorkStore({\n  page,\n  renderOpts,\n  isPrefetchRequest,\n  buildId,\n  deploymentId,\n  previouslyRevalidatedTags,\n  nonce,\n}: WorkStoreContext): WorkStore {\n  /**\n   * Rules of Static & Dynamic HTML:\n   *\n   *    1.) We must generate static HTML unless the caller explicitly opts\n   *        in to dynamic HTML support.\n   *\n   *    2.) If dynamic HTML support is requested, we must honor that request\n   *        or throw an error. It is the sole responsibility of the caller to\n   *        ensure they aren't e.g. requesting dynamic HTML for a static page.\n   *\n   *    3.) If the request is in draft mode, we must generate dynamic HTML.\n   *\n   *    4.) If the request is a server action, we must generate dynamic HTML.\n   *\n   * These rules help ensure that other existing features like request caching,\n   * coalescing, and ISR continue working as intended.\n   */\n  const isStaticGeneration =\n    !renderOpts.supportsDynamicResponse &&\n    !renderOpts.isDraftMode &&\n    !renderOpts.isPossibleServerAction\n\n  const shouldTrackFetchMetrics =\n    !!process.env.__NEXT_DEV_SERVER ||\n    // The only times we want to track fetch metrics outside of development is\n    // when we are performing a static generation and we either are in debug\n    // mode, or tracking fetch metrics was specifically opted into.\n    (isStaticGeneration &&\n      (!!process.env.NEXT_DEBUG_BUILD ||\n        process.env.NEXT_SSG_FETCH_METRICS === '1'))\n\n  const store: WorkStore = {\n    isStaticGeneration,\n    page,\n    route: normalizeAppPath(page),\n    incrementalCache:\n      // we fallback to a global incremental cache for edge-runtime locally\n      // so that it can access the fs cache without mocks\n      renderOpts.incrementalCache || (globalThis as any).__incrementalCache,\n    cacheLifeProfiles: renderOpts.cacheLifeProfiles,\n    useCacheTimeout: renderOpts.experimental.useCacheTimeout,\n    staticPageGenerationTimeout: renderOpts.staticPageGenerationTimeout,\n    isBuildTimePrerendering: renderOpts.isBuildTimePrerendering,\n    fetchCache: renderOpts.fetchCache,\n    isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,\n    requestId: undefined,\n    htmlRequestId: undefined,\n\n    isDraftMode: renderOpts.isDraftMode,\n\n    isPrefetchRequest,\n    buildId,\n    deploymentId,\n    reactLoadableManifest: renderOpts?.reactLoadableManifest || {},\n    assetPrefix: renderOpts?.assetPrefix || '',\n    nonce,\n\n    afterContext: createAfterContext(renderOpts),\n    cacheComponentsEnabled: renderOpts.cacheComponents,\n    validationLevel: renderOpts.validationLevel,\n    previouslyRevalidatedTags,\n    requestStartTime: performance.timeOrigin + performance.now(),\n    refreshTagsByCacheKind: createRefreshTagsByCacheKind(),\n    runInCleanSnapshot: createSnapshot(),\n    shouldTrackFetchMetrics,\n    reactServerErrorsByDigest: new Map(),\n  }\n\n  // TODO: remove this when we resolve accessing the store outside the execution context\n  renderOpts.store = store\n\n  return store\n}\n\nfunction createAfterContext(renderOpts: RequestLifecycleOpts): AfterContext {\n  const { waitUntil, onClose, onAfterTaskError } = renderOpts\n  return new AfterContext({\n    waitUntil,\n    onClose,\n    onTaskError: onAfterTaskError,\n  })\n}\n\n/**\n * Creates a map with lazy results that refresh tags for the respective cache\n * kind when they're awaited for the first time.\n */\nfunction createRefreshTagsByCacheKind(): Map<string, LazyResult<void>> {\n  const refreshTagsByCacheKind = new Map<string, LazyResult<void>>()\n  const cacheHandlers = getCacheHandlerEntries()\n\n  if (cacheHandlers) {\n    for (const [kind, cacheHandler] of cacheHandlers) {\n      if ('refreshTags' in cacheHandler) {\n        refreshTagsByCacheKind.set(\n          kind,\n          createLazyResult(async () => cacheHandler.refreshTags())\n        )\n      }\n    }\n  }\n\n  return refreshTagsByCacheKind\n}\n"],"names":["createWorkStore","page","renderOpts","isPrefetchRequest","buildId","deploymentId","previouslyRevalidatedTags","nonce","isStaticGeneration","supportsDynamicResponse","isDraftMode","isPossibleServerAction","shouldTrackFetchMetrics","process","env","__NEXT_DEV_SERVER","NEXT_DEBUG_BUILD","NEXT_SSG_FETCH_METRICS","store","route","normalizeAppPath","incrementalCache","globalThis","__incrementalCache","cacheLifeProfiles","useCacheTimeout","experimental","staticPageGenerationTimeout","isBuildTimePrerendering","fetchCache","isOnDemandRevalidate","requestId","undefined","htmlRequestId","reactLoadableManifest","assetPrefix","afterContext","createAfterContext","cacheComponentsEnabled","cacheComponents","validationLevel","requestStartTime","performance","timeOrigin","now","refreshTagsByCacheKind","createRefreshTagsByCacheKind","runInCleanSnapshot","createSnapshot","reactServerErrorsByDigest","Map","waitUntil","onClose","onAfterTaskError","AfterContext","onTaskError","cacheHandlers","getCacheHandlerEntries","kind","cacheHandler","set","createLazyResult","refreshTags"],"mappings":";;;;+BAyFgBA;;;eAAAA;;;8BA9Ea;0BAEI;4BACiB;0BACX;mCACR;AAyExB,SAASA,gBAAgB,EAC9BC,IAAI,EACJC,UAAU,EACVC,iBAAiB,EACjBC,OAAO,EACPC,YAAY,EACZC,yBAAyB,EACzBC,KAAK,EACY;IACjB;;;;;;;;;;;;;;;;GAgBC,GACD,MAAMC,qBACJ,CAACN,WAAWO,uBAAuB,IACnC,CAACP,WAAWQ,WAAW,IACvB,CAACR,WAAWS,sBAAsB;IAEpC,MAAMC,0BACJ,CAAC,CAACC,QAAQC,GAAG,CAACC,iBAAiB,IAC/B,0EAA0E;IAC1E,wEAAwE;IACxE,+DAA+D;IAC9DP,sBACE,CAAA,CAAC,CAACK,QAAQC,GAAG,CAACE,gBAAgB,IAC7BH,QAAQC,GAAG,CAACG,sBAAsB,KAAK,GAAE;IAE/C,MAAMC,QAAmB;QACvBV;QACAP;QACAkB,OAAOC,IAAAA,0BAAgB,EAACnB;QACxBoB,kBACE,qEAAqE;QACrE,m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