{"version":3,"sources":["../../../src/server/app-render/action-handler.ts"],"sourcesContent":["import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'node:http'\nimport type { SizeLimit } from '../../types'\nimport type { RequestStore } from '../app-render/work-unit-async-storage.external'\nimport type { AppRenderContext, GenerateFlight } from './app-render'\nimport type { AppPageModule } from '../route-modules/app-page/module'\nimport type { BaseNextRequest, BaseNextResponse } from '../base-http'\n\nimport {\n  RSC_HEADER,\n  RSC_CONTENT_TYPE_HEADER,\n  NEXT_ROUTER_STATE_TREE_HEADER,\n  ACTION_HEADER,\n  NEXT_ACTION_NOT_FOUND_HEADER,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n  NEXT_URL,\n  NEXT_ACTION_REVALIDATED_HEADER,\n} from '../../client/components/app-router-headers'\nimport {\n  getAccessFallbackHTTPStatus,\n  isHTTPAccessFallbackError,\n} from '../../client/components/http-access-fallback/http-access-fallback'\nimport {\n  getRedirectTypeFromError,\n  getURLFromRedirectError,\n} from '../../client/components/redirect'\nimport {\n  isRedirectError,\n  type RedirectType,\n} from '../../client/components/redirect-error'\nimport RenderResult, {\n  type AppPageRenderResultMetadata,\n} from '../render-result'\nimport type { WorkStore } from '../app-render/work-async-storage.external'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { FlightRenderResult } from './flight-render-result'\nimport {\n  filterReqHeaders,\n  actionsForbiddenHeaders,\n} from '../lib/server-ipc/utils'\nimport { getModifiedCookieValues } from '../web/spec-extension/adapters/request-cookies'\n\nimport {\n  JSON_CONTENT_TYPE_HEADER,\n  NEXT_CACHE_REVALIDATED_TAGS_HEADER,\n  NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,\n} from '../../lib/constants'\nimport { getServerActionRequestMetadata } from '../lib/server-action-request-meta'\nimport { isCsrfOriginAllowed } from './csrf-protection'\nimport { warn } from '../../build/output/log'\nimport { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies'\nimport { HeadersAdapter } from '../web/spec-extension/adapters/headers'\nimport { fromNodeOutgoingHttpHeaders } from '../web/utils'\nimport {\n  selectWorkerForForwarding,\n  type ServerModuleMap,\n  getServerActionsManifest,\n  getServerModuleMap,\n  getActionNotFoundError,\n  getInvalidServerReferenceIdError,\n} from './manifests-singleton'\nimport { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers'\nimport { normalizeFilePath } from './segment-explorer-path'\nimport {\n  extractInfoFromServerReferenceId,\n  mightBeServerReferenceId,\n} from '../../shared/lib/server-reference-info'\nimport type { ServerActionLogInfo } from '../dev/server-action-logger'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { synchronizeMutableCookies } from '../async-storage/request-store'\nimport type { TemporaryReferenceSet } from 'react-server-dom-webpack/server'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { executeRevalidates } from '../revalidation-utils'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { setCacheBustingSearchParamWithHash } from '../../client/components/router-reducer/set-cache-busting-search-param'\nimport {\n  ActionDidNotRevalidate,\n  ActionDidRevalidateStaticAndDynamic,\n} from '../../shared/lib/action-revalidation-kind'\nimport { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'\n\nconst INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'\n\n/**\n * Checks if the app has any server actions defined in any runtime.\n */\nfunction hasServerActions() {\n  const serverActionsManifest = getServerActionsManifest()\n\n  return (\n    Object.keys(serverActionsManifest.node).length > 0 ||\n    Object.keys(serverActionsManifest.edge).length > 0\n  )\n}\n\nfunction nodeHeadersToRecord(\n  headers: IncomingHttpHeaders | OutgoingHttpHeaders\n) {\n  const record: Record<string, string> = {}\n  for (const [key, value] of Object.entries(headers)) {\n    if (value !== undefined) {\n      record[key] = Array.isArray(value) ? value.join(', ') : `${value}`\n    }\n  }\n  return record\n}\n\nfunction getForwardedHeaders(\n  req: BaseNextRequest,\n  res: BaseNextResponse\n): Headers {\n  // Get request headers and cookies\n  const requestHeaders = req.headers\n  const requestCookies = new RequestCookies(HeadersAdapter.from(requestHeaders))\n\n  // Get response headers and cookies\n  const responseHeaders = res.getHeaders()\n  const responseCookies = new ResponseCookies(\n    fromNodeOutgoingHttpHeaders(responseHeaders)\n  )\n\n  // Merge request and response headers\n  const mergedHeaders = filterReqHeaders(\n    {\n      ...nodeHeadersToRecord(requestHeaders),\n      ...nodeHeadersToRecord(responseHeaders),\n    },\n    actionsForbiddenHeaders\n  ) as Record<string, string>\n\n  // Merge cookies into requestCookies, so responseCookies always take precedence\n  // and overwrite/delete those from requestCookies.\n  responseCookies.getAll().forEach((cookie) => {\n    if (typeof cookie.value === 'undefined') {\n      requestCookies.delete(cookie.name)\n    } else {\n      requestCookies.set(cookie)\n    }\n  })\n\n  // Update the 'cookie' header with the merged cookies\n  mergedHeaders['cookie'] = requestCookies.toString()\n\n  // Remove headers that should not be forwarded\n  delete mergedHeaders['transfer-encoding']\n\n  return new Headers(mergedHeaders)\n}\n\nfunction addRevalidationHeader(\n  res: BaseNextResponse,\n  {\n    workStore,\n    requestStore,\n  }: {\n    workStore: WorkStore\n    requestStore: RequestStore\n  }\n) {\n  // If a tag was revalidated, the client router needs to invalidate all the\n  // client router cache as they may be stale. And if a path was revalidated, the\n  // client needs to invalidate all subtrees below that path.\n\n  // TODO: Currently we don't send the specific tags or paths to the client,\n  // we just send a flag indicating that all the static data on the client\n  // should be invalidated. In the future, this will likely be a Bloom filter\n  // or bitmask of some kind.\n\n  // TODO-APP: Currently the prefetch cache doesn't have subtree information,\n  // so we need to invalidate the entire cache if a path was revalidated.\n  // TODO-APP: Currently paths are treated as tags, so the second element of the tuple\n  // is always empty.\n\n  // Only count tags without a profile (updateTag) as requiring client cache invalidation\n  // Tags with a profile (revalidateTag) use stale-while-revalidate and shouldn't\n  // trigger immediate client-side cache invalidation\n  const isTagRevalidated = workStore.pendingRevalidatedTags?.some(\n    (item) => item.profile === undefined\n  )\n    ? 1\n    : 0\n  const isCookieRevalidated = getModifiedCookieValues(\n    requestStore.mutableCookies\n  ).length\n    ? 1\n    : 0\n\n  // First check if a tag, cookie, or path was revalidated.\n  if (isTagRevalidated || isCookieRevalidated) {\n    res.setHeader(\n      NEXT_ACTION_REVALIDATED_HEADER,\n      JSON.stringify(ActionDidRevalidateStaticAndDynamic)\n    )\n  } else if (\n    // Check for refresh() actions. This will invalidate only the dynamic data.\n    workStore.pathWasRevalidated !== undefined &&\n    workStore.pathWasRevalidated !== ActionDidNotRevalidate\n  ) {\n    res.setHeader(\n      NEXT_ACTION_REVALIDATED_HEADER,\n      JSON.stringify(workStore.pathWasRevalidated)\n    )\n  }\n}\n\n/**\n * Forwards a server action request to a separate worker. Used when the requested action is not available in the current worker.\n */\nasync function createForwardedActionResponse(\n  req: BaseNextRequest,\n  res: BaseNextResponse,\n  host: Host,\n  workerPathname: string,\n  basePath: string\n) {\n  if (!host) {\n    throw new Error(\n      'Invariant: Missing `host` header from a forwarded Server Actions request.'\n    )\n  }\n\n  const forwardedHeaders = getForwardedHeaders(req, res)\n\n  // indicate that this action request was forwarded from another worker\n  // we use this to skip rendering the flight tree so that we don't update the UI\n  // with the response from the forwarded worker\n  forwardedHeaders.set('x-action-forwarded', '1')\n\n  // TODO: Remove __NEXT_PRIVATE_ORIGIN\n  let origin: string | undefined = process.env.__NEXT_PRIVATE_ORIGIN\n  if (origin === undefined) {\n    const initUrl = getRequestMeta(req, 'initURL')\n    if (initUrl !== undefined) {\n      try {\n        const parsedUrl = new URL(initUrl)\n        origin = parsedUrl.origin\n      } catch (error) {\n        throw new Error(\n          'Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server.',\n          { cause: error }\n        )\n      }\n    } else {\n      throw new InvariantError('Missing initURL')\n    }\n  }\n\n  const fetchUrl = new URL(`${origin}${basePath}${workerPathname}`)\n\n  try {\n    let body: BodyInit | ReadableStream<Uint8Array> | undefined\n    if (\n      // The type check here ensures that `req` is correctly typed, and the\n      // environment variable check provides dead code elimination.\n      process.env.NEXT_RUNTIME === 'edge' &&\n      isWebNextRequest(req)\n    ) {\n      if (!req.body) {\n        throw new Error('Invariant: missing request body.')\n      }\n\n      body = req.body\n    } else if (\n      // The type check here ensures that `req` is correctly typed, and the\n      // environment variable check provides dead code elimination.\n      process.env.NEXT_RUNTIME !== 'edge' &&\n      isNodeNextRequest(req)\n    ) {\n      body = req.stream()\n    } else {\n      throw new Error('Invariant: Unknown request type.')\n    }\n\n    // Forward the request to the new worker\n    const response = await fetch(fetchUrl, {\n      method: 'POST',\n      body,\n      duplex: 'half',\n      headers: forwardedHeaders,\n      redirect: 'manual',\n      next: {\n        // @ts-ignore\n        internal: 1,\n      },\n    })\n\n    if (\n      response.headers.get('content-type')?.startsWith(RSC_CONTENT_TYPE_HEADER)\n    ) {\n      // copy the headers from the redirect response to the response we're sending\n      for (const [key, value] of response.headers) {\n        if (!actionsForbiddenHeaders.includes(key)) {\n          res.setHeader(key, value)\n        }\n      }\n\n      return new FlightRenderResult(response.body!)\n    }\n\n    // Since we aren't consuming the response body, we cancel it to avoid memory leaks\n    response.body?.cancel()\n\n    // Pass the action-not-found marker through so the client throws\n    // UnrecognizedActionError instead of a generic \"unexpected response\".\n    if (response.headers.get(NEXT_ACTION_NOT_FOUND_HEADER) === '1') {\n      res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')\n      res.setHeader('content-type', 'text/plain')\n      res.statusCode = 404\n      return RenderResult.fromStatic('Server action not found.', 'text/plain')\n    }\n  } catch (err) {\n    // we couldn't stream the forwarded response, so we'll just return an empty response\n    console.error(`failed to forward action response`, err)\n  }\n\n  return RenderResult.fromStatic('{}', JSON_CONTENT_TYPE_HEADER)\n}\n\n/**\n * Returns the parsed redirect URL if we deem that it is hosted by us.\n *\n * We handle both relative and absolute redirect URLs.\n *\n * In case the redirect URL is not relative to the application we return `null`.\n */\nfunction getAppRelativeRedirectUrl(\n  basePath: string,\n  host: Host,\n  redirectUrl: string,\n  currentPathname?: string\n): URL | null {\n  if (redirectUrl.startsWith('/')) {\n    // Absolute path - just add basePath\n    return new URL(`${basePath}${redirectUrl}`, 'http://n')\n  } else if (redirectUrl.startsWith('.')) {\n    // Relative path - resolve relative to current pathname\n    let base = currentPathname || '/'\n    // Ensure the base path ends with a slash so relative resolution works correctly\n    // e.g., \"./subpage\" from \"/subdir\" should resolve to \"/subdir/subpage\"\n    // not \"/subpage\"\n    if (!base.endsWith('/')) {\n      base = base + '/'\n    }\n    const resolved = new URL(redirectUrl, `http://n${base}`)\n    // Include basePath in the final URL\n    return new URL(\n      `${basePath}${resolved.pathname}${resolved.search}${resolved.hash}`,\n      'http://n'\n    )\n  }\n\n  const parsedRedirectUrl = new URL(redirectUrl)\n\n  if (host?.value !== parsedRedirectUrl.host) {\n    return null\n  }\n\n  // At this point the hosts are the same, just confirm we\n  // are routing to a path underneath the `basePath`\n  return parsedRedirectUrl.pathname.startsWith(basePath)\n    ? parsedRedirectUrl\n    : null\n}\n\nasync function createRedirectRenderResult(\n  req: BaseNextRequest,\n  res: BaseNextResponse,\n  originalHost: Host,\n  redirectUrl: string,\n  redirectType: RedirectType,\n  basePath: string,\n  workStore: WorkStore,\n  currentPathname?: string\n) {\n  res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`)\n\n  // If we're redirecting to another route of this Next.js application, we'll\n  // try to stream the response from the other worker path. When that works,\n  // we can save an extra roundtrip and avoid a full page reload.\n  // When the redirect URL starts with a `/` or is to the same host, under the\n  // `basePath` we treat it as an app-relative redirect;\n  const appRelativeRedirectUrl = getAppRelativeRedirectUrl(\n    basePath,\n    originalHost,\n    redirectUrl,\n    currentPathname\n  )\n\n  if (appRelativeRedirectUrl) {\n    if (!originalHost) {\n      throw new Error(\n        'Invariant: Missing `host` header from a forwarded Server Actions request.'\n      )\n    }\n\n    const forwardedHeaders = getForwardedHeaders(req, res)\n    forwardedHeaders.set(RSC_HEADER, '1')\n\n    // TODO: Remove __NEXT_PRIVATE_ORIGIN\n    let origin: string | undefined = process.env.__NEXT_PRIVATE_ORIGIN\n    if (origin === undefined) {\n      const initUrl = getRequestMeta(req, 'initURL')\n      if (initUrl !== undefined) {\n        try {\n          const parsedUrl = new URL(initUrl)\n\n          origin = parsedUrl.origin\n        } catch (error) {\n          throw new Error(\n            'Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server.',\n            { cause: error }\n          )\n        }\n      } else {\n        throw new InvariantError('Missing initURL')\n      }\n    }\n\n    const fetchUrl = new URL(\n      `${origin}${appRelativeRedirectUrl.pathname}${appRelativeRedirectUrl.search}`\n    )\n\n    if (workStore.pendingRevalidatedTags) {\n      forwardedHeaders.set(\n        NEXT_CACHE_REVALIDATED_TAGS_HEADER,\n        workStore.pendingRevalidatedTags.map((item) => item.tag).join(',')\n      )\n      forwardedHeaders.set(\n        NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,\n        workStore.incrementalCache?.prerenderManifest?.preview?.previewModeId ||\n          ''\n      )\n    }\n\n    // Ensures that when the path was revalidated we don't return a partial response on redirects\n    forwardedHeaders.delete(NEXT_ROUTER_STATE_TREE_HEADER)\n    // When an action follows a redirect, it's no longer handling an action: it's just a normal RSC request\n    // to the requested URL. We should remove the `next-action` header so that it's not treated as an action\n    forwardedHeaders.delete(ACTION_HEADER)\n\n    try {\n      const cacheBustingSearchParam = await computeCacheBustingSearchParam(\n        forwardedHeaders.get(NEXT_ROUTER_PREFETCH_HEADER)\n          ? ('1' as const)\n          : undefined,\n        forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? undefined,\n        forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,\n        forwardedHeaders.get(NEXT_URL) ?? undefined\n      )\n      setCacheBustingSearchParamWithHash(fetchUrl, cacheBustingSearchParam)\n\n      const response = await fetch(fetchUrl, {\n        method: 'GET',\n        headers: forwardedHeaders,\n        next: {\n          // @ts-ignore\n          internal: 1,\n        },\n      })\n\n      if (\n        response.headers\n          .get('content-type')\n          ?.startsWith(RSC_CONTENT_TYPE_HEADER)\n      ) {\n        // copy the headers from the redirect response to the response we're sending\n        for (const [key, value] of response.headers) {\n          if (!actionsForbiddenHeaders.includes(key)) {\n            res.setHeader(key, value)\n          }\n        }\n\n        return new FlightRenderResult(response.body!)\n      } else {\n        // Since we aren't consuming the response body, we cancel it to avoid memory leaks\n        response.body?.cancel()\n      }\n    } catch (err) {\n      // we couldn't stream the redirect response, so we'll just do a normal redirect\n      console.error(`failed to get redirect response`, err)\n    }\n  }\n\n  return RenderResult.EMPTY\n}\n\n// Used to compare Host header and Origin header.\nconst enum HostType {\n  XForwardedHost = 'x-forwarded-host',\n  Host = 'host',\n}\ntype Host =\n  | {\n      type: HostType.XForwardedHost\n      value: string\n    }\n  | {\n      type: HostType.Host\n      value: string\n    }\n  | undefined\n\n/**\n * Ensures the value of the header can't create long logs.\n */\nfunction limitUntrustedHeaderValueForLogs(value: string) {\n  return value.length > 100 ? value.slice(0, 100) + '...' : value\n}\n\nexport function parseHostHeader(\n  headers: IncomingHttpHeaders,\n  originDomain?: string\n) {\n  const forwardedHostHeader = headers['x-forwarded-host']\n  const forwardedHostHeaderValue =\n    forwardedHostHeader && Array.isArray(forwardedHostHeader)\n      ? forwardedHostHeader[0]\n      : forwardedHostHeader?.split(',')?.[0]?.trim()\n  const hostHeader = headers['host']\n\n  if (originDomain) {\n    return forwardedHostHeaderValue === originDomain\n      ? {\n          type: HostType.XForwardedHost,\n          value: forwardedHostHeaderValue,\n        }\n      : hostHeader === originDomain\n        ? {\n            type: HostType.Host,\n            value: hostHeader,\n          }\n        : undefined\n  }\n\n  return forwardedHostHeaderValue\n    ? {\n        type: HostType.XForwardedHost,\n        value: forwardedHostHeaderValue,\n      }\n    : hostHeader\n      ? {\n          type: HostType.Host,\n          value: hostHeader,\n        }\n      : undefined\n}\n\ntype ServerActionsConfig = {\n  bodySizeLimit?: SizeLimit\n  allowedOrigins?: string[]\n}\n\ntype HandleActionResult =\n  | {\n      /** An MPA action threw notFound(), and we need to render the appropriate HTML */\n      type: 'not-found'\n    }\n  | {\n      type: 'done'\n      result: RenderResult | undefined\n      formState?: any\n    }\n  /** The request turned out not to be a server action. */\n  | null\n\nexport async function handleAction({\n  req,\n  res,\n  ComponentMod,\n  generateFlight,\n  workStore,\n  requestStore,\n  serverActions,\n  ctx,\n  metadata,\n}: {\n  req: BaseNextRequest\n  res: BaseNextResponse\n  ComponentMod: AppPageModule\n  generateFlight: GenerateFlight\n  workStore: WorkStore\n  requestStore: RequestStore\n  serverActions?: ServerActionsConfig\n  ctx: AppRenderContext\n  metadata: AppPageRenderResultMetadata\n}): Promise<HandleActionResult> {\n  const contentType = req.headers['content-type']\n  const { page } = ctx.renderOpts\n  const serverModuleMap = getServerModuleMap()\n\n  const {\n    actionId,\n    isMultipartAction,\n    isFetchAction,\n    isURLEncodedAction,\n    isPossibleServerAction,\n  } = getServerActionRequestMetadata(req)\n\n  const handleUnrecognizedFetchAction = (err: unknown): HandleActionResult => {\n    // If the deployment doesn't have skew protection, this is expected to occasionally happen,\n    // so we use a warning instead of an error.\n    console.warn(err)\n\n    // Return an empty response with a header that the client router will interpret.\n    // We don't need to waste time encoding a flight response, and using a blank body + header\n    // means that unrecognized actions can also be handled at the infra level\n    // (i.e. without needing to invoke a lambda)\n    res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')\n    res.setHeader('content-type', 'text/plain')\n    res.statusCode = 404\n    return {\n      type: 'done',\n      result: RenderResult.fromStatic('Server action not found.', 'text/plain'),\n    }\n  }\n\n  // If it can't be a Server Action, skip handling.\n  // Note that this can be a false positive -- any multipart/urlencoded POST can get us here,\n  // But won't know if it's an MPA action or not until we call `decodeAction` below.\n  if (!isPossibleServerAction) {\n    return null\n  }\n\n  // We don't currently support URL encoded actions, so we bail out early.\n  // Depending on if it's a fetch action or an MPA, we return a different response.\n  if (isURLEncodedAction) {\n    if (isFetchAction) {\n      return {\n        type: 'not-found',\n      }\n    } else {\n      // This is an MPA action, so we return null\n      return null\n    }\n  }\n\n  // If the app has no server actions at all, we can 404 early.\n  if (!hasServerActions()) {\n    const error =\n      actionId !== null && !mightBeServerReferenceId(actionId)\n        ? getInvalidServerReferenceIdError(actionId)\n        : getActionNotFoundError(actionId)\n    return handleUnrecognizedFetchAction(error)\n  }\n\n  if (workStore.isStaticGeneration) {\n    throw new Error(\n      \"Invariant: server actions can't be handled during static rendering\"\n    )\n  }\n\n  let temporaryReferences: TemporaryReferenceSet | undefined\n\n  // When running actions the default is no-store, you can still `cache: 'force-cache'`\n  workStore.fetchCache = 'default-no-store'\n\n  const originHeader = req.headers['origin']\n  const originHost =\n    typeof originHeader === 'string'\n      ? // 'null' is a valid origin e.g. from privacy-sensitive contexts like sandboxed iframes.\n        // However, these contexts can still send along credentials like cookies,\n        // so we need to check if they're allowed cross-origin requests.\n        originHeader === 'null'\n        ? 'null'\n        : new URL(originHeader).host\n      : undefined\n  const host = parseHostHeader(req.headers)\n\n  let warning: string | undefined = undefined\n\n  function warnBadServerActionRequest() {\n    if (warning) {\n      warn(warning)\n    }\n  }\n  // This is to prevent CSRF attacks. If `x-forwarded-host` is set, we need to\n  // ensure that the request is coming from the same host.\n  if (!originHost) {\n    // This is a handcrafted request without an origin or a request from an unsafe browser.\n    // We'll let this through but log a warning.\n    // We can't guard against unsafe browsers and handcrafted requests can't contain\n    // user credentials that haven't been shared willingly.\n    warning = 'Missing `origin` header from a forwarded Server Actions request.'\n  } else if (!host || originHost !== host.value) {\n    // If the customer sets a list of allowed origins, we'll allow the request.\n    // These are considered safe but might be different from forwarded host set\n    // by the infra (i.e. reverse proxies).\n    if (isCsrfOriginAllowed(originHost, serverActions?.allowedOrigins)) {\n      // Ignore it\n    } else {\n      if (host) {\n        // This seems to be an CSRF attack. We should not proceed the action.\n        console.error(\n          `\\`${\n            host.type\n          }\\` header with value \\`${limitUntrustedHeaderValueForLogs(\n            host.value\n          )}\\` does not match \\`origin\\` header with value \\`${limitUntrustedHeaderValueForLogs(\n            originHost\n          )}\\` from a forwarded Server Actions request. Aborting the action.`\n        )\n      } else {\n        // This is an attack. We should not proceed the action.\n        console.error(\n          `\\`x-forwarded-host\\` or \\`host\\` headers are not provided. One of these is needed to compare the \\`origin\\` header from a forwarded Server Actions request. Aborting the action.`\n        )\n      }\n\n      const error = new Error('Invalid Server Actions request.')\n\n      if (isFetchAction) {\n        res.statusCode = 500\n        metadata.statusCode = 500\n\n        const promise = Promise.reject(error)\n        try {\n          // we need to await the promise to trigger the rejection early\n          // so that it's already handled by the time we call\n          // the RSC runtime. Otherwise, it will throw an unhandled\n          // promise rejection error in the renderer.\n          await promise\n        } catch {\n          // swallow error, it's gonna be handled on the client\n        }\n\n        return {\n          type: 'done',\n          result: await generateFlight(req, ctx, requestStore, {\n            actionResult: promise,\n            // We didn't execute an action, so no revalidations could have\n            // occurred. We can skip rendering the page.\n            skipPageRendering: true,\n            temporaryReferences,\n          }),\n        }\n      }\n\n      throw error\n    }\n  }\n\n  // ensure we avoid caching server actions unexpectedly\n  res.setHeader(\n    'Cache-Control',\n    'no-cache, no-store, max-age=0, must-revalidate'\n  )\n\n  const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])\n\n  // Only attempt to forward if this request has not already been forwarded.\n  // Otherwise middleware that rewrites the action POST can cause the receiving\n  // worker to forward again, looping indefinitely.\n  if (actionId && !actionWasForwarded) {\n    const forwardedWorker = selectWorkerForForwarding(actionId, page)\n\n    // If forwardedWorker is truthy, it means there isn't a worker for the\n    // action in the current handler, so we forward the request to a worker that\n    // has the action.\n    if (forwardedWorker) {\n      return {\n        type: 'done',\n        result: await createForwardedActionResponse(\n          req,\n          res,\n          host,\n          forwardedWorker,\n          ctx.renderOpts.basePath\n        ),\n      }\n    }\n  }\n\n  try {\n    return await actionAsyncStorage.run(\n      { isAction: true },\n      async (): Promise<HandleActionResult> => {\n        // We only use these for fetch actions -- MPA actions handle them inside `decodeAction`.\n        let actionModId: string | number | undefined\n        let boundActionArguments: unknown[] = []\n\n        const defaultBodySizeLimit = '1 MB'\n        const bodySizeLimit =\n          serverActions?.bodySizeLimit ?? defaultBodySizeLimit\n        const bodySizeLimitBytes =\n          bodySizeLimit !== defaultBodySizeLimit\n            ? (\n                require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')\n              ).parse(bodySizeLimit)\n            : 1024 * 1024 // 1 MB\n\n        if (\n          // The type check here ensures that `req` is correctly typed, and the\n          // environment variable check provides dead code elimination.\n          process.env.NEXT_RUNTIME === 'edge' &&\n          isWebNextRequest(req)\n        ) {\n          if (!req.body) {\n            throw new Error('invariant: Missing request body.')\n          }\n\n          // Use react-server-dom-webpack/server\n          const {\n            createTemporaryReferenceSet,\n            decodeReply,\n            decodeAction,\n            decodeFormState,\n          } = ComponentMod\n\n          temporaryReferences = createTemporaryReferenceSet()\n\n          if (isMultipartAction) {\n            // TODO-APP: Add streaming support\n            // Read the body stream with size tracking to enforce bodySizeLimitBytes.\n            // We cannot call req.request.formData() directly as that would bypass\n            // the body size limit entirely.\n            const edgeChunks: Uint8Array[] = []\n            let edgeBodySize = 0\n            const edgeReader = req.body.getReader()\n            while (true) {\n              const { done, value } = await edgeReader.read()\n              if (done) break\n              edgeBodySize += value.byteLength\n              if (edgeBodySize > bodySizeLimitBytes) {\n                const { ApiError } =\n                  require('../api-utils') as typeof import('../api-utils')\n                throw new ApiError(\n                  413,\n                  `Body exceeded ${bodySizeLimit} limit.\\n` +\n                    `To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`\n                )\n              }\n              edgeChunks.push(value)\n            }\n            // Reconstruct a Blob from the buffered chunks and parse formData from it.\n            // Note: we must pass the original Content-Type as an explicit header\n            // rather than relying on the Blob's `type`. The Blob constructor\n            // normalizes `type` to ASCII lowercase per the File API spec, which\n            // would lowercase the multipart boundary parameter (e.g.\n            // `boundary=----WebKitFormBoundaryAbCdEf`). The body bytes contain the\n            // original mixed-case boundary delimiter, so a lowercased boundary\n            // would fail to match and `formData()` would throw. An explicit header\n            // on the Request takes precedence over the Blob's normalized type.\n            const edgeBodyBlob = new Blob(edgeChunks as BlobPart[])\n            const formData = await new Request('http://n/', {\n              method: 'POST',\n              headers: { 'content-type': req.headers['content-type'] ?? '' },\n              body: edgeBodyBlob,\n            }).formData()\n            if (isFetchAction) {\n              // A fetch action with a multipart body.\n\n              try {\n                actionModId = getActionModIdOrError(actionId, serverModuleMap)\n              } catch (err) {\n                return handleUnrecognizedFetchAction(err)\n              }\n\n              boundActionArguments = await decodeReply<unknown[]>(\n                formData,\n                serverModuleMap,\n                { temporaryReferences }\n              )\n            } else {\n              // Multipart POST, but not a fetch action.\n              // Potentially an MPA action, we have to try decoding it to check.\n              if (areAllActionIdsValid(formData, serverModuleMap) === false) {\n                // TODO: This can be from skew or manipulated input. We should handle this case\n                // more gracefully but this preserves the prior behavior where decodeAction would throw instead.\n                throw new Error(\n                  `Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n                )\n              }\n\n              const action = await decodeAction(formData, serverModuleMap)\n              if (typeof action === 'function') {\n                // an MPA action.\n\n                // Only warn if it's a server action, otherwise skip for other post requests\n                warnBadServerActionRequest()\n\n                const { actionResult } = await executeActionAndPrepareForRender(\n                  action as () => Promise<unknown>,\n                  [],\n                  workStore,\n                  requestStore,\n                  actionWasForwarded\n                )\n\n                const formState = await decodeFormState(\n                  actionResult,\n                  formData,\n                  serverModuleMap\n                )\n\n                // Skip the fetch path.\n                // We need to render a full HTML version of the page for the response, we'll handle that in app-render.\n                return {\n                  type: 'done',\n                  result: undefined,\n                  formState,\n                }\n              } else {\n                // We couldn't decode an action, so this POST request turned out not to be a server action request.\n                return null\n              }\n            }\n          } else {\n            // POST with non-multipart body.\n\n            // If it's not multipart AND not a fetch action,\n            // then it can't be an action request.\n            if (!isFetchAction) {\n              return null\n            }\n\n            try {\n              actionModId = getActionModIdOrError(actionId, serverModuleMap)\n            } catch (err) {\n              return handleUnrecognizedFetchAction(err)\n            }\n\n            // A fetch action with a non-multipart body.\n            // In practice, this happens if `encodeReply` returned a string instead of FormData,\n            // which can happen for very simple JSON-like values that don't need multiple flight rows.\n\n            const chunks: Buffer[] = []\n            let nonMultipartBodySize = 0\n            const reader = req.body.getReader()\n            while (true) {\n              const { done, value } = await reader.read()\n              if (done) {\n                break\n              }\n\n              nonMultipartBodySize += value.byteLength\n              if (nonMultipartBodySize > bodySizeLimitBytes) {\n                const { ApiError } =\n                  require('../api-utils') as typeof import('../api-utils')\n                throw new ApiError(\n                  413,\n                  `Body exceeded ${bodySizeLimit} limit.\\n` +\n                    `To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`\n                )\n              }\n              chunks.push(value)\n            }\n\n            const actionData = Buffer.concat(chunks).toString('utf-8')\n\n            boundActionArguments = await decodeReply<unknown[]>(\n              actionData,\n              serverModuleMap,\n              { temporaryReferences }\n            )\n          }\n        } else if (\n          // The type check here ensures that `req` is correctly typed, and the\n          // environment variable check provides dead code elimination.\n          process.env.NEXT_RUNTIME !== 'edge' &&\n          isNodeNextRequest(req)\n        ) {\n          // Use react-server-dom-webpack/server.node which supports streaming\n          const {\n            createTemporaryReferenceSet,\n            decodeReply,\n            decodeReplyFromBusboy,\n            decodeAction,\n            decodeFormState,\n          } = require(\n            `./react-server.node`\n          ) as typeof import('./react-server.node')\n\n          temporaryReferences = createTemporaryReferenceSet()\n\n          const { PassThrough, Readable, Transform } =\n            require('node:stream') as typeof import('node:stream')\n          const { pipeline } =\n            require('node:stream/promises') as typeof import('node:stream/promises')\n\n          // If actionBody was stashed in request meta (from parsing the postponed\n          // state prefix in minimal mode), use it instead of req.body\n          const actionBodyFromMeta = getRequestMeta(req, 'actionBody')\n          const body: import('node:stream').Readable = actionBodyFromMeta\n            ? Readable.from(actionBodyFromMeta)\n            : req.body\n\n          let size = 0\n          const sizeLimitTransform = new Transform({\n            transform(chunk, encoding, callback) {\n              size += Buffer.byteLength(chunk, encoding)\n              if (size > bodySizeLimitBytes) {\n                const { ApiError } =\n                  require('../api-utils') as typeof import('../api-utils')\n\n                callback(\n                  new ApiError(\n                    413,\n                    `Body exceeded ${bodySizeLimit} limit.\\n` +\n                      `To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`\n                  )\n                )\n                return\n              }\n\n              callback(null, chunk)\n            },\n          })\n\n          if (isMultipartAction) {\n            if (isFetchAction) {\n              // A fetch action with a multipart body.\n\n              try {\n                actionModId = getActionModIdOrError(actionId, serverModuleMap)\n              } catch (err) {\n                return handleUnrecognizedFetchAction(err)\n              }\n\n              const busboy = (\n                require('next/dist/compiled/busboy') as typeof import('next/dist/compiled/busboy')\n              )({\n                defParamCharset: 'utf8',\n                headers: req.headers,\n                limits: { fieldSize: bodySizeLimitBytes },\n              })\n\n              const abortController = new AbortController()\n              try {\n                ;[, boundActionArguments] = await Promise.all([\n                  pipeline(body, sizeLimitTransform, busboy, {\n                    signal: abortController.signal,\n                  }),\n                  decodeReplyFromBusboy<unknown[]>(busboy, serverModuleMap, {\n                    temporaryReferences,\n                  }),\n                ])\n              } catch (err) {\n                abortController.abort()\n                throw err\n              }\n            } else {\n              // Multipart POST, but not a fetch action.\n              // Potentially an MPA action, we have to try decoding it to check.\n\n              const sizeLimitedBody = new PassThrough()\n\n              // React doesn't yet publish a busboy version of decodeAction\n              // so we polyfill the parsing of FormData.\n              const fakeRequest = new Request('http://localhost', {\n                method: 'POST',\n                // @ts-expect-error\n                headers: { 'Content-Type': contentType },\n                body: Readable.toWeb(\n                  sizeLimitedBody\n                ) as ReadableStream<Uint8Array>,\n                duplex: 'half',\n              })\n\n              let formData: FormData\n              const abortController = new AbortController()\n              try {\n                ;[, formData] = await Promise.all([\n                  pipeline(body, sizeLimitTransform, sizeLimitedBody, {\n                    signal: abortController.signal,\n                  }),\n                  fakeRequest.formData(),\n                ])\n              } catch (err) {\n                abortController.abort()\n                throw err\n              }\n\n              if (areAllActionIdsValid(formData, serverModuleMap) === false) {\n                // TODO: This can be from skew or manipulated input. We should handle this case\n                // more gracefully but this preserves the prior behavior where decodeAction would throw instead.\n                throw new Error(\n                  `Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n                )\n              }\n\n              // TODO: Refactor so it is harder to accidentally decode an action before you have validated that the\n              // action referred to is available.\n              const action = await decodeAction(formData, serverModuleMap)\n              if (typeof action === 'function') {\n                // an MPA action.\n\n                // Only warn if it's a server action, otherwise skip for other post requests\n                warnBadServerActionRequest()\n\n                const { actionResult } = await executeActionAndPrepareForRender(\n                  action as () => Promise<unknown>,\n                  [],\n                  workStore,\n                  requestStore,\n                  actionWasForwarded\n                )\n\n                const formState = await decodeFormState(\n                  actionResult,\n                  formData,\n                  serverModuleMap\n                )\n\n                // Skip the fetch path.\n                // We need to render a full HTML version of the page for the response, we'll handle that in app-render.\n                return {\n                  type: 'done',\n                  result: undefined,\n                  formState,\n                }\n              } else {\n                // We couldn't decode an action, so this POST request turned out not to be a server action request.\n                return null\n              }\n            }\n          } else {\n            // POST with non-multipart body.\n\n            // If it's not multipart AND not a fetch action,\n            // then it can't be an action request.\n            if (!isFetchAction) {\n              return null\n            }\n\n            try {\n              actionModId = getActionModIdOrError(actionId, serverModuleMap)\n            } catch (err) {\n              return handleUnrecognizedFetchAction(err)\n            }\n\n            // A fetch action with a non-multipart body.\n            // In practice, this happens if `encodeReply` returned a string instead of FormData,\n            // which can happen for very simple JSON-like values that don't need multiple flight rows.\n\n            const sizeLimitedBody = new PassThrough()\n\n            const chunks: Buffer[] = []\n            await Promise.all([\n              pipeline(body, sizeLimitTransform, sizeLimitedBody),\n              (async () => {\n                for await (const chunk of sizeLimitedBody) {\n                  chunks.push(Buffer.from(chunk))\n                }\n              })(),\n            ])\n\n            const actionData = Buffer.concat(chunks).toString('utf-8')\n\n            boundActionArguments = await decodeReply<unknown[]>(\n              actionData,\n              serverModuleMap,\n              { temporaryReferences }\n            )\n          }\n        } else {\n          throw new Error('Invariant: Unknown request type.')\n        }\n\n        // actions.js\n        // app/page.js\n        //   action worker1\n        //     appRender1\n\n        // app/foo/page.js\n        //   action worker2\n        //     appRender\n\n        // / -> fire action -> POST / -> appRender1 -> modId for the action file\n        // /foo -> fire action -> POST /foo -> appRender2 -> modId for the action file\n\n        const actionMod = (await ComponentMod.__next_app__.require(\n          actionModId\n        )) as Record<string, (...args: unknown[]) => Promise<unknown>>\n        const actionHandler =\n          actionMod[\n            // `actionId` must exist if we got here, as otherwise we would have thrown an error above\n            actionId!\n          ]\n\n        // Log server action call in development when enabled\n        let logInfo: ServerActionLogInfo | null = null\n        const { type: actionType } = extractInfoFromServerReferenceId(actionId!)\n        if (\n          process.env.NODE_ENV === 'development' &&\n          ctx.renderOpts.logServerFunctions &&\n          // TODO: For now, skip logging for 'use cache' Server Functions as the\n          // output needs more work, or a different approach entirely.\n          actionType !== 'use-cache'\n        ) {\n          const serverActionsManifest = getServerActionsManifest()\n          const runtime = process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n          const actionInfo = serverActionsManifest[runtime]?.[actionId!]\n\n          if (actionInfo) {\n            const isInlineAction =\n              actionInfo.exportedName?.startsWith(INLINE_ACTION_PREFIX)\n\n            const projectDir =\n              ctx.renderOpts.dir ||\n              (process.env.NEXT_RUNTIME === 'edge' ? '' : process.cwd())\n            const location = normalizeFilePath(projectDir, actionInfo.filename)\n\n            // Format function name for display\n            let functionName: string\n            if (isInlineAction) {\n              functionName = '<inline action>'\n            } else if (actionInfo.exportedName === 'default') {\n              functionName = 'default'\n            } else {\n              functionName = actionInfo.exportedName || '<action>'\n            }\n\n            logInfo = { functionName, args: boundActionArguments, location }\n          }\n        }\n\n        const startTime = performance.now()\n        const { actionResult, skipPageRendering } =\n          await executeActionAndPrepareForRender(\n            actionHandler,\n            boundActionArguments,\n            workStore,\n            requestStore,\n            actionWasForwarded\n          ).finally(() => {\n            addRevalidationHeader(res, { workStore, requestStore })\n            if (logInfo) {\n              // Store server action log info to be logged after the request log\n              const duration = Math.round(performance.now() - startTime)\n              addRequestMeta(req, 'devServerActionLog', {\n                functionName: logInfo.functionName,\n                args: logInfo.args,\n                location: logInfo.location,\n                duration,\n              })\n            }\n          })\n\n        // For form actions, we need to continue rendering the page.\n        if (isFetchAction) {\n          // If we skip page rendering, we need to ensure pending revalidates\n          // are awaited before closing the response. Otherwise, this will be\n          // done after rendering the page.\n          const maybeRevalidatesPromise = skipPageRendering\n            ? executeRevalidates(workStore)\n            : false\n\n          return {\n            type: 'done',\n            result: await actionAsyncStorage.exit(() =>\n              generateFlight(req, ctx, requestStore, {\n                actionResult: Promise.resolve(actionResult),\n                skipPageRendering,\n                temporaryReferences,\n                waitUntil:\n                  maybeRevalidatesPromise === false\n                    ? undefined\n                    : maybeRevalidatesPromise,\n              })\n            ),\n          }\n        } else {\n          // TODO: this shouldn't be reachable, because all non-fetch codepaths return early.\n          // this will be handled in a follow-up refactor PR.\n          return null\n        }\n      }\n    )\n  } catch (err) {\n    if (isRedirectError(err)) {\n      const redirectUrl = getURLFromRedirectError(err)\n      const redirectType = getRedirectTypeFromError(err)\n\n      if (isFetchAction) {\n        // Fetch actions communicate redirects through `x-action-redirect` and\n        // can include the redirect target's Flight response in the body. Since\n        // this is not an HTTP redirect, keep the response successful.\n        res.statusCode = 200\n        metadata.statusCode = 200\n\n        return {\n          type: 'done',\n          result: await createRedirectRenderResult(\n            req,\n            res,\n            host,\n            redirectUrl,\n            redirectType,\n            ctx.renderOpts.basePath,\n            workStore,\n            requestStore.url.pathname\n          ),\n        }\n      }\n\n      // For an MPA action, the redirect doesn't need a body, just a Location header.\n      res.statusCode = RedirectStatusCode.SeeOther\n      metadata.statusCode = RedirectStatusCode.SeeOther\n      res.setHeader('Location', redirectUrl)\n      return {\n        type: 'done',\n        result: RenderResult.EMPTY,\n      }\n    } else if (isHTTPAccessFallbackError(err)) {\n      res.statusCode = getAccessFallbackHTTPStatus(err)\n      metadata.statusCode = res.statusCode\n\n      if (isFetchAction) {\n        const promise = Promise.reject(err)\n        try {\n          // we need to await the promise to trigger the rejection early\n          // so that it's already handled by the time we call\n          // the RSC runtime. Otherwise, it will throw an unhandled\n          // promise rejection error in the renderer.\n          await promise\n        } catch {\n          // swallow error, it's gonna be handled on the client\n        }\n        return {\n          type: 'done',\n          result: await generateFlight(req, ctx, requestStore, {\n            skipPageRendering: false,\n            actionResult: promise,\n            temporaryReferences,\n          }),\n        }\n      }\n\n      // For an MPA action, we need to render a HTML response. We'll handle that in app-render.\n      return {\n        type: 'not-found',\n      }\n    }\n\n    // An error that didn't come from `redirect()` or `notFound()`, likely thrown from user code\n    // (but it could also be a bug in our code!)\n\n    if (isFetchAction) {\n      // TODO: consider checking if the error is an `ApiError` and change status code\n      // so that we can respond with a 413 to requests that break the body size limit\n      // (but if we do that, we also need to make sure that whatever handles the non-fetch error path below does the same)\n      res.statusCode = 500\n      metadata.statusCode = 500\n      const promise = Promise.reject(err)\n      try {\n        // we need to await the promise to trigger the rejection early\n        // so that it's already handled by the time we call\n        // the RSC runtime. Otherwise, it will throw an unhandled\n        // promise rejection error in the renderer.\n        await promise\n      } catch {\n        // swallow error, it's gonna be handled on the client\n      }\n\n      return {\n        type: 'done',\n        result: await generateFlight(req, ctx, requestStore, {\n          actionResult: promise,\n          // If the page was not revalidated, or if the action was forwarded\n          // from another worker, we can skip rendering the page.\n          skipPageRendering:\n            workStore.pathWasRevalidated === undefined ||\n            workStore.pathWasRevalidated === ActionDidNotRevalidate ||\n            actionWasForwarded,\n          temporaryReferences,\n        }),\n      }\n    }\n\n    // For an MPA action, we need to render a HTML response. We'll rethrow the error and let it be handled above.\n    throw err\n  }\n}\n\n/**\n * Limit on the number of arguments passed to a server action. This prevents\n * stack overflow during `action.apply()` from malicious requests.\n */\nconst SERVER_ACTION_ARGS_LIMIT = 1000\n\nasync function executeActionAndPrepareForRender<\n  TFn extends (...args: any[]) => Promise<any>,\n>(\n  action: TFn,\n  args: Parameters<TFn>,\n  workStore: WorkStore,\n  requestStore: RequestStore,\n  actionWasForwarded: boolean\n): Promise<{\n  actionResult: Awaited<ReturnType<TFn>>\n  skipPageRendering: boolean\n}> {\n  requestStore.phase = 'action'\n  let skipPageRendering = actionWasForwarded\n\n  if (args.length > SERVER_ACTION_ARGS_LIMIT) {\n    throw new Error(\n      `Server Action arguments list is too long (${args.length}). Maximum allowed is ${SERVER_ACTION_ARGS_LIMIT}.`\n    )\n  }\n\n  try {\n    const actionResult = await workUnitAsyncStorage.run(requestStore, () =>\n      action.apply(null, args)\n    )\n\n    // If the page was not revalidated, or if the action was forwarded from\n    // another worker, we can skip rendering the page.\n    skipPageRendering ||=\n      workStore.pathWasRevalidated === undefined ||\n      workStore.pathWasRevalidated === ActionDidNotRevalidate\n\n    return { actionResult, skipPageRendering }\n  } finally {\n    if (!skipPageRendering) {\n      requestStore.phase = 'render'\n\n      // When we switch to the render phase, cookies() will return\n      // `workUnitStore.cookies` instead of\n      // `workUnitStore.userspaceMutableCookies`. We want the render to see any\n      // cookie writes that we performed during the action, so we need to update\n      // the immutable cookies to reflect the changes.\n      synchronizeMutableCookies(requestStore)\n\n      // The server action might have toggled draft mode, so we need to reflect\n      // that in the work store to be up-to-date for subsequent rendering.\n      workStore.isDraftMode = requestStore.draftMode.isEnabled\n\n      // If the action called revalidateTag/revalidatePath, then that might\n      // affect data used by the subsequent render, so we need to make sure all\n      // revalidations are applied before that.\n      await executeRevalidates(workStore)\n    }\n  }\n}\n\n/**\n * Attempts to find the module ID for the action from the module map. When this fails, it could be a deployment skew where\n * the action came from a different deployment. It could also simply be an invalid POST request that is not a server action.\n * In either case, we'll throw an error to be handled by the caller.\n */\nfunction getActionModIdOrError(\n  actionId: string | null,\n  serverModuleMap: ServerModuleMap\n): string | number {\n  // if we're missing the action ID header, we can't do any further processing\n  if (!actionId) {\n    throw new InvariantError(\"Missing 'next-action' header.\")\n  }\n\n  const entry = serverModuleMap[actionId]\n\n  if (entry == null) {\n    // The proxy throws for malformed IDs and IDs that are missing from the\n    // manifest. It only returns undefined when the ID collides with a\n    // well-known property name (e.g. `toString`) that the proxy excludes from\n    // server reference validation so that framework reflection probes don't\n    // throw. Next.js never produces such an ID, so this is almost certainly a\n    // probe with a known-bad ID. Repeat the manifest's throw logic here so the\n    // caller gets a diagnosable error instead of a `TypeError`.\n    throw mightBeServerReferenceId(actionId)\n      ? getActionNotFoundError(actionId)\n      : getInvalidServerReferenceIdError(actionId)\n  }\n\n  return entry.id\n}\n\nconst $ACTION_ = '$ACTION_'\nconst $ACTION_REF_ = '$ACTION_REF_'\nconst $ACTION_ID_ = '$ACTION_ID_'\n\n/**\n * This function mirrors logic inside React's decodeAction and should be kept in sync with that.\n * It pre-parses the FormData to ensure that any action IDs referred to are actual action IDs for\n * this Next.js application.\n */\nfunction areAllActionIdsValid(\n  mpaFormData: FormData,\n  serverModuleMap: ServerModuleMap\n): boolean {\n  let seenActionRefs = 0\n  let hasAtLeastOneAction = false\n  // Before we attempt to decode the payload for a possible MPA action, assert that all\n  // action IDs are valid IDs. If not we should disregard the payload\n  for (let key of mpaFormData.keys()) {\n    if (!key.startsWith($ACTION_)) {\n      // not a relevant field\n      continue\n    }\n\n    if (key.startsWith($ACTION_ID_)) {\n      // No Bound args case\n      if (isInvalidActionIdFieldName(key, serverModuleMap)) {\n        return false\n      }\n\n      hasAtLeastOneAction = true\n    } else if (key.startsWith($ACTION_REF_)) {\n      if (++seenActionRefs > 2) {\n        // We only expect to see at most 2 $ACTION_REF_ fields in the form data:\n        // one from <form action=\"...\" method=\"post\">\n        // and one from <input action=\"...\" type=\"submit\">\n        return false\n      }\n\n      // Bound args case\n      const actionDescriptorField =\n        $ACTION_ + key.slice($ACTION_REF_.length) + ':0'\n      const actionFields = mpaFormData.getAll(actionDescriptorField)\n      if (actionFields.length !== 1) {\n        return false\n      }\n      const actionField = actionFields[0]\n      if (typeof actionField !== 'string') {\n        return false\n      }\n\n      if (isInvalidStringActionDescriptor(actionField, serverModuleMap)) {\n        return false\n      }\n      hasAtLeastOneAction = true\n    }\n  }\n  return hasAtLeastOneAction\n}\n\nconst ACTION_DESCRIPTOR_ID_PREFIX = '{\"id\":\"'\nfunction isInvalidStringActionDescriptor(\n  actionDescriptor: string,\n  serverModuleMap: ServerModuleMap\n): unknown {\n  if (actionDescriptor.startsWith(ACTION_DESCRIPTOR_ID_PREFIX) === false) {\n    return true\n  }\n\n  const from = ACTION_DESCRIPTOR_ID_PREFIX.length\n  const to = actionDescriptor.indexOf('\"', from)\n  if (to === -1) {\n    return true\n  }\n\n  // We expect actionDescriptor to be '{\"id\":\"<actionId>\",...}'\n  const actionId = actionDescriptor.slice(from, to)\n  if (!mightBeServerReferenceId(actionId)) {\n    return true\n  }\n\n  const entry = serverModuleMap[actionId]\n\n  if (entry == null) {\n    return true\n  }\n\n  return false\n}\n\nfunction isInvalidActionIdFieldName(\n  actionIdFieldName: string,\n  serverModuleMap: ServerModuleMap\n): boolean {\n  // The field name must always start with $ACTION_ID_ but since it is\n  // the id is extracted from the key of the field we have already validated\n  // this before entering this function\n  const actionId = actionIdFieldName.slice($ACTION_ID_.length)\n  if (!mightBeServerReferenceId(actionId)) {\n    // this field name has too few or too many characters\n    // or it is otherwise in the wrong format\n    return true\n  }\n\n  const entry = serverModuleMap[actionId]\n\n  if (entry == null) {\n    return true\n  }\n\n  return false\n}\n"],"names":["handleAction","parseHostHeader","INLINE_ACTION_PREFIX","hasServerActions","serverActionsManifest","getServerActionsManifest","Object","keys","node","length","edge","nodeHeadersToRecord","headers","record","key","value","entries","undefined","Array","isArray","join","getForwardedHeaders","req","res","requestHeaders","requestCookies","RequestCookies","HeadersAdapter","from","responseHeaders","getHeaders","responseCookies","ResponseCookies","fromNodeOutgoingHttpHeaders","mergedHeaders","filterReqHeaders","actionsForbiddenHeaders","getAll","forEach","cookie","delete","name","set","toString","Headers","addRevalidationHeader","workStore","requestStore","isTagRevalidated","pendingRevalidatedTags","some","item","profile","isCookieRevalidated","getModifiedCookieValues","mutableCookies","setHeader","NEXT_ACTION_REVALIDATED_HEADER","JSON","stringify","ActionDidRevalidateStaticAndDynamic","pathWasRevalidated","ActionDidNotRevalidate","createForwardedActionResponse","host","workerPathname","basePath","Error","forwardedHeaders","origin","process","env","__NEXT_PRIVATE_ORIGIN","initUrl","getRequestMeta","parsedUrl","URL","error","cause","InvariantError","fetchUrl","response","body","NEXT_RUNTIME","isWebNextRequest","isNodeNextRequest","stream","fetch","method","duplex","redirect","next","internal","get","startsWith","RSC_CONTENT_TYPE_HEADER","includes","FlightRenderResult","cancel","NEXT_ACTION_NOT_FOUND_HEADER","statusCode","RenderResult","fromStatic","err","console","JSON_CONTENT_TYPE_HEADER","getAppRelativeRedirectUrl","redirectUrl","currentPathname","base","endsWith","resolved","pathname","search","hash","parsedRedirectUrl","createRedirectRenderResult","originalHost","redirectType","appRelativeRedirectUrl","RSC_HEADER","NEXT_CACHE_REVALIDATED_TAGS_HEADER","map","tag","NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER","incrementalCache","prerenderManifest","preview","previewModeId","NEXT_ROUTER_STATE_TREE_HEADER","ACTION_HEADER","cacheBustingSearchParam","computeCacheBustingSearchParam","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_URL","setCacheBustingSearchParamWithHash","EMPTY","limitUntrustedHeaderValueForLogs","slice","originDomain","forwardedHostHeader","forwardedHostHeaderValue","split","trim","hostHeader","type","ComponentMod","generateFlight","serverActions","ctx","metadata","contentType","page","renderOpts","serverModuleMap","getServerModuleMap","actionId","isMultipartAction","isFetchAction","isURLEncodedAction","isPossibleServerAction","getServerActionRequestMetadata","handleUnrecognizedFetchAction","warn","result","mightBeServerReferenceId","getInvalidServerReferenceIdError","getActionNotFoundError","isStaticGeneration","temporaryReferences","fetchCache","originHeader","originHost","warning","warnBadServerActionRequest","isCsrfOriginAllowed","allowedOrigins","promise","Promise","reject","actionResult","skipPageRendering","actionWasForwarded","Boolean","forwardedWorker","selectWorkerForForwarding","actionAsyncStorage","run","isAction","actionModId","boundActionArguments","defaultBodySizeLimit","bodySizeLimit","bodySizeLimitBytes","require","parse","createTemporaryReferenceSet","decodeReply","decodeAction","decodeFormState","edgeChunks","edgeBodySize","edgeReader","getReader","done","read","byteLength","ApiError","push","edgeBodyBlob","Blob","formData","Request","getActionModIdOrError","areAllActionIdsValid","action","executeActionAndPrepareForRender","formState","chunks","nonMultipartBodySize","reader","actionData","Buffer","concat","decodeReplyFromBusboy","PassThrough","Readable","Transform","pipeline","actionBodyFromMeta","size","sizeLimitTransform","transform","chunk","encoding","callback","busboy","defParamCharset","limits","fieldSize","abortController","AbortController","all","signal","abort","sizeLimitedBody","fakeRequest","toWeb","actionMod","__next_app__","actionHandler","logInfo","actionType","extractInfoFromServerReferenceId","NODE_ENV","logServerFunctions","runtime","actionInfo","isInlineAction","exportedName","projectDir","dir","cwd","location","normalizeFilePath","filename","functionName","args","startTime","performance","now","finally","duration","Math","round","addRequestMeta","maybeRevalidatesPromise","executeRevalidates","exit","resolve","waitUntil","isRedirectError","getURLFromRedirectError","getRedirectTypeFromError","url","RedirectStatusCode","SeeOther","isHTTPAccessFallbackError","getAccessFallbackHTTPStatus","SERVER_ACTION_ARGS_LIMIT","phase","workUnitAsyncStorage","apply","synchronizeMutableCookies","isDraftMode","draftMode","isEnabled","entry","id","$ACTION_","$ACTION_REF_","$ACTION_ID_","mpaFormData","seenActionRefs","hasAtLeastOneAction","isInvalidActionIdFieldName","actionDescriptorField","actionFields","actionField","isInvalidStringActionDescriptor","ACTION_DESCRIPTOR_ID_PREFIX","actionDescriptor","to","indexOf","actionIdFieldName"],"mappings":";;;;;;;;;;;;;;;IAsjBsBA,YAAY;eAAZA;;IAxDNC,eAAe;eAAfA;;;kCA7eT;oCAIA;0BAIA;+BAIA;qEAGA;4CAE4B;oCACA;uBAI5B;gCACiC;2BAMjC;yCACwC;gCACX;qBACf;yBA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