MCPcopy Create free account
hub / github.com/TanStack/router / executeMiddleware

Function executeMiddleware

packages/start-server-core/src/createStartHandler.ts:308–489  ·  view source on GitHub ↗

* Compose middleware around a terminal response handler. With no middleware * the terminal runs directly.

(
  middlewares: Array<TODO>,
  terminal: TODO,
  ctx: PipelineContext,
  signal: AbortSignal,
  terminalNext?: TODO,
)

Source from the content-addressed store, hash-verified

306 * the terminal runs directly.
307 */
308async function executeMiddleware(
309 middlewares: Array<TODO>,
310 terminal: TODO,
311 ctx: PipelineContext,
312 signal: AbortSignal,
313 terminalNext?: TODO,
314): Promise<HandlerCallbackResult> {
315 let index = -1
316 let responseOwnership: MiddlewareResponseOwnership | undefined
317 // Once the pipeline returned, the HTTP runtime owns the response. A result
318 // that settles later (for example the loser of a `Promise.race`) must not
319 // replace or cancel it.
320 let settled = false
321 const disposeAbandonedResult = createLateResponseDisposer(signal)
322
323 const setResponse = (response: TODO) => {
324 const ssrResponse = isSsrResponse(response) ? response : undefined
325 const streamResponse =
326 ssrResponse?.serverSsrCleanup === 'stream' ? ssrResponse : undefined
327 const exposed: Response | undefined = ssrResponse
328 ? ssrResponse.response
329 : response
330 const current = responseOwnership
331
332 if (settled) {
333 if (exposed !== ctx.response) {
334 disposeResponseResult(response, 'late middleware response')
335 }
336 return
337 }
338 if (current && current.response === exposed) {
339 current.streamResponse ??= streamResponse
340 } else if (current && inheritsResponseOwnership(current, exposed)) {
341 current.response = exposed
342 current.streamResponse ??= streamResponse
343 } else {
344 if (current) {
345 disposeResponseOwnership(current, 'middleware response replaced')
346 }
347 if (hasResponseBody(exposed)) {
348 responseOwnership = {
349 response: exposed,
350 sourceBody: exposed.body,
351 streamResponse,
352 }
353 } else {
354 responseOwnership = undefined
355 }
356 }
357 ctx.response = exposed
358 }
359
360 const reconcileCtxResponse = () => {
361 if (ctx.response !== responseOwnership?.response) {
362 setResponse(ctx.response)
363 }
364 }
365

Callers 2

startRequestResolverFunction · 0.70
handleServerRoutesFunction · 0.70

Calls 6

runNextFunction · 0.85
throwRouteHandlerErrorFunction · 0.85
reconcileCtxResponseFunction · 0.85
getOwnedResponseFunction · 0.85
disposeResponseOwnershipFunction · 0.85

Tested by

no test coverage detected