{"version":3,"file":"middleware.mjs","names":[],"sources":["../../../src/nitro-v3/middleware.ts"],"sourcesContent":["import type { RequestLogger } from '../types'\nimport { MxllogError } from '../error'\nimport { serializeMxllogErrorResponse } from '../nitro'\n\n/**\n * Server middleware handler that catches MxllogError and returns a structured JSON response.\n *\n * Frameworks like TanStack Start catch thrown errors before Nitro's error handler,\n * stripping the `data` field (containing `why`, `fix`, `link`). This middleware\n * intercepts MxllogErrors first, attaches them to the wide event, and throws a\n * `Response` that the framework passes through directly.\n *\n * @example TanStack Start\n * ```ts\n * import { createMiddleware } from '@tanstack/react-start'\n * import { mxllogErrorHandler } from '@safaricom-mxl/log/nitro/v3'\n *\n * const mxllogMiddleware = createMiddleware().server(mxllogErrorHandler)\n *\n * export const Route = createRootRoute({\n *   server: { middleware: [mxllogMiddleware] },\n * })\n * ```\n */\n\nexport async function mxllogErrorHandler<T>(next: (...args: any[]) => Promise<T>): Promise<T> {\n  try {\n    return await next()\n  } catch (error: unknown) {\n    if (error instanceof MxllogError || (error && typeof error === 'object' && (error as Error).name === 'MxllogError')) {\n      const mxllogError = error as MxllogError\n\n      try {\n        const { useRequest } = await import('nitro/context')\n        const req = useRequest()\n        const log = req.context?.log as RequestLogger | undefined\n        log?.error(mxllogError)\n      } catch {\n        // ignore\n      }\n\n      // Throw as Response so frameworks (TanStack Start, SolidStart, etc.) pass it through\n      throw new Response(JSON.stringify(mxllogError.toJSON()), {\n        status: mxllogError.status || 500,\n        headers: { 'Content-Type': 'application/json' },\n      })\n    }\n    throw error\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyBA,eAAsB,mBAAsB,MAAkD;AAC5F,KAAI;AACF,SAAO,MAAM,MAAM;UACZ,OAAgB;AACvB,MAAI,iBAAiB,eAAgB,SAAS,OAAO,UAAU,YAAa,MAAgB,SAAS,eAAgB;GACnH,MAAM,cAAc;AAEpB,OAAI;IACF,MAAM,EAAE,eAAe,MAAM,OAAO;AAGpC,KAFY,YAAY,CACR,SAAS,MACpB,MAAM,YAAY;WACjB;AAKR,SAAM,IAAI,SAAS,KAAK,UAAU,YAAY,QAAQ,CAAC,EAAE;IACvD,QAAQ,YAAY,UAAU;IAC9B,SAAS,EAAE,gBAAgB,oBAAoB;IAChD,CAAC;;AAEJ,QAAM"}