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72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import type {
  ActionFlightResponse,
  ActionResult,
} from '../../../../server/app-render/types'
import { callServer } from '../../../app-call-server'
import { findSourceMapURL } from '../../../app-find-source-map-url'
import {
  ACTION_HEADER,
  NEXT_ACTION_NOT_FOUND_HEADER,
  NEXT_IS_PRERENDER_HEADER,
  NEXT_ROUTER_STATE_TREE_HEADER,
  NEXT_URL,
  RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers'

// TODO: Explicitly import from client.browser
// eslint-disable-next-line import/no-extraneous-dependencies
import {
  createFromFetch as createFromFetchBrowser,
  createTemporaryReferenceSet,
  encodeReply,
} from 'react-server-dom-webpack/client'

import {
  PrefetchKind,
  type ReadonlyReducerState,
  type ReducerState,
  type ServerActionAction,
  type ServerActionMutable,
} from '../router-reducer-types'
import { assignLocation } from '../../../assign-location'
import { createHrefFromUrl } from '../create-href-from-url'
import { handleExternalUrl } from './navigate-reducer'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime'
import { handleMutable } from '../handle-mutable'
import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'
import { createEmptyCacheNode } from '../../app-router'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { handleSegmentMismatch } from '../handle-segment-mismatch'
import { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments'
import {
  normalizeFlightData,
  prepareFlightRouterStateForRequest,
  type NormalizedFlightData,
} from '../../../flight-data-helpers'
import { getRedirectError } from '../../redirect'
import { RedirectType } from '../../redirect-error'
import { createSeededPrefetchCacheEntry } from '../prefetch-cache-utils'
import { removeBasePath } from '../../../remove-base-path'
import { hasBasePath } from '../../../has-base-path'
import {
  extractInfoFromServerReferenceId,
  omitUnusedArgs,
} from '../../../../shared/lib/server-reference-info'
import { revalidateEntireCache } from '../../segment-cache'

const createFromFetch =
  createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']

type FetchServerActionResult = {
  redirectLocation: URL | undefined
  redirectType: RedirectType | undefined
  actionResult: ActionResult | undefined
  actionFlightData: NormalizedFlightData[] | string | undefined
  isPrerender: boolean
  revalidatedParts: {
    tag: boolean
    cookie: boolean
    paths: string[]
  }
}

async function fetchServerAction(
  state: ReadonlyReducerState,
  nextUrl: ReadonlyReducerState['nextUrl'],
  { actionId, actionArgs }: ServerActionAction
): Promise<FetchServerActionResult> {
  const temporaryReferences = createTemporaryReferenceSet()
  const info = extractInfoFromServerReferenceId(actionId)

  // TODO: Currently, we're only omitting unused args for the experimental "use
  // cache" functions. Once the server reference info byte feature is stable, we
  // should apply this to server actions as well.
  const usedArgs =
    info.type === 'use-cache' ? omitUnusedArgs(actionArgs, info) : actionArgs

  const body = await encodeReply(usedArgs, { temporaryReferences })

  const res = await fetch(state.canonicalUrl, {
    method: 'POST',
    headers: {
      Accept: RSC_CONTENT_TYPE_HEADER,
      [ACTION_HEADER]: actionId,
      [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(
        state.tree
      ),
      ...(process.env.NEXT_DEPLOYMENT_ID
        ? {
            'x-deployment-id': process.env.NEXT_DEPLOYMENT_ID,
          }
        : {}),
      ...(nextUrl
        ? {
            [NEXT_URL]: nextUrl,
          }
        : {}),
    },
    body,
  })

  // Handle server actions that the server didn't recognize.
  const unrecognizedActionHeader = res.headers.get(NEXT_ACTION_NOT_FOUND_HEADER)
  if (unrecognizedActionHeader === '1') {
    throw new Error(
      `Server Action "${actionId}" was not found on the server. \nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
    )
  }

  const redirectHeader = res.headers.get('x-action-redirect')
  const [location, _redirectType] = redirectHeader?.split(';') || []
  let redirectType: RedirectType | undefined
  switch (_redirectType) {
    case 'push':
      redirectType = RedirectType.push
      break
    case 'replace':
      redirectType = RedirectType.replace
      break
    default:
      redirectType = undefined
  }

  const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)
  let revalidatedParts: FetchServerActionResult['revalidatedParts']
  try {
    const revalidatedHeader = JSON.parse(
      res.headers.get('x-action-revalidated') || '[[],0,0]'
    )
    revalidatedParts = {
      paths: revalidatedHeader[0] || [],
      tag: !!revalidatedHeader[1],
      cookie: revalidatedHeader[2],
    }
  } catch (e) {
    revalidatedParts = NO_REVALIDATED_PARTS
  }

  const redirectLocation = location
    ? assignLocation(
        location,
        new URL(state.canonicalUrl, window.location.href)
      )
    : undefined

  const contentType = res.headers.get('content-type')
  const isRscResponse = !!(
    contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)
  )

  // Handle invalid server action responses.
  // A valid response must have `content-type: text/x-component`, unless it's an external redirect.
  // (external redirects have an 'x-action-redirect' header, but the body is an empty 'text/plain')
  if (!isRscResponse && !redirectLocation) {
    // The server can respond with a text/plain error message, but we'll fallback to something generic
    // if there isn't one.
    const message =
      res.status >= 400 && contentType === 'text/plain'
        ? await res.text()
        : 'An unexpected response was received from the server.'

    throw new Error(message)
  }

  let actionResult: FetchServerActionResult['actionResult']
  let actionFlightData: FetchServerActionResult['actionFlightData']
  if (isRscResponse) {
    const response: ActionFlightResponse = await createFromFetch(
      Promise.resolve(res),
      { callServer, findSourceMapURL, temporaryReferences }
    )
    // An internal redirect can send an RSC response, but does not have a useful `actionResult`.
    actionResult = redirectLocation ? undefined : response.a
    actionFlightData = normalizeFlightData(response.f)
  } else {
    // An external redirect doesn't contain RSC data.
    actionResult = undefined
    actionFlightData = undefined
  }

  return {
    actionResult,
    actionFlightData,
    redirectLocation,
    redirectType,
    revalidatedParts,
    isPrerender,
  }
}

const NO_REVALIDATED_PARTS = {
  paths: [],
  tag: false,
  cookie: false,
}

/*
 * This reducer is responsible for calling the server action and processing any side-effects from the server action.
 * It does not mutate the state by itself but rather delegates to other reducers to do the actual mutation.
 */
export function serverActionReducer(
  state: ReadonlyReducerState,
  action: ServerActionAction
): ReducerState {
  const { resolve, reject } = action
  const mutable: ServerActionMutable = {}

  let currentTree = state.tree

  mutable.preserveCustomHistoryState = false

  // only pass along the `nextUrl` param (used for interception routes) if the current route was intercepted.
  // If the route has been intercepted, the action should be as well.
  // Otherwise the server action might be intercepted with the wrong action id
  // (ie, one that corresponds with the intercepted route)
  const nextUrl =
    state.nextUrl && hasInterceptionRouteInCurrentTree(state.tree)
      ? state.nextUrl
      : null

  const navigatedAt = Date.now()

  return fetchServerAction(state, nextUrl, action).then(
    async ({
      actionResult,
      actionFlightData: flightData,
      redirectLocation,
      redirectType,
      isPrerender,
      revalidatedParts,
    }) => {
      let redirectHref: string | undefined

      // honor the redirect type instead of defaulting to push in case of server actions.
      if (redirectLocation) {
        if (redirectType === RedirectType.replace) {
          state.pushRef.pendingPush = false
          mutable.pendingPush = false
        } else {
          state.pushRef.pendingPush = true
          mutable.pendingPush = true
        }

        redirectHref = createHrefFromUrl(redirectLocation, false)
        mutable.canonicalUrl = redirectHref
      }

      if (!flightData) {
        resolve(actionResult)

        // If there is a redirect but no flight data we need to do a mpaNavigation.
        if (redirectLocation) {
          return handleExternalUrl(
            state,
            mutable,
            redirectLocation.href,
            state.pushRef.pendingPush
          )
        }
        return state
      }

      if (typeof flightData === 'string') {
        // Handle case when navigating to page in `pages` from `app`
        resolve(actionResult)

        return handleExternalUrl(
          state,
          mutable,
          flightData,
          state.pushRef.pendingPush
        )
      }

      const actionRevalidated =
        revalidatedParts.paths.length > 0 ||
        revalidatedParts.tag ||
        revalidatedParts.cookie

      for (const normalizedFlightData of flightData) {
        const {
          tree: treePatch,
          seedData: cacheNodeSeedData,
          head,
          isRootRender,
        } = normalizedFlightData

        if (!isRootRender) {
          // TODO-APP: handle this case better
          console.log('SERVER ACTION APPLY FAILED')
          resolve(actionResult)

          return state
        }

        // Given the path can only have two items the items are only the router state and rsc for the root.
        const newTree = applyRouterStatePatchToTree(
          // TODO-APP: remove ''
          [''],
          currentTree,
          treePatch,
          redirectHref ? redirectHref : state.canonicalUrl
        )

        if (newTree === null) {
          resolve(actionResult)

          return handleSegmentMismatch(state, action, treePatch)
        }

        if (isNavigatingToNewRootLayout(currentTree, newTree)) {
          resolve(actionResult)

          return handleExternalUrl(
            state,
            mutable,
            redirectHref || state.canonicalUrl,
            state.pushRef.pendingPush
          )
        }

        // The server sent back RSC data for the server action, so we need to apply it to the cache.
        if (cacheNodeSeedData !== null) {
          const rsc = cacheNodeSeedData[1]
          const cache: CacheNode = createEmptyCacheNode()
          cache.rsc = rsc
          cache.prefetchRsc = null
          cache.loading = cacheNodeSeedData[3]
          fillLazyItemsTillLeafWithHead(
            navigatedAt,
            cache,
            // Existing cache is not passed in as server actions have to invalidate the entire cache.
            undefined,
            treePatch,
            cacheNodeSeedData,
            head,
            undefined
          )

          mutable.cache = cache
          if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {
            revalidateEntireCache(state.nextUrl, newTree)
          } else {
            mutable.prefetchCache = new Map()
          }
          if (actionRevalidated) {
            await refreshInactiveParallelSegments({
              navigatedAt,
              state,
              updatedTree: newTree,
              updatedCache: cache,
              includeNextUrl: Boolean(nextUrl),
              canonicalUrl: mutable.canonicalUrl || state.canonicalUrl,
            })
          }
        }

        mutable.patchedTree = newTree
        currentTree = newTree
      }

      if (redirectLocation && redirectHref) {
        if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE && !actionRevalidated) {
          // Because the RedirectBoundary will trigger a navigation, we need to seed the prefetch cache
          // with the FlightData that we got from the server action for the target page, so that it's
          // available when the page is navigated to and doesn't need to be re-fetched.
          // We only do this if the server action didn't revalidate any data, as in that case the
          // client cache will be cleared and the data will be re-fetched anyway.
          // NOTE: We don't do this in the Segment Cache implementation.
          // Dynamic data should never be placed into the cache, unless it's
          // "converted" to static data using <Link prefetch={true}>. What we
          // do instead is re-prefetch links and forms whenever the cache is
          // invalidated.
          createSeededPrefetchCacheEntry({
            url: redirectLocation,
            data: {
              flightData,
              canonicalUrl: undefined,
              couldBeIntercepted: false,
              prerendered: false,
              postponed: false,
              // TODO: We should be able to set this if the server action
              // returned a fully static response.
              staleTime: -1,
            },
            tree: state.tree,
            prefetchCache: state.prefetchCache,
            nextUrl: state.nextUrl,
            kind: isPrerender ? PrefetchKind.FULL : PrefetchKind.AUTO,
          })
          mutable.prefetchCache = state.prefetchCache
        }

        // If the action triggered a redirect, the action promise will be rejected with
        // a redirect so that it's handled by RedirectBoundary as we won't have a valid
        // action result to resolve the promise with. This will effectively reset the state of
        // the component that called the action as the error boundary will remount the tree.
        // The status code doesn't matter here as the action handler will have already sent
        // a response with the correct status code.
        reject(
          getRedirectError(
            hasBasePath(redirectHref)
              ? removeBasePath(redirectHref)
              : redirectHref,
            redirectType || RedirectType.push
          )
        )
      } else {
        resolve(actionResult)
      }

      return handleMutable(state, mutable)
    },
    (e: any) => {
      // When the server action is rejected we don't update the state and instead call the reject handler of the promise.
      reject(e)

      return state
    }
  )
}