{"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'\nimport type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\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} 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 { 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 { selectWorkerForForwarding } from './action-utils'\nimport { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers'\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 { getRequestMeta } from '../request-meta'\nimport { setCacheBustingSearchParam } from '../../client/components/router-reducer/set-cache-busting-search-param'\n\n/**\n * Checks if the app has any server actions defined in any runtime.\n */\nfunction hasServerActions(manifest: ActionManifest) {\n  return (\n    Object.keys(manifest.node).length > 0 ||\n    Object.keys(manifest.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  // To keep the header size small, we use a tuple of\n  // [[revalidatedPaths], isTagRevalidated ? 1 : 0, isCookieRevalidated ? 1 : 0]\n  // instead of a JSON object.\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  const isTagRevalidated = workStore.pendingRevalidatedTags?.length ? 1 : 0\n  const isCookieRevalidated = getModifiedCookieValues(\n    requestStore.mutableCookies\n  ).length\n    ? 1\n    : 0\n\n  res.setHeader(\n    'x-action-revalidated',\n    JSON.stringify([[], isTagRevalidated, isCookieRevalidated])\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  const proto =\n    getRequestMeta(req, 'initProtocol')?.replace(/:+$/, '') || 'https'\n\n  // For standalone or the serverful mode, use the internal origin directly\n  // other than the host headers from the request.\n  const origin = process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${host.value}`\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    } 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 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): URL | null {\n  if (redirectUrl.startsWith('/') || redirectUrl.startsWith('.')) {\n    // Make sure we are appending the basePath to relative URLS\n    return new URL(`${basePath}${redirectUrl}`, 'http://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) {\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  )\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    const proto =\n      getRequestMeta(req, 'initProtocol')?.replace(/:+$/, '') || 'https'\n\n    // For standalone or the serverful mode, use the internal origin directly\n    // other than the host headers from the request.\n    const origin =\n      process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${originalHost.value}`\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.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      setCacheBustingSearchParam(fetchUrl, {\n        [NEXT_ROUTER_PREFETCH_HEADER]: forwardedHeaders.get(\n          NEXT_ROUTER_PREFETCH_HEADER\n        )\n          ? ('1' as const)\n          : undefined,\n        [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]:\n          forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ??\n          undefined,\n        [NEXT_ROUTER_STATE_TREE_HEADER]:\n          forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,\n        [NEXT_URL]: forwardedHeaders.get(NEXT_URL) ?? undefined,\n      })\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 ServerModuleMap = Record<\n  string,\n  {\n    id: string\n    chunks: string[]\n    name: string\n  }\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  serverModuleMap,\n  generateFlight,\n  workStore,\n  requestStore,\n  serverActions,\n  ctx,\n  metadata,\n}: {\n  req: BaseNextRequest\n  res: BaseNextResponse\n  ComponentMod: AppPageModule\n  serverModuleMap: ServerModuleMap\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 { serverActionsManifest, page } = ctx.renderOpts\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(serverActionsManifest)) {\n    return handleUnrecognizedFetchAction(getActionNotFoundError(actionId))\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 originDomain =\n    typeof req.headers['origin'] === 'string'\n      ? new URL(req.headers['origin']).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 (!originDomain) {\n    // This might be an old browser that doesn't send `host` header. We ignore\n    // this case.\n    warning = 'Missing `origin` header from a forwarded Server Actions request.'\n  } else if (!host || originDomain !== 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(originDomain, 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            originDomain\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 occurred. We can skip rendering the page.\n            skipFlight: 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 { actionAsyncStorage } = ComponentMod\n\n  const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])\n\n  if (actionId) {\n    const forwardedWorker = selectWorkerForForwarding(\n      actionId,\n      page,\n      serverActionsManifest\n    )\n\n    // If forwardedWorker is truthy, it means there isn't a worker for the action\n    // in the current handler, so we forward the request to a worker that 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 | undefined\n        let boundActionArguments: unknown[] = []\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          // TODO: add body limit\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            const formData = await req.request.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(\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 actionReturnedState =\n                  await executeActionAndPrepareForRender(\n                    action as () => Promise<unknown>,\n                    [],\n                    workStore,\n                    requestStore\n                  )\n\n                const formState = await decodeFormState(\n                  actionReturnedState,\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            const reader = req.body.getReader()\n            while (true) {\n              const { done, value } = await reader.read()\n              if (done) {\n                break\n              }\n\n              chunks.push(value)\n            }\n\n            const actionData = Buffer.concat(chunks).toString('utf-8')\n\n            boundActionArguments = await decodeReply(\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 { Transform, pipeline } =\n            require('node:stream') as typeof import('node:stream')\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          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          const sizeLimitedBody = pipeline(\n            req.body,\n            sizeLimitTransform,\n            // Avoid unhandled errors from `pipeline()` by passing an empty completion callback.\n            // We'll propagate the errors properly when consuming the stream.\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              // We need to use `pipeline(one, two)` instead of `one.pipe(two)` to propagate size limit errors correctly.\n              pipeline(\n                sizeLimitedBody,\n                busboy,\n                // Avoid unhandled errors from `pipeline()` by passing an empty completion callback.\n                // We'll propagate the errors properly when consuming the stream.\n                () => {}\n              )\n\n              boundActionArguments = await decodeReplyFromBusboy(\n                busboy,\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\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: new ReadableStream({\n                  start: (controller) => {\n                    sizeLimitedBody.on('data', (chunk) => {\n                      controller.enqueue(new Uint8Array(chunk))\n                    })\n                    sizeLimitedBody.on('end', () => {\n                      controller.close()\n                    })\n                    sizeLimitedBody.on('error', (err) => {\n                      controller.error(err)\n                    })\n                  },\n                }),\n                duplex: 'half',\n              })\n\n              const formData = await fakeRequest.formData()\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 actionReturnedState =\n                  await executeActionAndPrepareForRender(\n                    action as () => Promise<unknown>,\n                    [],\n                    workStore,\n                    requestStore\n                  )\n\n                const formState = await decodeFormState(\n                  actionReturnedState,\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            for await (const chunk of sizeLimitedBody) {\n              chunks.push(Buffer.from(chunk))\n            }\n\n            const actionData = Buffer.concat(chunks).toString('utf-8')\n\n            boundActionArguments = await decodeReply(\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        const returnVal = await executeActionAndPrepareForRender(\n          actionHandler,\n          boundActionArguments,\n          workStore,\n          requestStore\n        ).finally(() => {\n          addRevalidationHeader(res, { workStore, requestStore })\n        })\n\n        // For form actions, we need to continue rendering the page.\n        if (isFetchAction) {\n          const actionResult = await generateFlight(req, ctx, requestStore, {\n            actionResult: Promise.resolve(returnVal),\n            // if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree\n            skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,\n            temporaryReferences,\n          })\n\n          return {\n            type: 'done',\n            result: actionResult,\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 it's a fetch action, we'll set the status code for logging/debugging purposes\n      // but we won't set a Location header, as the redirect will be handled by the client router\n      res.statusCode = RedirectStatusCode.SeeOther\n      metadata.statusCode = RedirectStatusCode.SeeOther\n\n      if (isFetchAction) {\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          ),\n        }\n      }\n\n      // For an MPA action, the redirect doesn't need a body, just a Location header.\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            skipFlight: 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 from another worker, we can skip the rendering the flight tree\n          skipFlight: !workStore.pathWasRevalidated || 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\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): Promise<Awaited<ReturnType<TFn>>> {\n  requestStore.phase = 'action'\n  try {\n    return await workUnitAsyncStorage.run(requestStore, () =>\n      action.apply(null, args)\n    )\n  } finally {\n    requestStore.phase = 'render'\n\n    // When we switch to the render phase, cookies() will return\n    // `workUnitStore.cookies` instead of `workUnitStore.userspaceMutableCookies`.\n    // We want the render to see any cookie writes that we performed during the action,\n    // so we need to update 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 affect data used by the subsequent render,\n    // so we need to make sure all revalidations are applied before that\n    await executeRevalidates(workStore)\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 {\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 actionModId = serverModuleMap[actionId]?.id\n\n  if (!actionModId) {\n    throw getActionNotFoundError(actionId)\n  }\n\n  return actionModId\n}\n\nfunction getActionNotFoundError(actionId: string | null): Error {\n  return new Error(\n    `Failed to find Server Action${actionId ? ` \"${actionId}\"` : ''}. 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\nconst $ACTION_ = '$ACTION_'\nconst $ACTION_REF_ = '$ACTION_REF_'\nconst $ACTION_ID_ = '$ACTION_ID_'\nconst ACTION_ID_EXPECTED_LENGTH = 42\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 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      // 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 = from + ACTION_ID_EXPECTED_LENGTH\n\n  // We expect actionDescriptor to be '{\"id\":\"<actionId>\",...}'\n  const actionId = actionDescriptor.slice(from, to)\n  if (\n    actionId.length !== ACTION_ID_EXPECTED_LENGTH ||\n    actionDescriptor[to] !== '\"'\n  ) {\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  if (\n    actionIdFieldName.length !==\n    $ACTION_ID_.length + ACTION_ID_EXPECTED_LENGTH\n  ) {\n    // this field name has too few or too many characters\n    return true\n  }\n\n  const actionId = actionIdFieldName.slice($ACTION_ID_.length)\n  const entry = serverModuleMap[actionId]\n\n  if (entry == null) {\n    return true\n  }\n\n  return false\n}\n"],"names":["handleAction","parseHostHeader","hasServerActions","manifest","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","isCookieRevalidated","getModifiedCookieValues","mutableCookies","setHeader","JSON","stringify","createForwardedActionResponse","host","workerPathname","basePath","getRequestMeta","Error","forwardedHeaders","proto","replace","origin","process","env","__NEXT_PRIVATE_ORIGIN","fetchUrl","URL","response","body","NEXT_RUNTIME","isWebNextRequest","isNodeNextRequest","stream","fetch","method","duplex","redirect","next","internal","get","startsWith","RSC_CONTENT_TYPE_HEADER","includes","FlightRenderResult","cancel","err","console","error","RenderResult","fromStatic","JSON_CONTENT_TYPE_HEADER","getAppRelativeRedirectUrl","redirectUrl","parsedRedirectUrl","pathname","createRedirectRenderResult","originalHost","redirectType","appRelativeRedirectUrl","RSC_HEADER","search","NEXT_CACHE_REVALIDATED_TAGS_HEADER","NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER","incrementalCache","prerenderManifest","preview","previewModeId","NEXT_ROUTER_STATE_TREE_HEADER","ACTION_HEADER","setCacheBustingSearchParam","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_URL","EMPTY","limitUntrustedHeaderValueForLogs","slice","originDomain","forwardedHostHeader","forwardedHostHeaderValue","split","trim","hostHeader","type","ComponentMod","serverModuleMap","generateFlight","serverActions","ctx","metadata","contentType","serverActionsManifest","page","renderOpts","actionId","isMultipartAction","isFetchAction","isURLEncodedAction","isPossibleServerAction","getServerActionRequestMetadata","handleUnrecognizedFetchAction","warn","NEXT_ACTION_NOT_FOUND_HEADER","statusCode","result","getActionNotFoundError","isStaticGeneration","temporaryReferences","fetchCache","warning","warnBadServerActionRequest","isCsrfOriginAllowed","allowedOrigins","promise","Promise","reject","actionResult","skipFlight","actionAsyncStorage","actionWasForwarded","Boolean","forwardedWorker","selectWorkerForForwarding","run","isAction","actionModId","boundActionArguments","createTemporaryReferenceSet","decodeReply","decodeAction","decodeFormState","formData","request","getActionModIdOrError","areAllActionIdsValid","action","actionReturnedState","executeActionAndPrepareForRender","formState","chunks","reader","getReader","done","read","push","actionData","Buffer","concat","decodeReplyFromBusboy","require","Transform","pipeline","defaultBodySizeLimit","bodySizeLimit","bodySizeLimitBytes","parse","size","sizeLimitTransform","transform","chunk","encoding","callback","byteLength","ApiError","sizeLimitedBody","busboy","defParamCharset","limits","fieldSize","fakeRequest","Request","ReadableStream","start","controller","on","enqueue","Uint8Array","close","actionMod","__next_app__","actionHandler","returnVal","finally","resolve","pathWasRevalidated","isRedirectError","getURLFromRedirectError","getRedirectTypeFromError","RedirectStatusCode","SeeOther","isHTTPAccessFallbackError","getAccessFallbackHTTPStatus","args","phase","workUnitAsyncStorage","apply","synchronizeMutableCookies","isDraftMode","draftMode","isEnabled","executeRevalidates","InvariantError","id","$ACTION_","$ACTION_REF_","$ACTION_ID_","ACTION_ID_EXPECTED_LENGTH","mpaFormData","hasAtLeastOneAction","isInvalidActionIdFieldName","actionDescriptorField","actionFields","actionField","isInvalidStringActionDescriptor","ACTION_DESCRIPTOR_ID_PREFIX","actionDescriptor","to","entry","actionIdFieldName"],"mappings":";;;;;;;;;;;;;;;IAqesBA,YAAY;eAAZA;;IAjENC,eAAe;eAAfA;;;kCAnZT;oCAIA;0BAIA;+BAIA;qEAGA;oCAE4B;uBAI5B;gCACiC;2BAMjC;yCACwC;gCACX;qBACf;yBAC2B;yBACjB;wBACa;6BACF;yBACU;oCACjB;8BACO;8CAEL;gCACN;mCACI;6BACJ;4CACY;;;;;;AAE3C;;CAEC,GACD,SAASC,iBAAiBC,QAAwB;IAChD,OACEC,OAAOC,IAAI,CAACF,SAASG,IAAI,EAAEC,MAAM,GAAG,KACpCH,OAAOC,IAAI,CAACF,SAASK,IAAI,EAAED,MAAM,GAAG;AAExC;AAEA,SAASE,oBACPC,OAAkD;IAElD,MAAMC,SAAiC,CAAC;IACxC,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIT,OAAOU,OAAO,CAACJ,SAAU;QAClD,IAAIG,UAAUE,WAAW;YACvBJ,MAAM,CAACC,IAAI,GAAGI,MAAMC,OAAO,CAACJ,SAASA,MAAMK,IAAI,CAAC,QAAQ,GAAGL,OAAO;QACpE;IACF;IACA,OAAOF;AACT;AAEA,SAASQ,oBACPC,GAAoB,EACpBC,GAAqB;IAErB,kCAAkC;IAClC,MAAMC,iBAAiBF,IAAIV,OAAO;IAClC,MAAMa,iBAAiB,IAAIC,uBAAc,CAACC,uBAAc,CAACC,IAAI,CAACJ;IAE9D,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