{"version":3,"sources":["../src/core/error-handler.ts","../src/core/errors.ts","../src/core/logger.ts","../src/next/errors/redirect.ts","../src/next/errors/http-access-fallback.ts","../src/next/errors/framework.ts","../src/next/errors/index.ts","../src/core/redirect.ts","../src/core/redact.ts","../src/core/form-data.ts","../src/core/pipeline.ts","../src/core/server-action-client.ts","../src/core/schema-helpers.ts","../src/core/middleware-helpers.ts"],"sourcesContent":["import { $ZodError } from \"zod/v4/core\";\r\nimport type {\r\n  ActionLogger,\r\n  AuthRedirectOptions,\r\n  ServerActionError,\r\n  ServerActionResponse,\r\n} from \"../types\";\r\nimport { InvalidFormDataError, OutputValidationError } from \"./errors\";\r\nimport { consoleLogger, describeAction } from \"./logger\";\r\nimport { rethrowIfNextInternal } from \"../next/errors\";\r\n\r\nconst GENERIC_MESSAGE = \"An unexpected error occurred\";\r\n\r\ntype CustomErrorHandler = (error: unknown) => ServerActionError | undefined;\r\n\r\nexport type ResolvedAuthRedirect = { codes: readonly string[]; to: string } | false;\r\n\r\nconst DEFAULT_AUTH_REDIRECT_CODES: readonly string[] = [\"AUTHENTICATION_ERROR\"];\r\n\r\nexport const DEFAULT_AUTH_REDIRECT: ResolvedAuthRedirect = {\r\n  codes: DEFAULT_AUTH_REDIRECT_CODES,\r\n  to: \"/login\",\r\n};\r\n\r\nexport function resolveAuthRedirect(\r\n  option: AuthRedirectOptions | false | undefined,\r\n): ResolvedAuthRedirect {\r\n  if (option === false) return false;\r\n  if (option === undefined) return DEFAULT_AUTH_REDIRECT;\r\n  return { codes: option.codes ?? DEFAULT_AUTH_REDIRECT_CODES, to: option.to };\r\n}\r\n\r\n/**\r\n * Add the sign-in redirect to a matching error. Returns a copy: the object\r\n * produced by `toServerActionError()` may be shared and must stay untouched.\r\n */\r\nfunction applyAuthRedirect(\r\n  serverError: ServerActionError,\r\n  errorType: unknown,\r\n  authRedirect: ResolvedAuthRedirect,\r\n): ServerActionError {\r\n  if (!authRedirect || serverError.shouldRedirect === false) {\r\n    return serverError;\r\n  }\r\n  const matches =\r\n    (serverError.code !== undefined && authRedirect.codes.includes(serverError.code)) ||\r\n    (typeof errorType === \"string\" && authRedirect.codes.includes(errorType));\r\n  if (!matches) {\r\n    return serverError;\r\n  }\r\n  return {\r\n    ...serverError,\r\n    shouldRedirect: true,\r\n    redirectTo: serverError.redirectTo ?? authRedirect.to,\r\n  };\r\n}\r\n\r\n/**\r\n * Where an error surfaced. Only a `ZodError` produced by input validation is\r\n * user-facing; any other `ZodError` comes from server code parsing internal\r\n * data and must not reveal its field names.\r\n */\r\nexport type ErrorPhase = \"input\" | \"execution\";\r\n\r\n/**\r\n * Whether error details may be shown to the client. Fails closed: only an\r\n * explicit development environment reveals them, so a missing or unexpected\r\n * `NODE_ENV` (unset, \"test\", \"staging\") never leaks internal messages.\r\n */\r\nfunction revealsDetails(): boolean {\r\n  return process.env.NODE_ENV === \"development\";\r\n}\r\n\r\n/** Any thrown value exposing `toServerActionError()`, not only `Error` subclasses. */\r\nfunction hasServerActionErrorConverter(\r\n  error: unknown,\r\n): error is { toServerActionError: () => unknown; type?: unknown } {\r\n  return (\r\n    typeof error === \"object\" &&\r\n    error !== null &&\r\n    typeof (error as { toServerActionError?: unknown }).toServerActionError === \"function\"\r\n  );\r\n}\r\n\r\nexport function isServerActionError(value: unknown): value is ServerActionError {\r\n  return (\r\n    typeof value === \"object\" &&\r\n    value !== null &&\r\n    typeof (value as { message?: unknown }).message === \"string\"\r\n  );\r\n}\r\n\r\n/**\r\n * Format a `ZodError` as a user-facing validation error. The pipeline applies\r\n * it to input validation failures only; use it in `.onError()` to expose\r\n * other validation errors on purpose.\r\n */\r\nexport function zodErrorToServerActionError(error: $ZodError): ServerActionError {\r\n  // Keys are full dotted paths (\"address.city\", \"items.0.name\"), the same\r\n  // names react-hook-form registers, so each message lands on its input.\r\n  const fields: Record<string, string[]> = {};\r\n  const formErrors: string[] = [];\r\n  for (const issue of error.issues) {\r\n    if (issue.path.length === 0) {\r\n      formErrors.push(issue.message);\r\n      continue;\r\n    }\r\n    const key = issue.path.map(String).join(\".\");\r\n    (fields[key] ??= []).push(issue.message);\r\n  }\r\n\r\n  const [field] = Object.keys(fields);\r\n  const message = (field !== undefined ? fields[field][0] : undefined) ?? formErrors[0] ?? \"Validation failed\";\r\n  return {\r\n    message,\r\n    code: \"VALIDATION_ERROR\",\r\n    ...(field !== undefined && { field, fields }),\r\n    ...(formErrors.length > 0 && { formErrors }),\r\n  };\r\n}\r\n\r\nfunction convertOutputValidationError(error: OutputValidationError): ServerActionError {\r\n  let message = GENERIC_MESSAGE;\r\n  if (revealsDetails()) {\r\n    const [issue] = error.issues;\r\n    const where = issue && issue.path.length > 0 ? ` at \"${issue.path.join(\".\")}\"` : \"\";\r\n    message = `Action output does not match the output schema${where}${issue ? `: ${issue.message}` : \"\"}`;\r\n  }\r\n  return {\r\n    message,\r\n    code: \"OUTPUT_VALIDATION_ERROR\",\r\n    statusCode: 500,\r\n  };\r\n}\r\n\r\nfunction convertGenericError(error: unknown): ServerActionError {\r\n  const message = error instanceof Error ? error.message : GENERIC_MESSAGE;\r\n\r\n  return {\r\n    message: revealsDetails() ? message : GENERIC_MESSAGE,\r\n    code: \"INTERNAL_ERROR\",\r\n    statusCode: 500,\r\n  };\r\n}\r\n\r\nexport interface ResolveErrorOptions {\r\n  customHandler?: CustomErrorHandler;\r\n  phase: ErrorPhase;\r\n  logger: ActionLogger;\r\n  authRedirect: ResolvedAuthRedirect;\r\n  actionName?: string;\r\n}\r\n\r\n/**\r\n * Resolve any error into the `ServerActionError` sent to the client.\r\n * Precedence: custom handler, output validation, input validation (`phase`\r\n * \"input\" only), `toServerActionError()` duck typing, generic error.\r\n *\r\n * Only what nobody handled is logged: output validation failures, errors\r\n * that fall through to the generic conversion and a throwing custom handler.\r\n *\r\n * @internal Used by the action pipeline; not part of the public API.\r\n */\r\nexport function resolveActionError(\r\n  error: unknown,\r\n  { customHandler, phase, logger, authRedirect, actionName }: ResolveErrorOptions,\r\n): ServerActionError {\r\n  const where = describeAction(actionName);\r\n\r\n  if (customHandler) {\r\n    try {\r\n      const customError = customHandler(error);\r\n      if (customError) {\r\n        return customError;\r\n      }\r\n    } catch (handlerError) {\r\n      logger.error(`[next-action-forge] The onError handler threw${where}:`, handlerError);\r\n    }\r\n  }\r\n\r\n  if (error instanceof OutputValidationError) {\r\n    logger.error(`[next-action-forge] Output validation failed${where}:`, error);\r\n    return convertOutputValidationError(error);\r\n  }\r\n\r\n  // A malformed request, not a server bug: answered, not logged.\r\n  if (error instanceof InvalidFormDataError) {\r\n    return {\r\n      message: revealsDetails() ? error.message : \"Invalid form submission\",\r\n      code: \"INVALID_FORM_DATA\",\r\n      statusCode: 400,\r\n    };\r\n  }\r\n\r\n  // `$ZodError` covers classic Zod (`z.ZodError` extends it) and Zod Mini.\r\n  if (error instanceof $ZodError && phase === \"input\") {\r\n    return zodErrorToServerActionError(error);\r\n  }\r\n\r\n  if (hasServerActionErrorConverter(error)) {\r\n    let converted: unknown;\r\n    try {\r\n      converted = error.toServerActionError();\r\n    } catch (conversionError) {\r\n      logger.error(`[next-action-forge] toServerActionError() threw${where}:`, conversionError);\r\n      return unhandled(error, logger, where);\r\n    }\r\n\r\n    if (!isServerActionError(converted)) {\r\n      logger.error(\r\n        `[next-action-forge] toServerActionError() returned a value without a string \"message\"${where}:`,\r\n        converted,\r\n      );\r\n      return unhandled(error, logger, where);\r\n    }\r\n\r\n    return applyAuthRedirect(converted, error.type, authRedirect);\r\n  }\r\n\r\n  return unhandled(error, logger, where);\r\n}\r\n\r\n/** Report an error nobody handled and convert it to a generic response. */\r\nfunction unhandled(error: unknown, logger: ActionLogger, where: string): ServerActionError {\r\n  logger.error(`[next-action-forge] Unhandled error${where}:`, error);\r\n  return convertGenericError(error);\r\n}\r\n\r\n/**\r\n * Convert an error into a failed `ServerActionResponse`. A `ZodError` passed\r\n * here is treated as a validation error meant for the user. Unhandled errors\r\n * are reported to `console.error`.\r\n *\r\n * Next.js control flow (`redirect()`, `notFound()`, prerendering bailouts…)\r\n * is rethrown, so calling this inside your own `catch` never swallows it.\r\n */\r\nexport function handleServerActionError(\r\n  error: unknown,\r\n  customHandler?: CustomErrorHandler\r\n): { success: false; error: ServerActionError } {\r\n  rethrowIfNextInternal(error);\r\n\r\n  return {\r\n    success: false,\r\n    error: resolveActionError(error, {\r\n      customHandler,\r\n      phase: \"input\",\r\n      logger: consoleLogger,\r\n      authRedirect: DEFAULT_AUTH_REDIRECT,\r\n    }),\r\n  };\r\n}\r\n\r\nexport function isErrorResponse<T>(response: ServerActionResponse<T>): response is { success: false; error: ServerActionError } {\r\n  return !response.success;\r\n}\r\n","import type { $ZodError, $ZodIssue } from \"zod/v4/core\";\r\n\r\n/**\r\n * Raised when an action's result does not match its `.outputSchema()`.\r\n *\r\n * This is a server-side bug, never a user mistake: the client receives a\r\n * generic `OUTPUT_VALIDATION_ERROR` without field details, while `onError`\r\n * and `onFailure` receive this error with the original Zod error as `cause`.\r\n */\r\n/**\r\n * A form action was called without FormData, most often because a\r\n * `.formAction()` was passed where a regular `.action()` is expected (for\r\n * example to `useFormAction`). Answered with `INVALID_FORM_DATA` (400).\r\n */\r\nexport class InvalidFormDataError extends Error {\r\n  constructor() {\r\n    super(\r\n      \"Form actions must be called with FormData. To send an object (for example from useFormAction), define the action with .action() instead of .formAction().\",\r\n    );\r\n    this.name = \"InvalidFormDataError\";\r\n  }\r\n}\r\n\r\nexport class OutputValidationError extends Error {\r\n  readonly issues: $ZodIssue[];\r\n\r\n  constructor(zodError: $ZodError) {\r\n    super(\"Action output does not match the output schema\", { cause: zodError });\r\n    this.name = \"OutputValidationError\";\r\n    this.issues = zodError.issues;\r\n  }\r\n}\r\n","import type { ActionLogger } from \"../types\";\r\n\r\n/** Forwards to `console` at call time, so runtime patches and test spies apply. */\r\nexport const consoleLogger: ActionLogger = {\r\n  error: (...args) => console.error(...args),\r\n  warn: (...args) => console.warn(...args),\r\n};\r\n\r\nconst silentLogger: ActionLogger = {\r\n  error: () => {},\r\n  warn: () => {},\r\n};\r\n\r\nexport function resolveLogger(logger: ActionLogger | false | undefined): ActionLogger {\r\n  if (logger === false) return silentLogger;\r\n  return logger ?? consoleLogger;\r\n}\r\n\r\n/** Suffix naming the action in a log line, when it has a name. */\r\nexport function describeAction(actionName: string | undefined): string {\r\n  return actionName ? ` in action \"${actionName}\"` : \"\";\r\n}\r\n","// Comes from: https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect-error.ts\r\n\r\nenum RedirectStatusCode {\r\n\tSeeOther = 303,\r\n\tTemporaryRedirect = 307,\r\n\tPermanentRedirect = 308,\r\n}\r\n\r\nconst REDIRECT_ERROR_CODE = \"NEXT_REDIRECT\";\r\n\r\nenum RedirectType {\r\n\tpush = \"push\",\r\n\treplace = \"replace\",\r\n}\r\n\r\nexport type RedirectError = Error & {\r\n\tdigest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`;\r\n};\r\n\r\n/**\r\n * Checks an error to determine if it's an error generated by the\r\n * `redirect(url)` helper.\r\n *\r\n * @param error the error that may reference a redirect error\r\n * @returns true if the error is a redirect error\r\n */\r\nexport function isRedirectError(error: unknown): error is RedirectError {\r\n\tif (typeof error !== \"object\" || error === null || !(\"digest\" in error) || typeof error.digest !== \"string\") {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tconst digest = error.digest.split(\";\");\r\n\tconst [errorCode, type] = digest;\r\n\tconst destination = digest.slice(2, -2).join(\";\");\r\n\tconst status = digest.at(-2);\r\n\r\n\tconst statusCode = Number(status);\r\n\r\n\treturn (\r\n\t\terrorCode === REDIRECT_ERROR_CODE &&\r\n\t\t(type === \"replace\" || type === \"push\") &&\r\n\t\ttypeof destination === \"string\" &&\r\n\t\t!isNaN(statusCode) &&\r\n\t\tstatusCode in RedirectStatusCode\r\n\t);\r\n}\r\n\r\n/**\r\n * The destination of a redirect error. For a Server Action call that\r\n * redirected, Next.js puts there the path and search it navigates to\r\n * (without the base path), or the full URL of an external target.\r\n */\r\nexport function getURLFromRedirectError(error: RedirectError): string {\r\n\treturn error.digest.split(\";\").slice(2, -2).join(\";\");\r\n}","// Comes from https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/http-access-fallback/http-access-fallback.ts\r\n\r\nconst HTTPAccessErrorStatus = {\r\n\tNOT_FOUND: 404,\r\n\tFORBIDDEN: 403,\r\n\tUNAUTHORIZED: 401,\r\n};\r\n\r\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus));\r\n\r\nconst HTTP_ERROR_FALLBACK_ERROR_CODE = \"NEXT_HTTP_ERROR_FALLBACK\";\r\n\r\nexport type HTTPAccessFallbackError = Error & {\r\n\tdigest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`;\r\n};\r\n\r\n/**\r\n * Checks an error to determine if it's an error generated by\r\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\r\n *\r\n * @param error the error that may reference a HTTP access error\r\n * @returns true if the error is a HTTP access error\r\n */\r\nexport function isHTTPAccessFallbackError(error: unknown): error is HTTPAccessFallbackError {\r\n\tif (typeof error !== \"object\" || error === null || !(\"digest\" in error) || typeof error.digest !== \"string\") {\r\n\t\treturn false;\r\n\t}\r\n\tconst [prefix, httpStatus] = error.digest.split(\";\");\r\n\r\n\treturn prefix === HTTP_ERROR_FALLBACK_ERROR_CODE && ALLOWED_CODES.has(Number(httpStatus));\r\n}\r\n\r\nexport function getAccessFallbackHTTPStatus(error: HTTPAccessFallbackError): number {\r\n\tconst httpStatus = error.digest.split(\";\")[1];\r\n\treturn Number(httpStatus);\r\n}","// Mirrors of the checks behind `unstable_rethrow` in next/navigation\r\n// (Next.js 16.3: client/components/unstable-rethrow.server.js and the\r\n// modules it imports). They are copied rather than imported because plain\r\n// Node ESM cannot resolve \"next/navigation\" (Next ships no \"exports\" map),\r\n// which would break this package's ESM build outside a bundler.\r\n\r\nfunction hasDigest(error: unknown): error is { digest: string } {\r\n  return (\r\n    typeof error === \"object\" &&\r\n    error !== null &&\r\n    \"digest\" in error &&\r\n    typeof (error as { digest: unknown }).digest === \"string\"\r\n  );\r\n}\r\n\r\n/** `notFound()` on Next.js 14 and 15.0, before NEXT_HTTP_ERROR_FALLBACK. */\r\nexport function isLegacyNotFoundError(error: unknown): boolean {\r\n  return hasDigest(error) && error.digest === \"NEXT_NOT_FOUND\";\r\n}\r\n\r\n/** Dynamic API used while prerendering (hooks-server-context). */\r\nexport function isDynamicServerError(error: unknown): boolean {\r\n  return hasDigest(error) && error.digest === \"DYNAMIC_SERVER_USAGE\";\r\n}\r\n\r\n/** `useSearchParams()` and friends opting a subtree out of prerendering. */\r\nexport function isBailoutToCSRError(error: unknown): boolean {\r\n  return hasDigest(error) && error.digest === \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\r\n}\r\n\r\n/** Prerendering stopped a promise that will never settle (cache components). */\r\nexport function isHangingPromiseRejectionError(error: unknown): boolean {\r\n  return hasDigest(error) && error.digest === \"HANGING_PROMISE_REJECTION\";\r\n}\r\n\r\n/** Prerendering interrupted by dynamic access (cache components). */\r\nexport function isPrerenderInterruptedError(error: unknown): boolean {\r\n  return (\r\n    hasDigest(error) &&\r\n    error.digest === \"NEXT_PRERENDER_INTERRUPTED\" &&\r\n    error instanceof Error\r\n  );\r\n}\r\n\r\n/** React's postpone signal used by partial prerendering. */\r\nexport function isPostpone(error: unknown): boolean {\r\n  return (\r\n    typeof error === \"object\" &&\r\n    error !== null &&\r\n    (error as { $$typeof?: unknown }).$$typeof === Symbol.for(\"react.postpone\")\r\n  );\r\n}\r\n\r\n/** Partial prerendering postponing because a dynamic API was used. */\r\nexport function isDynamicPostpone(error: unknown): boolean {\r\n  if (typeof error !== \"object\" || error === null) return false;\r\n  const message = (error as { message?: unknown }).message;\r\n  return (\r\n    typeof message === \"string\" &&\r\n    message.includes(\"needs to bail out of prerendering at this point because it used\") &&\r\n    message.includes(\"Learn more: https://nextjs.org/docs/messages/ppr-caught-error\")\r\n  );\r\n}\r\n","import { isRedirectError } from \"./redirect\";\r\nimport { isHTTPAccessFallbackError, getAccessFallbackHTTPStatus } from \"./http-access-fallback\";\r\nimport {\r\n  isBailoutToCSRError,\r\n  isDynamicPostpone,\r\n  isDynamicServerError,\r\n  isHangingPromiseRejectionError,\r\n  isLegacyNotFoundError,\r\n  isPostpone,\r\n  isPrerenderInterruptedError,\r\n} from \"./framework\";\r\n\r\nexport { isRedirectError } from \"./redirect\";\r\nexport type { RedirectError } from \"./redirect\";\r\n\r\nexport { isHTTPAccessFallbackError, getAccessFallbackHTTPStatus } from \"./http-access-fallback\";\r\nexport type { HTTPAccessFallbackError } from \"./http-access-fallback\";\r\n\r\n/**\r\n * Checks if the error is a navigation error that should be re-thrown:\r\n * `redirect()`, `permanentRedirect()`, `notFound()`, `forbidden()` and\r\n * `unauthorized()`, including the `notFound()` digest of Next.js 14 and 15.0.\r\n */\r\nexport function isNextNavigationError(error: unknown): boolean {\r\n\treturn isRedirectError(error) || isHTTPAccessFallbackError(error) || isLegacyNotFoundError(error);\r\n}\r\n\r\n/**\r\n * Checks if the error is a notFound error\r\n * Note: Next.js implements notFound() using HTTP_ERROR_FALLBACK with status 404,\r\n * not as a separate error type like NEXT_REDIRECT (Next.js 14 and 15.0 used\r\n * the NEXT_NOT_FOUND digest instead).\r\n */\r\nexport function isNotFoundError(error: unknown): boolean {\r\n\treturn (\r\n\t\tisLegacyNotFoundError(error) ||\r\n\t\t(isHTTPAccessFallbackError(error) && getAccessFallbackHTTPStatus(error) === 404)\r\n\t);\r\n}\r\n\r\n/**\r\n * Whether the error is Next.js control flow that user code must never\r\n * swallow: navigation errors plus the signals Next uses while rendering\r\n * (dynamic usage, client-side-rendering bailouts, postpones). The same set\r\n * `unstable_rethrow` from next/navigation checks.\r\n */\r\nexport function isNextInternalError(error: unknown): boolean {\r\n\treturn (\r\n\t\tisNextNavigationError(error) ||\r\n\t\tisBailoutToCSRError(error) ||\r\n\t\tisDynamicServerError(error) ||\r\n\t\tisDynamicPostpone(error) ||\r\n\t\tisPostpone(error) ||\r\n\t\tisHangingPromiseRejectionError(error) ||\r\n\t\tisPrerenderInterruptedError(error)\r\n\t);\r\n}\r\n\r\nconst MAX_CAUSE_DEPTH = 10;\r\n\r\n/**\r\n * Rethrow the error, or the first error in its `cause` chain, when it is\r\n * Next.js control flow. Mirrors `unstable_rethrow`, so an action called from\r\n * a Server Component keeps redirects, `notFound()` and prerendering bailouts\r\n * working even when user code wraps them in another error.\r\n */\r\nexport function rethrowIfNextInternal(error: unknown): void {\r\n\tlet current: unknown = error;\r\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && current !== undefined && current !== null; depth++) {\r\n\t\tif (isNextInternalError(current)) {\r\n\t\t\tthrow current;\r\n\t\t}\r\n\t\tcurrent = current instanceof Error ? current.cause : undefined;\r\n\t}\r\n}\r\n","import type { ActionLogger, RedirectSpec, RedirectTarget } from \"../types\";\r\n\r\nexport type { RedirectSpec } from \"../types\";\r\nimport { describeAction } from \"./logger\";\r\n\r\nconst PARSE_BASE = \"http://next-action-forge.invalid\";\r\n\r\n// Browsers strip tabs and newlines from URLs before parsing them, so a path\r\n// such as \"/\\t/evil.example\" would turn into the protocol-relative\r\n// \"//evil.example\". Any control character is rejected outright.\r\n// eslint-disable-next-line no-control-regex -- matching control characters is the point.\r\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001F\\u007F]/;\r\n\r\n/**\r\n * Whether `value` is a same-origin path that is safe to navigate to: it\r\n * starts with a single \"/\" and, once parsed the way a browser parses it,\r\n * still points to the current origin. Rejects absolute and\r\n * protocol-relative URLs, backslash tricks (\"/\\\\evil.example\") and control\r\n * characters.\r\n */\r\nexport function isSafeRedirectPath(value: unknown): value is string {\r\n  if (typeof value !== \"string\" || !value.startsWith(\"/\")) return false;\r\n  if (value[1] === \"/\" || value[1] === \"\\\\\") return false;\r\n  if (CONTROL_CHARACTERS.test(value)) return false;\r\n  try {\r\n    return new URL(value, PARSE_BASE).origin === PARSE_BASE;\r\n  } catch {\r\n    return false;\r\n  }\r\n}\r\n\r\n/** Throws at definition time when a static redirect points outside the app. */\r\nexport function assertSafeRedirectPath(url: unknown, source: string): void {\r\n  if (!isSafeRedirectPath(url)) {\r\n    throw new TypeError(\r\n      `[next-action-forge] ${source} only accepts a same-origin path starting with \"/\", received ${JSON.stringify(url)}. ` +\r\n        `Use redirect() from next/navigation inside the handler to leave the app.`,\r\n    );\r\n  }\r\n}\r\n\r\n/** Validate a fixed target at definition time; callbacks are checked on each call. */\r\nexport function assertStaticRedirect(spec: RedirectSpec | undefined, source: string): void {\r\n  if (typeof spec === \"string\") {\r\n    assertSafeRedirectPath(spec, source);\r\n  } else if (typeof spec === \"object\" && spec !== null) {\r\n    assertSafeRedirectPath(spec.url, source);\r\n  }\r\n}\r\n\r\n/**\r\n * Resolve the redirect attached to a successful result. The callback may be\r\n * async. A callback that throws or returns an unsafe target is logged and\r\n * yields no redirect: the mutation already happened, so the success must\r\n * still reach the client.\r\n */\r\nexport async function resolveRedirect(\r\n  spec: RedirectSpec | undefined,\r\n  output: unknown,\r\n  logger: ActionLogger,\r\n  actionName: string | undefined,\r\n): Promise<RedirectTarget | undefined> {\r\n  if (!spec) return undefined;\r\n\r\n  let value: RedirectTarget | undefined;\r\n  try {\r\n    value = typeof spec === \"function\" ? await spec(output) : spec;\r\n  } catch (error) {\r\n    logger.error(`[next-action-forge] The redirect callback threw${describeAction(actionName)}:`, error);\r\n    return undefined;\r\n  }\r\n\r\n  if (value === undefined || value === null) return undefined;\r\n\r\n  const url = typeof value === \"string\" ? value : value.url;\r\n  if (!isSafeRedirectPath(url)) {\r\n    logger.error(\r\n      `[next-action-forge] Ignored a redirect to ${JSON.stringify(url)}${describeAction(actionName)}: only same-origin paths are allowed.`,\r\n    );\r\n    return undefined;\r\n  }\r\n  return value;\r\n}\r\n","/** Placeholder that replaces the value of a sensitive key. */\r\nexport const REDACTED = \"[REDACTED]\";\r\n\r\n/**\r\n * A key to hide: a string matches the whole key, ignoring case; a RegExp is\r\n * tested against the key.\r\n */\r\nexport type RedactMatcher = string | RegExp;\r\n\r\n/**\r\n * Keys hidden from lifecycle hooks and `.onError()` by default. Built from\r\n * the audit sanitizers of real consumers. Short names such as `ssn` match the\r\n * whole key only, so keys like `className` are left alone.\r\n */\r\nexport const DEFAULT_REDACT_KEYS: readonly RedactMatcher[] = [\r\n  /pass(word|wd|phrase)/i,\r\n  /token/i,\r\n  /secret/i,\r\n  /api[-_]?key/i,\r\n  /jwt/i,\r\n  /bearer/i,\r\n  /^authorization$/i,\r\n  /cookie/i,\r\n  /hash$/i,\r\n  /credit[-_]?card|card[-_]?number/i,\r\n  /^(cvv|cvc)$/i,\r\n  /^ssn$/i,\r\n  /private[-_]?key/i,\r\n];\r\n\r\nconst MAX_DEPTH = 32;\r\n\r\nexport function resolveRedactKeys(\r\n  option: false | readonly RedactMatcher[] | undefined,\r\n): readonly RedactMatcher[] {\r\n  if (option === false) return [];\r\n  return option ?? DEFAULT_REDACT_KEYS;\r\n}\r\n\r\nfunction matchesKey(key: string, matchers: readonly RedactMatcher[]): boolean {\r\n  return matchers.some((matcher) => {\r\n    if (typeof matcher === \"string\") {\r\n      return matcher.toLowerCase() === key.toLowerCase();\r\n    }\r\n    matcher.lastIndex = 0;\r\n    return matcher.test(key);\r\n  });\r\n}\r\n\r\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\r\n  if (typeof value !== \"object\" || value === null) return false;\r\n  const prototype = Object.getPrototypeOf(value);\r\n  return prototype === Object.prototype || prototype === null;\r\n}\r\n\r\nfunction walk(\r\n  value: unknown,\r\n  matchers: readonly RedactMatcher[],\r\n  copies: WeakMap<object, unknown>,\r\n  depth: number,\r\n): unknown {\r\n  if (depth > MAX_DEPTH) return value;\r\n\r\n  if (Array.isArray(value)) {\r\n    if (copies.has(value)) return copies.get(value);\r\n    const copy: unknown[] = [];\r\n    copies.set(value, copy);\r\n    for (const item of value) {\r\n      copy.push(walk(item, matchers, copies, depth + 1));\r\n    }\r\n    return copy;\r\n  }\r\n\r\n  if (isPlainObject(value)) {\r\n    if (copies.has(value)) return copies.get(value);\r\n    const copy: Record<string, unknown> = {};\r\n    copies.set(value, copy);\r\n    for (const [key, item] of Object.entries(value)) {\r\n      copy[key] = matchesKey(key, matchers) ? REDACTED : walk(item, matchers, copies, depth + 1);\r\n    }\r\n    return copy;\r\n  }\r\n\r\n  // Dates, Maps, Files, class instances and primitives are returned as-is.\r\n  return value;\r\n}\r\n\r\n/**\r\n * Dotted paths of the keys matching `matchers`, looking at most `maxDepth`\r\n * levels deep (an array index counts as a level). Used to warn about results\r\n * that would send sensitive-looking data to the client.\r\n */\r\nexport function findSensitiveKeys(\r\n  value: unknown,\r\n  matchers: readonly RedactMatcher[],\r\n  maxDepth = 3,\r\n): string[] {\r\n  const found: string[] = [];\r\n  const seen = new WeakSet<object>();\r\n  const visit = (node: unknown, path: string, depth: number): void => {\r\n    if (depth >= maxDepth || typeof node !== \"object\" || node === null || seen.has(node)) return;\r\n    seen.add(node);\r\n    if (Array.isArray(node)) {\r\n      node.forEach((item, index) => visit(item, path ? `${path}.${index}` : String(index), depth + 1));\r\n      return;\r\n    }\r\n    if (!isPlainObject(node)) return;\r\n    for (const [key, item] of Object.entries(node)) {\r\n      const keyPath = path ? `${path}.${key}` : key;\r\n      if (matchesKey(key, matchers)) {\r\n        found.push(keyPath);\r\n      } else {\r\n        visit(item, keyPath, depth + 1);\r\n      }\r\n    }\r\n  };\r\n  visit(value, \"\", 0);\r\n  return found;\r\n}\r\n\r\n/**\r\n * Copy of `value` where every plain-object key matching `matchers` holds\r\n * `\"[REDACTED]\"`. Arrays and plain objects are copied; the original is\r\n * never modified. Other values are returned unchanged.\r\n */\r\nexport function redact(value: unknown, matchers: readonly RedactMatcher[]): unknown {\r\n  if (matchers.length === 0) return value;\r\n  return walk(value, matchers, new WeakMap(), 0);\r\n}\r\n","import type { $ZodType } from \"zod/v4/core\";\r\n\r\n// Native form decoding. It rebuilds structure only (nested objects, arrays,\r\n// files) and never guesses types from values: every value stays the string\r\n// the browser sent, and the schema declares the conversions it wants, with\r\n// z.stringbool(), z.coerce.number(), z.iso.date() or z.preprocess().\r\n\r\nconst APPEND = Symbol(\"append\");\r\ntype Segment = string | number | typeof APPEND;\r\n\r\n// Names that would reach Object.prototype through a nested assignment.\r\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\r\n\r\nconst MAX_SCHEMA_DEPTH = 32;\r\n\r\n// Empty slots that array indexes may open, all arrays together. A gap is\r\n// legitimate (rows removed from the middle of a list keep their indexes),\r\n// but the schema validates every slot: with a limit per index only, a small\r\n// request with nested indexes such as `items[i].tags[9999]` would make it\r\n// walk millions of them.\r\nconst MAX_ARRAY_HOLES = 10_000;\r\n\r\n/**\r\n * Split a field name into path segments: `a.b` and `a[b]` are object keys,\r\n * `a[0]` is an array index and `a[]` appends. A malformed name is kept whole.\r\n */\r\nfunction parseName(name: string): Segment[] {\r\n  const segments: Segment[] = [];\r\n  let current = \"\";\r\n  let index = 0;\r\n  while (index < name.length) {\r\n    const char = name[index];\r\n    if (char === \".\") {\r\n      if (current) segments.push(current);\r\n      current = \"\";\r\n      index += 1;\r\n    } else if (char === \"[\") {\r\n      const end = name.indexOf(\"]\", index);\r\n      if (end === -1) return [name];\r\n      if (current) segments.push(current);\r\n      current = \"\";\r\n      const inner = name.slice(index + 1, end);\r\n      if (inner === \"\") {\r\n        segments.push(APPEND);\r\n      } else if (/^\\d+$/.test(inner)) {\r\n        segments.push(Number(inner));\r\n      } else {\r\n        segments.push(inner);\r\n      }\r\n      index = end + 1;\r\n    } else {\r\n      current += char;\r\n      index += 1;\r\n    }\r\n  }\r\n  if (current) segments.push(current);\r\n  return segments.length > 0 ? segments : [name];\r\n}\r\n\r\ntype Container = Record<string, unknown> | unknown[];\r\n\r\nfunction isContainer(value: unknown): value is Container {\r\n  return typeof value === \"object\" && value !== null && !(value instanceof Blob);\r\n}\r\n\r\n/**\r\n * How many empty slots `assign(root, segments, …)` would open: an index past\r\n * the end of an array leaves a gap before it. Mirrors the walk of `assign`\r\n * without changing anything; `undefined` stands for a container it would\r\n * create.\r\n */\r\nfunction holesOpenedBy(root: Container, segments: Segment[]): number {\r\n  let node: Container | undefined = root;\r\n  let holes = 0;\r\n  for (let position = 0; position < segments.length; position++) {\r\n    const segment = segments[position];\r\n    if (typeof segment === \"number\" && (node === undefined || Array.isArray(node))) {\r\n      holes += Math.max(0, segment - (node?.length ?? 0));\r\n    }\r\n    if (position === segments.length - 1) break;\r\n\r\n    const next = segments[position + 1];\r\n    const wantsArray = next === APPEND || typeof next === \"number\";\r\n    const child: unknown =\r\n      node === undefined || segment === APPEND ? undefined : (node as Record<string | number, unknown>)[segment];\r\n    node = isContainer(child) && Array.isArray(child) === wantsArray ? child : undefined;\r\n  }\r\n  return holes;\r\n}\r\n\r\nfunction assign(root: Record<string, unknown>, segments: Segment[], value: unknown): void {\r\n  let node: Container = root;\r\n  for (let position = 0; position < segments.length; position++) {\r\n    const segment = segments[position];\r\n    const isLast = position === segments.length - 1;\r\n\r\n    if (segment === APPEND) {\r\n      if (!Array.isArray(node)) return;\r\n      if (isLast) {\r\n        node.push(value);\r\n        return;\r\n      }\r\n      const next = segments[position + 1];\r\n      const child: Container = next === APPEND || typeof next === \"number\" ? [] : {};\r\n      node.push(child);\r\n      node = child;\r\n      continue;\r\n    }\r\n\r\n    const slot = node as Record<string | number, unknown>;\r\n    if (isLast) {\r\n      const existing = slot[segment];\r\n      if (existing === undefined) {\r\n        slot[segment] = value;\r\n      } else if (Array.isArray(existing)) {\r\n        existing.push(value);\r\n      } else {\r\n        // A repeated plain name (checkbox group, multi-select) becomes an array.\r\n        slot[segment] = [existing, value];\r\n      }\r\n      return;\r\n    }\r\n\r\n    const next = segments[position + 1];\r\n    const wantsArray = next === APPEND || typeof next === \"number\";\r\n    let child = slot[segment];\r\n    if (!isContainer(child) || Array.isArray(child) !== wantsArray) {\r\n      child = wantsArray ? [] : {};\r\n      slot[segment] = child;\r\n    }\r\n    node = child as Container;\r\n  }\r\n}\r\n\r\n/** The schema that receives the raw input, looking through wrappers and preprocessing. */\r\nfunction inputSide(schema: $ZodType | undefined): $ZodType | undefined {\r\n  let current = schema;\r\n  for (let step = 0; step < MAX_SCHEMA_DEPTH && current; step++) {\r\n    const def = current._zod?.def as Record<string, any> | undefined;\r\n    if (!def) return undefined;\r\n    switch (def.type) {\r\n      case \"optional\":\r\n      case \"nullable\":\r\n      case \"default\":\r\n      case \"prefault\":\r\n      case \"catch\":\r\n      case \"readonly\":\r\n      case \"nonoptional\":\r\n        current = def.innerType;\r\n        break;\r\n      case \"pipe\":\r\n        // z.preprocess() is a pipe whose input side is a transform: the\r\n        // structure lives in its output schema.\r\n        current = def.in?._zod?.def?.type === \"transform\" ? def.out : def.in;\r\n        break;\r\n      case \"lazy\":\r\n        current = def.getter();\r\n        break;\r\n      default:\r\n        return current;\r\n    }\r\n  }\r\n  return current;\r\n}\r\n\r\n/**\r\n * Wrap single values in arrays where the schema expects an array, so a\r\n * multi-select or checkbox group with one selected option still validates.\r\n */\r\nfunction alignArrays(value: unknown, schema: $ZodType | undefined, depth: number): unknown {\r\n  if (depth > MAX_SCHEMA_DEPTH || value === undefined) return value;\r\n  const target = inputSide(schema);\r\n  const def = target?._zod?.def as Record<string, any> | undefined;\r\n  if (!def) return value;\r\n\r\n  if (def.type === \"array\") {\r\n    const items = Array.isArray(value) ? value : [value];\r\n    return items.map((item) => alignArrays(item, def.element, depth + 1));\r\n  }\r\n\r\n  if (def.type === \"object\" && isContainer(value) && !Array.isArray(value)) {\r\n    const shape = def.shape as Record<string, $ZodType>;\r\n    for (const key of Object.keys(shape)) {\r\n      if (Object.prototype.hasOwnProperty.call(value, key)) {\r\n        value[key] = alignArrays(value[key], shape[key], depth + 1);\r\n      }\r\n    }\r\n  }\r\n  return value;\r\n}\r\n\r\n/**\r\n * Decode native form data into a plain object without guessing types.\r\n *\r\n * - `a.b` and `a[b]` build nested objects, `a[0]` builds arrays, `a[]`\r\n *   appends, and a repeated name becomes an array.\r\n * - Values stay strings (or `File`); declare conversions in the schema.\r\n * - The empty part an unselected `<input type=\"file\">` sends is dropped.\r\n * - Names reaching `__proto__`, `prototype` or `constructor` are ignored.\r\n * - Indexes keep their positions: rows removed from the middle of a list leave\r\n *   empty slots, which a schema accepts with optional elements\r\n *   (`z.array(row.optional())`). All arrays together may hold up to 10,000\r\n *   empty slots; an entry that would open more is ignored.\r\n * - With a schema, a single value is wrapped where the schema expects an array.\r\n */\r\nexport function decodeFormData(formData: FormData, schema?: $ZodType): Record<string, unknown> {\r\n  const result: Record<string, unknown> = {};\r\n  let holesLeft = MAX_ARRAY_HOLES;\r\n\r\n  for (const [name, value] of formData.entries()) {\r\n    if (typeof value !== \"string\" && value.size === 0 && value.name === \"\") continue;\r\n\r\n    const segments = parseName(name);\r\n    if (segments.some((segment) => typeof segment === \"string\" && FORBIDDEN_SEGMENTS.has(segment))) continue;\r\n\r\n    const holes = holesOpenedBy(result, segments);\r\n    if (holes > holesLeft) continue;\r\n    holesLeft -= holes;\r\n\r\n    assign(result, segments, value);\r\n  }\r\n\r\n  return schema ? (alignArrays(result, schema, 0) as Record<string, unknown>) : result;\r\n}\r\n","import * as z4 from \"zod/v4/core\";\r\nimport type {\r\n  ActionLogger,\r\n  ServerActionError,\r\n  ServerActionResponse,\r\n  HookOptions,\r\n  OnStartHook,\r\n  OnSuccessHook,\r\n  OnFailureHook,\r\n  OnCompleteHook,\r\n} from \"../types\";\r\nimport type { ServerActionMiddleware } from \"./middleware-helpers\";\r\nimport {\r\n  isServerActionError,\r\n  resolveActionError,\r\n  type ErrorPhase,\r\n  type ResolvedAuthRedirect,\r\n} from \"./error-handler\";\r\nimport { OutputValidationError } from \"./errors\";\r\nimport { describeAction } from \"./logger\";\r\nimport { DEFAULT_REDACT_KEYS, findSensitiveKeys, redact, type RedactMatcher } from \"./redact\";\r\nimport { resolveRedirect, type RedirectSpec } from \"./redirect\";\r\nimport { rethrowIfNextInternal } from \"../next/errors\";\r\n\r\nexport type { RedirectSpec } from \"./redirect\";\r\n\r\nexport type HookEntry<H> = { hook: H; options: HookOptions };\r\n\r\n/** Context given to `.onError()`: the input known when the error happened, redacted. */\r\nexport interface ErrorHandlerContext {\r\n  /** The validated input, or `undefined` when validation had not succeeded. */\r\n  parsedInput?: unknown;\r\n  /** What the client sent. */\r\n  rawInput?: unknown;\r\n}\r\n\r\nexport type ActionErrorHandler = (\r\n  error: unknown,\r\n  context: ErrorHandlerContext,\r\n) => ServerActionError | undefined;\r\n\r\ntype SafeParseResult = z4.util.SafeParseResult<unknown>;\r\n\r\n/**\r\n * Parse with the schema's own `safeParseAsync` when it has one (Zod and Zod\r\n * Mini both do), so errors keep the consumer's flavour: `z.ZodError` for\r\n * classic Zod. Core's top-level function, the fallback for bare core\r\n * schemas, always returns a plain `$ZodError`.\r\n */\r\nfunction safeParseAsync(schema: z4.$ZodType, value: unknown): Promise<SafeParseResult> {\r\n  const method = (schema as { safeParseAsync?: (value: unknown) => Promise<SafeParseResult> })\r\n    .safeParseAsync;\r\n  return typeof method === \"function\"\r\n    ? method.call(schema, value)\r\n    : z4.safeParseAsync(schema, value);\r\n}\r\n\r\n/** Everything one action invocation needs; built by `ServerActionClient`. */\r\nexport interface PipelineConfig {\r\n  inputSchema?: z4.$ZodType;\r\n  outputSchema?: z4.$ZodType;\r\n  /** `.useBeforeValidation()` middleware: raw input, before validation. */\r\n  preValidationFns: ServerActionMiddleware<any, any, any>[];\r\n  /** `.use()` middleware: validated input, after validation. */\r\n  middlewareFns: ServerActionMiddleware<any, any, any>[];\r\n  onError?: ActionErrorHandler;\r\n  serverCodeFn: (...args: any[]) => Promise<any>;\r\n  redirectConfig?: RedirectSpec;\r\n  actionName?: string;\r\n  logger: ActionLogger;\r\n  authRedirect: ResolvedAuthRedirect;\r\n  /** Keys hidden from hooks and `.onError()`. Empty disables redaction. */\r\n  redactKeys: readonly RedactMatcher[];\r\n  onStartFns?: HookEntry<OnStartHook<any, any>>[];\r\n  onSuccessFns?: HookEntry<OnSuccessHook<any, any, any>>[];\r\n  onFailureFns?: HookEntry<OnFailureHook<any, any>>[];\r\n  onCompleteFns?: HookEntry<OnCompleteHook<any, any, any>>[];\r\n}\r\n\r\ntype HookName = \"onStart\" | \"onSuccess\" | \"onFailure\" | \"onComplete\";\r\n\r\nconst warnedAboutOutput = new WeakSet<PipelineConfig>();\r\n\r\n/**\r\n * In development, warn once per action when a result sent without an output\r\n * schema contains keys that look sensitive: everything the handler returns\r\n * reaches the client.\r\n */\r\nfunction warnAboutSensitiveOutput(config: PipelineConfig, output: unknown): void {\r\n  if (process.env.NODE_ENV !== \"development\" || config.outputSchema || warnedAboutOutput.has(config)) {\r\n    return;\r\n  }\r\n  const matchers = config.redactKeys.length > 0 ? config.redactKeys : DEFAULT_REDACT_KEYS;\r\n  const keys = findSensitiveKeys(output, matchers);\r\n  if (keys.length === 0) return;\r\n  warnedAboutOutput.add(config);\r\n  const action = config.actionName ? `Action \"${config.actionName}\"` : \"An action\";\r\n  config.logger.warn(\r\n    `[next-action-forge] ${action} returned keys that look sensitive (${keys.join(\", \")}) and has no outputSchema, ` +\r\n      `so the client receives them. Add .outputSchema() to choose what is sent.`,\r\n  );\r\n}\r\n\r\nfunction describeValue(value: unknown): string {\r\n  if (value === undefined) return \"undefined\";\r\n  try {\r\n    return JSON.stringify(value);\r\n  } catch {\r\n    return typeof value;\r\n  }\r\n}\r\n\r\n/**\r\n * Read what a middleware returned. Anything other than `{ context }` or\r\n * `{ error: ServerActionError }` is a bug in the middleware, most often a\r\n * forgotten `return` in an authorization branch, so it fails closed.\r\n */\r\nfunction readMiddlewareResult(result: unknown): { context: object } | { error: ServerActionError } {\r\n  if (typeof result === \"object\" && result !== null) {\r\n    const { context, error } = result as { context?: unknown; error?: unknown };\r\n    if (error !== undefined && error !== null) {\r\n      if (isServerActionError(error)) return { error };\r\n    } else if (\"context\" in result) {\r\n      return { context: typeof context === \"object\" && context !== null ? context : {} };\r\n    }\r\n  }\r\n  throw new TypeError(\r\n    `[next-action-forge] A middleware must return { context } or { error: { message } }, received ${describeValue(result)}.`,\r\n  );\r\n}\r\n\r\n/**\r\n * Run one action invocation: pre-validation middleware, input validation,\r\n * `onStart`, the `.use()` middleware, the handler, output validation,\r\n * redirect resolution and the remaining lifecycle hooks. Shared by\r\n * `.action()` and `.formAction()`.\r\n *\r\n * `readInput` runs inside the error boundary, so a failure while reading the\r\n * raw input (for example decoding a malformed FormData payload) is reported\r\n * like any other error instead of rejecting the action promise.\r\n */\r\nexport async function runPipeline<TOutput>(\r\n  config: PipelineConfig,\r\n  readInput: () => unknown,\r\n): Promise<ServerActionResponse<TOutput>> {\r\n  const hasInputSchema = config.inputSchema !== undefined && config.inputSchema !== null;\r\n  const startTs = performance.now();\r\n  const name = config.actionName;\r\n  const { logger } = config;\r\n  let middlewareContext: Record<string, unknown> = {};\r\n  let finalResult: ServerActionResponse<TOutput> | undefined;\r\n  let rawInput: unknown;\r\n  // Set only once validation succeeded: hooks never see unvalidated data as `input`.\r\n  let validatedInput: unknown;\r\n\r\n  const elapsed = () => performance.now() - startTs;\r\n\r\n  // Hooks and `.onError()` only ever see redacted copies, each computed once.\r\n  const redactedCopies = new WeakMap<object, unknown>();\r\n  const redacted = (value: unknown): unknown => {\r\n    if (typeof value !== \"object\" || value === null) return value;\r\n    if (!redactedCopies.has(value)) {\r\n      redactedCopies.set(value, redact(value, config.redactKeys));\r\n    }\r\n    return redactedCopies.get(value);\r\n  };\r\n  const inputs = () => ({ input: redacted(validatedInput), rawInput: redacted(rawInput) });\r\n\r\n  // Each hook is isolated: a throwing hook is reported and never breaks the\r\n  // action flow. A `fireAndForget` hook starts on a later macrotask, so none\r\n  // of its code runs before the action resolves.\r\n  const runHooks = async (\r\n    entries: HookEntry<(...args: any[]) => void | Promise<void>>[] | undefined,\r\n    buildParams: () => unknown,\r\n    hookName: HookName,\r\n  ): Promise<void> => {\r\n    if (!entries || entries.length === 0) return;\r\n    const params = buildParams();\r\n    for (const entry of entries) {\r\n      const invoke = async () => {\r\n        try {\r\n          await entry.hook(params as any);\r\n        } catch (err) {\r\n          logger.warn(`[next-action-forge] The ${hookName} hook threw${describeAction(name)}:`, err);\r\n        }\r\n      };\r\n      if (entry.options?.fireAndForget) {\r\n        setTimeout(() => void invoke(), 0);\r\n      } else {\r\n        await invoke();\r\n      }\r\n    }\r\n  };\r\n\r\n  const resolveError = (error: unknown, phase: ErrorPhase) =>\r\n    resolveActionError(error, {\r\n      customHandler: config.onError\r\n        ? (err: unknown) => config.onError!(err, inputsForErrorHandler())\r\n        : undefined,\r\n      phase,\r\n      logger,\r\n      authRedirect: config.authRedirect,\r\n      actionName: name,\r\n    });\r\n  const inputsForErrorHandler = (): ErrorHandlerContext => ({\r\n    parsedInput: redacted(validatedInput),\r\n    rawInput: redacted(rawInput),\r\n  });\r\n\r\n  // Answer with `error` and report `cause` (what went wrong) to onFailure.\r\n  const fail = async (error: ServerActionError, cause: unknown) => {\r\n    finalResult = { success: false, error };\r\n    await runHooks(config.onFailureFns, () => ({\r\n      ...inputs(),\r\n      context: middlewareContext,\r\n      name,\r\n      error: cause,\r\n      duration: elapsed(),\r\n    }), \"onFailure\");\r\n    return finalResult;\r\n  };\r\n\r\n  // Run middleware in order, merging each returned context. Returns the\r\n  // first error a middleware answers with, if any.\r\n  const runMiddleware = async (\r\n    middlewares: ServerActionMiddleware<any, any, any>[],\r\n    input: unknown,\r\n  ): Promise<ServerActionError | undefined> => {\r\n    for (const middleware of middlewares) {\r\n      const outcome = readMiddlewareResult(await middleware({ context: middlewareContext, input }));\r\n      if (\"error\" in outcome) return outcome.error;\r\n      middlewareContext = { ...middlewareContext, ...outcome.context };\r\n    }\r\n    return undefined;\r\n  };\r\n\r\n  try {\r\n    rawInput = readInput();\r\n\r\n    // Pre-validation middleware see the raw input, so authentication can\r\n    // reject a caller before the schema reveals anything about the input.\r\n    const preValidationError = await runMiddleware(config.preValidationFns, rawInput);\r\n    if (preValidationError) {\r\n      return await fail(preValidationError, preValidationError);\r\n    }\r\n\r\n    if (config.inputSchema) {\r\n      const parsed = await safeParseAsync(config.inputSchema, rawInput);\r\n      if (!parsed.success) {\r\n        return await fail(resolveError(parsed.error, \"input\"), parsed.error);\r\n      }\r\n      validatedInput = parsed.data;\r\n    }\r\n\r\n    // onStart fires after input validation, before the .use() middleware.\r\n    await runHooks(config.onStartFns, () => ({\r\n      ...inputs(),\r\n      context: middlewareContext,\r\n      name,\r\n    }), \"onStart\");\r\n\r\n    // Post-validation middleware see the validated input.\r\n    const middlewareError = await runMiddleware(\r\n      config.middlewareFns,\r\n      hasInputSchema ? validatedInput : undefined,\r\n    );\r\n    if (middlewareError) {\r\n      return await fail(middlewareError, middlewareError);\r\n    }\r\n\r\n    const output = hasInputSchema\r\n      ? await config.serverCodeFn(validatedInput, middlewareContext)\r\n      : await config.serverCodeFn(middlewareContext);\r\n\r\n    let validatedOutput: unknown = output;\r\n    if (config.outputSchema) {\r\n      const parsed = await safeParseAsync(config.outputSchema, output);\r\n      if (!parsed.success) {\r\n        // A result that breaks its own schema is a server bug: never send\r\n        // the schema's field names to the client.\r\n        const outputError = new OutputValidationError(parsed.error);\r\n        return await fail(resolveError(outputError, \"execution\"), outputError);\r\n      }\r\n      validatedOutput = parsed.data;\r\n    }\r\n\r\n    warnAboutSensitiveOutput(config, validatedOutput);\r\n\r\n    const redirectValue = await resolveRedirect(config.redirectConfig, validatedOutput, logger, name);\r\n\r\n    finalResult = {\r\n      success: true,\r\n      data: validatedOutput as TOutput,\r\n      ...(redirectValue && { redirect: redirectValue }),\r\n    };\r\n\r\n    await runHooks(config.onSuccessFns, () => ({\r\n      ...inputs(),\r\n      context: middlewareContext,\r\n      name,\r\n      output: redacted(validatedOutput),\r\n      duration: elapsed(),\r\n    }), \"onSuccess\");\r\n\r\n    return finalResult;\r\n  } catch (error) {\r\n    // Next.js control flow (redirect, notFound, prerendering bailouts…),\r\n    // even wrapped as the cause of another error, is not a failure:\r\n    // rethrow it without firing any hook.\r\n    rethrowIfNextInternal(error);\r\n    return await fail(resolveError(error, \"execution\"), error);\r\n  } finally {\r\n    const result = finalResult;\r\n    if (result !== undefined) {\r\n      await runHooks(config.onCompleteFns, () => ({\r\n        ...inputs(),\r\n        context: middlewareContext,\r\n        name,\r\n        result: result.success ? { ...result, data: redacted(result.data) } : result,\r\n        duration: elapsed(),\r\n      }), \"onComplete\");\r\n    }\r\n  }\r\n}\r\n","import type * as z4 from \"zod/v4/core\";\r\nimport type {\r\n  ActionClientOptions,\r\n  ActionLogger,\r\n  ActionOptions,\r\n  ServerActionResponse,\r\n  ServerAction,\r\n  HookOptions,\r\n  OnStartHook,\r\n  OnSuccessHook,\r\n  OnFailureHook,\r\n  OnCompleteHook,\r\n} from \"../types\";\r\nimport type { MiddlewareResult, ServerActionMiddleware } from \"./middleware-helpers\";\r\nimport { decodeFormData } from \"./form-data\";\r\nimport { InvalidFormDataError } from \"./errors\";\r\n\r\n/**\r\n * A form action. React calls it with `(formData)` when it is passed to\r\n * `<form action>` and with `(prevState, formData)` through `useActionState`.\r\n */\r\nexport interface FormServerAction<TOutput> {\r\n  (formData: FormData): Promise<ServerActionResponse<TOutput>>;\r\n  /**\r\n   * The same call as seen by `<form action>`, which types its handler as\r\n   * returning `void | Promise<void>` and ignores the result.\r\n   */\r\n  (formData: FormData): Promise<void>;\r\n  // Keep this signature last: TypeScript infers useActionState's state from\r\n  // the last overload.\r\n  (prevState: ServerActionResponse<TOutput>, formData: FormData): Promise<ServerActionResponse<TOutput>>;\r\n  /** Type-only marker: useFormAction sends objects and rejects form actions. */\r\n  readonly \"~formAction\"?: true;\r\n}\r\n\r\n/** The last FormData argument, wherever React placed it. */\r\nfunction findFormData(args: readonly unknown[]): FormData | undefined {\r\n  for (let index = args.length - 1; index >= 0; index--) {\r\n    const arg = args[index];\r\n    if (typeof FormData !== \"undefined\" && arg instanceof FormData) return arg;\r\n  }\r\n  return undefined;\r\n}\r\nimport { consoleLogger, resolveLogger } from \"./logger\";\r\nimport {\r\n  DEFAULT_AUTH_REDIRECT,\r\n  resolveAuthRedirect,\r\n  type ResolvedAuthRedirect,\r\n} from \"./error-handler\";\r\nimport {\r\n  runPipeline,\r\n  type ActionErrorHandler,\r\n  type HookEntry,\r\n  type PipelineConfig,\r\n  type RedirectSpec,\r\n} from \"./pipeline\";\r\nimport { DEFAULT_REDACT_KEYS, resolveRedactKeys, type RedactMatcher } from \"./redact\";\r\nimport { assertSafeRedirectPath, assertStaticRedirect } from \"./redirect\";\r\n\r\ntype InferZodOutput<T> = T extends z4.$ZodType ? z4.output<T> : never;\r\ntype InferZodInput<T> = T extends z4.$ZodType ? z4.input<T> : never;\r\n\r\n/** What the client receives as `data`: the output schema's output, or what the handler returns. */\r\ntype ResultOf<OutputSchema, Data> = OutputSchema extends z4.$ZodType ? z4.output<OutputSchema> : Data;\r\n\r\n/** Input seen after validation: the schema output, or `unknown` while no schema is attached yet. */\r\ntype ValidatedInput<InputSchema> = InputSchema extends z4.$ZodType ? z4.output<InputSchema> : unknown;\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\ntype ContextOf<R> = R extends { context: infer C } ? (C extends object ? C : never) : never;\r\n\r\n/** The context a middleware adds: `{}` when it only ever returns errors. */\r\ntype AddedContext<R> = [ContextOf<R>] extends [never] ? {} : ContextOf<R>; // eslint-disable-line @typescript-eslint/no-empty-object-type -- {} is the identity of context intersections\r\n\r\n/** The context after a middleware: the keys it returns replace the ones they shadow. */\r\ntype MergeContext<Context, Added> = Prettify<Omit<Context, keyof Added> & Added>;\r\n\r\ntype AnyMiddleware = ServerActionMiddleware<any, any, any>;\r\n\r\ntype SafeActionClientArgs = {\r\n  middlewareFns: AnyMiddleware[];\r\n  preValidationFns?: AnyMiddleware[];\r\n  inputSchema?: z4.$ZodType;\r\n  outputSchema?: z4.$ZodType;\r\n  onError?: ActionErrorHandler;\r\n  redirectConfig?: RedirectSpec;\r\n  actionName?: string;\r\n  logger?: ActionLogger;\r\n  authRedirect?: ResolvedAuthRedirect;\r\n  redactKeys?: readonly RedactMatcher[];\r\n  onStartFns?: HookEntry<OnStartHook<any, any>>[];\r\n  onSuccessFns?: HookEntry<OnSuccessHook<any, any, any>>[];\r\n  onFailureFns?: HookEntry<OnFailureHook<any, any>>[];\r\n  onCompleteFns?: HookEntry<OnCompleteHook<any, any, any>>[];\r\n};\r\n\r\n// A new client starts with an empty context; {} is the identity of context intersections.\r\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\r\nexport class ServerActionClient<Context extends object = {}, InputSchema extends z4.$ZodType | undefined = undefined, OutputSchema extends z4.$ZodType | undefined = undefined> {\r\n  readonly #args: SafeActionClientArgs;\r\n\r\n  constructor(args: SafeActionClientArgs = { middlewareFns: [] }) {\r\n    this.#args = args;\r\n  }\r\n\r\n  /**\r\n   * Copy of this client with some settings replaced. Builder methods that\r\n   * keep the type parameters return `this`, so a generic helper such as\r\n   * `withAuditHooks<C>(client: C): C` keeps the exact client type.\r\n   */\r\n  #with(patch: Partial<SafeActionClientArgs>): this {\r\n    const Client = this.constructor as new (args: SafeActionClientArgs) => this;\r\n    return new Client({ ...this.#args, ...patch });\r\n  }\r\n\r\n  /**\r\n   * Add a middleware that runs after input validation, in registration\r\n   * order. It receives the context accumulated so far and the validated input\r\n   * (`unknown` when no schema is attached yet), and returns either\r\n   * `{ context }` with the keys it adds, merged into the context, or\r\n   * `{ error }` to stop the action.\r\n   */\r\n  use<R extends MiddlewareResult<object>>(\r\n    middleware: (params: { context: Context; input: ValidatedInput<InputSchema> }) => Promise<R> | R,\r\n  ): ServerActionClient<MergeContext<Context, AddedContext<R>>, InputSchema, OutputSchema> {\r\n    return new ServerActionClient<MergeContext<Context, AddedContext<R>>, InputSchema, OutputSchema>({\r\n      ...this.#args,\r\n      middlewareFns: [...this.#args.middlewareFns, middleware as AnyMiddleware],\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Add a middleware that runs before input validation, on the raw input the\r\n   * client sent. Use it for checks that must happen first, such as\r\n   * authentication: an anonymous caller is rejected before the schema can\r\n   * tell it anything about the expected input.\r\n   *\r\n   * It must be registered before any `.use()` middleware, because it runs\r\n   * before them and cannot depend on the context they add.\r\n   */\r\n  useBeforeValidation<R extends MiddlewareResult<object>>(\r\n    middleware: (params: { context: Context; input: unknown }) => Promise<R> | R,\r\n  ): ServerActionClient<MergeContext<Context, AddedContext<R>>, InputSchema, OutputSchema> {\r\n    if (this.#args.middlewareFns.length > 0) {\r\n      throw new Error(\r\n        \"[next-action-forge] .useBeforeValidation() must be registered before any .use() middleware: \" +\r\n          \"it runs before them, so it cannot depend on the context they add.\",\r\n      );\r\n    }\r\n    return new ServerActionClient<MergeContext<Context, AddedContext<R>>, InputSchema, OutputSchema>({\r\n      ...this.#args,\r\n      preValidationFns: [...(this.#args.preValidationFns ?? []), middleware as AnyMiddleware],\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Define the input validation schema for the action.\r\n   * @param schema Input validation schema (Zod or Zod Mini)\r\n   */\r\n  inputSchema<IS extends z4.$ZodType>(schema: IS) {\r\n    return new ServerActionClient<Context, IS, OutputSchema>({\r\n      ...this.#args,\r\n      inputSchema: schema,\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Define the output validation schema for the action.\r\n   * @param schema Output validation schema (Zod or Zod Mini)\r\n   */\r\n  outputSchema<OS extends z4.$ZodType>(schema: OS) {\r\n    return new ServerActionClient<Context, InputSchema, OS>({\r\n      ...this.#args,\r\n      outputSchema: schema,\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Define a custom error handler for the action.\r\n   * @param handler Error handler function\r\n   */\r\n  onError(handler: ActionErrorHandler): this {\r\n    return this.#with({ onError: handler });\r\n  }\r\n\r\n  /**\r\n   * Define a redirect configuration for successful actions.\r\n   *\r\n   * Only same-origin paths starting with \"/\" are accepted: a static target\r\n   * outside the app throws here, and a target returned by the callback that\r\n   * is not safe is dropped and logged. Use `redirect()` from\r\n   * `next/navigation` inside the handler to leave the app.\r\n   *\r\n   * The callback may be async. After `.outputSchema()` its `result` is typed\r\n   * as the schema output; otherwise annotate it, or pass `{ redirect }` to\r\n   * `.action()` to have it typed from the handler.\r\n   *\r\n   * @param config Redirect URL, config object, or function that returns redirect config based on result\r\n   */\r\n  redirect<Data = OutputSchema extends z4.$ZodType ? z4.output<OutputSchema> : any>(\r\n    config: RedirectSpec<Data>\r\n  ): this {\r\n    assertStaticRedirect(config, \".redirect()\");\r\n    return this.#with({ redirectConfig: config as RedirectSpec });\r\n  }\r\n\r\n  /**\r\n   * Attach a semantic name to the action. The name is passed to every\r\n   * lifecycle hook (`onStart` / `onSuccess` / `onFailure` / `onComplete`)\r\n   * and is useful for structured logging and audit trails.\r\n   *\r\n   * Calling `.name()` multiple times replaces the previous value.\r\n   *\r\n   * @param actionName Human-readable identifier (e.g. `\"auth.login\"`)\r\n   */\r\n  name(actionName: string): this {\r\n    return this.#with({ actionName });\r\n  }\r\n\r\n  /**\r\n   * Register a hook fired after input validation and before the `.use()`\r\n   * middleware chain runs. Useful for request-start logging.\r\n   *\r\n   * The hook is side-effect only: its return value is ignored and it cannot\r\n   * mutate the action flow. Errors thrown inside the hook are reported\r\n   * through the client's logger but never surface to the caller.\r\n   *\r\n   * Multiple hooks can be registered; they run in registration order.\r\n   */\r\n  onStart(\r\n    hook: OnStartHook<Context, InputSchema extends z4.$ZodType ? InferZodOutput<InputSchema> : undefined>,\r\n    options: HookOptions = {},\r\n  ): this {\r\n    return this.#with({\r\n      onStartFns: [...(this.#args.onStartFns ?? []), { hook: hook as OnStartHook<any, any>, options }],\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Register a hook fired after the handler resolves successfully and\r\n   * output validation passes (but before the response is returned to the\r\n   * caller). Receives the validated `output` and the total `duration` in ms.\r\n   *\r\n   * Side-effect only; errors are reported through the client's logger.\r\n   * Multiple hooks can be registered; they run in registration order.\r\n   */\r\n  onSuccess<Output = OutputSchema extends z4.$ZodType ? InferZodOutput<OutputSchema> : unknown>(\r\n    hook: OnSuccessHook<Context, InputSchema extends z4.$ZodType ? InferZodOutput<InputSchema> : undefined, Output>,\r\n    options: HookOptions = {},\r\n  ): this {\r\n    return this.#with({\r\n      onSuccessFns: [...(this.#args.onSuccessFns ?? []), { hook: hook as OnSuccessHook<any, any, any>, options }],\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Register a hook fired when the action fails for any reason:\r\n   * input/output validation failure, middleware-returned error, or a\r\n   * thrown exception inside the handler.\r\n   *\r\n   * NOT invoked for Next.js navigation errors (redirect, notFound), which\r\n   * are re-thrown unchanged.\r\n   *\r\n   * Side-effect only; errors are reported through the client's logger.\r\n   * Multiple hooks can be registered; they run in registration order.\r\n   */\r\n  onFailure(\r\n    hook: OnFailureHook<Context, InputSchema extends z4.$ZodType ? InferZodOutput<InputSchema> : undefined>,\r\n    options: HookOptions = {},\r\n  ): this {\r\n    return this.#with({\r\n      onFailureFns: [...(this.#args.onFailureFns ?? []), { hook: hook as OnFailureHook<any, any>, options }],\r\n    });\r\n  }\r\n\r\n  /**\r\n   * Register a hook fired after the action resolves (success or failure),\r\n   * with the final `result` object available. Not fired when the action\r\n   * re-throws a Next.js navigation error.\r\n   *\r\n   * Side-effect only; errors are reported through the client's logger.\r\n   * Multiple hooks can be registered; they run in registration order.\r\n   */\r\n  onComplete<Output = OutputSchema extends z4.$ZodType ? InferZodOutput<OutputSchema> : unknown>(\r\n    hook: OnCompleteHook<Context, InputSchema extends z4.$ZodType ? InferZodOutput<InputSchema> : undefined, Output>,\r\n    options: HookOptions = {},\r\n  ): this {\r\n    return this.#with({\r\n      onCompleteFns: [...(this.#args.onCompleteFns ?? []), { hook: hook as OnCompleteHook<any, any, any>, options }],\r\n    });\r\n  }\r\n\r\n  #toPipelineConfig(\r\n    serverCodeFn: (...args: any[]) => Promise<any>,\r\n    options: ActionOptions<any> | undefined,\r\n  ): PipelineConfig {\r\n    assertStaticRedirect(options?.redirect, \"The redirect option\");\r\n    return {\r\n      inputSchema: this.#args.inputSchema,\r\n      outputSchema: this.#args.outputSchema,\r\n      preValidationFns: this.#args.preValidationFns ?? [],\r\n      middlewareFns: this.#args.middlewareFns,\r\n      onError: this.#args.onError,\r\n      serverCodeFn,\r\n      redirectConfig: options?.redirect ?? this.#args.redirectConfig,\r\n      actionName: this.#args.actionName,\r\n      logger: this.#args.logger ?? consoleLogger,\r\n      authRedirect: this.#args.authRedirect ?? DEFAULT_AUTH_REDIRECT,\r\n      redactKeys: this.#args.redactKeys ?? DEFAULT_REDACT_KEYS,\r\n      onStartFns: this.#args.onStartFns,\r\n      onSuccessFns: this.#args.onSuccessFns,\r\n      onFailureFns: this.#args.onFailureFns,\r\n      onCompleteFns: this.#args.onCompleteFns,\r\n    };\r\n  }\r\n\r\n  /**\r\n   * Define the action.\r\n   * @param serverCodeFn Code that will be executed on the server side\r\n   * @param options `redirect` after success, typed from the result (overrides `.redirect()`)\r\n   */\r\n  action<Data>(\r\n    serverCodeFn: InputSchema extends undefined\r\n      ? (context: Context) => Promise<Data>\r\n      : InputSchema extends z4.$ZodType\r\n        ? (input: InferZodOutput<InputSchema>, context: Context) => Promise<Data>\r\n        : (context: Context) => Promise<Data>,\r\n    options?: ActionOptions<ResultOf<OutputSchema, Data>>,\r\n  ): ServerAction<\r\n    InputSchema extends undefined\r\n      ? void\r\n      : InputSchema extends z4.$ZodType\r\n        ? InferZodInput<InputSchema>\r\n        : void,\r\n    ResultOf<OutputSchema, Data>\r\n  > {\r\n    const config = this.#toPipelineConfig(serverCodeFn as (...args: any[]) => Promise<any>, options);\r\n    const hasInputSchema = config.inputSchema !== undefined;\r\n    // An action without a schema takes no input: whatever the client sends is ignored.\r\n    const actionFn = (...args: unknown[]) =>\r\n      runPipeline(config, () => (hasInputSchema ? args[0] : undefined));\r\n    return actionFn as any;\r\n  }\r\n\r\n  /**\r\n   * Define a form action that accepts FormData.\r\n   * @param serverCodeFn Code that will be executed on the server side\r\n   * @param options `redirect` after success, typed from the result (overrides `.redirect()`)\r\n   */\r\n  formAction<Data>(\r\n    serverCodeFn: InputSchema extends undefined\r\n      ? (context: Context) => Promise<Data>\r\n      : InputSchema extends z4.$ZodType\r\n        ? (input: InferZodOutput<InputSchema>, context: Context) => Promise<Data>\r\n        : (context: Context) => Promise<Data>,\r\n    options?: ActionOptions<ResultOf<OutputSchema, Data>>,\r\n  ): FormServerAction<ResultOf<OutputSchema, Data>> {\r\n    const config = this.#toPipelineConfig(serverCodeFn as (...args: any[]) => Promise<any>, options);\r\n    const schema = config.inputSchema;\r\n    // React calls a <form action> with (formData) and useActionState with\r\n    // (prevState, formData). The previous state is client-controlled and\r\n    // deliberately ignored; without a schema the FormData is not decoded.\r\n    const formActionFn = (...args: unknown[]) =>\r\n      runPipeline(config, () => {\r\n        if (!schema) return undefined;\r\n        const formData = findFormData(args);\r\n        if (!formData) throw new InvalidFormDataError();\r\n        return decodeFormData(formData, schema);\r\n      });\r\n    return formActionFn as FormServerAction<ResultOf<OutputSchema, Data>>;\r\n  }\r\n}\r\n\r\n/** Any client, whatever its context and schemas: the constraint for helpers that decorate clients. */\r\nexport type AnyServerActionClient = ServerActionClient<any, any, any>;\r\n\r\n/**\r\n * Create a new action client. Every client derived from it through the\r\n * builder methods shares these options.\r\n */\r\nexport function createActionClient(options: ActionClientOptions = {}) {\r\n  if (options.authRedirect) {\r\n    assertSafeRedirectPath(options.authRedirect.to, \"authRedirect.to\");\r\n  }\r\n  return new ServerActionClient({\r\n    middlewareFns: [],\r\n    logger: resolveLogger(options.logger),\r\n    authRedirect: resolveAuthRedirect(options.authRedirect),\r\n    redactKeys: resolveRedactKeys(options.redact),\r\n  });\r\n}\r\n","// Preprocessors for form fields, meant for your own Zod flavour's\r\n// preprocess, so they work with Zod and Zod Mini alike:\r\n//\r\n//   nickname: z.preprocess(emptyToNull, z.string().nullable())\r\n//   age: z.preprocess(emptyToUndefined, z.coerce.number().int().optional())\r\n//\r\n// Without them an empty field reaches the schema as \"\": z.coerce.number()\r\n// turns it into 0 and a nullable string stores \"\" instead of null.\r\n\r\nfunction isBlank(value: unknown): boolean {\r\n  return typeof value === \"string\" && value.trim() === \"\";\r\n}\r\n\r\n/** Turn an empty or whitespace-only string into `null`; other values pass through. */\r\nexport function emptyToNull(value: unknown): unknown {\r\n  return isBlank(value) ? null : value;\r\n}\r\n\r\n/** Turn an empty or whitespace-only string into `undefined`; other values pass through. */\r\nexport function emptyToUndefined(value: unknown): unknown {\r\n  return isBlank(value) ? undefined : value;\r\n}\r\n","import type { ServerActionError } from '../types';\r\n\r\n/**\r\n * What a middleware returns: the context it adds (merged into the context\r\n * accumulated so far), or an error that stops the action.\r\n */\r\nexport type MiddlewareResult<NextContext extends object = {}> = // eslint-disable-line @typescript-eslint/no-empty-object-type -- {} is the identity of context intersections\r\n  | { context: NextContext; error?: undefined }\r\n  | { error: ServerActionError; context?: undefined };\r\n\r\n/**\r\n * A server action middleware.\r\n *\r\n * @template Context - The context the middleware receives (what earlier middleware produced).\r\n * @template Input - The input it receives: the raw input before validation, the validated one after.\r\n * @template NextContext - The context it returns. Only the keys it adds are needed:\r\n *   the result is merged into `Context`.\r\n */\r\nexport type ServerActionMiddleware<Context = any, Input = unknown, NextContext extends object = Context & object> = (params: {\r\n  context: Context;\r\n  input: Input;\r\n}) => Promise<MiddlewareResult<NextContext>> | MiddlewareResult<NextContext>;\r\n\r\n/**\r\n * Declare a middleware's types explicitly, for middleware built by a factory\r\n * or shared between clients.\r\n *\r\n * Inline middleware passed to `.use()` does not need it: its `context` is\r\n * already typed and the context it returns is inferred.\r\n *\r\n * @template TOutputContext - The context the middleware returns (what it adds).\r\n * @template TInput - The input it reads. Defaults to `unknown`.\r\n * @template TContext - The context it requires from earlier middleware.\r\n *   `.use()` rejects a client whose context does not provide it. Defaults to\r\n *   `any`, which accepts every client but leaves `context` untyped.\r\n *\r\n * @example\r\n * ```typescript\r\n * interface AuthContext { userId: string; permissions: Set<string> }\r\n *\r\n * const authMiddleware = createTypedMiddleware<AuthContext>(async () => {\r\n *   const session = await getSession();\r\n *   if (!session) return { error: { message: \"Unauthorized\", code: \"AUTH_ERROR\" } };\r\n *   return { context: { userId: session.userId, permissions: session.permissions } };\r\n * });\r\n *\r\n * // Requires AuthContext: using it on a client without authMiddleware is a type error.\r\n * const requirePermission = (permission: string) =>\r\n *   createTypedMiddleware<{}, unknown, AuthContext>(async ({ context }) =>\r\n *     context.permissions.has(permission)\r\n *       ? { context: {} }\r\n *       : { error: { message: \"Forbidden\", code: \"FORBIDDEN\" } },\r\n *   );\r\n *\r\n * const adminClient = baseClient.use(authMiddleware).use(requirePermission(\"admin\"));\r\n * ```\r\n */\r\nexport function createTypedMiddleware<TOutputContext extends object, TInput = unknown, TContext = any>(\r\n  middlewareFn: (params: {\r\n    context: TContext;\r\n    input: TInput;\r\n  }) => Promise<MiddlewareResult<TOutputContext>> | MiddlewareResult<TOutputContext>\r\n): ServerActionMiddleware<TContext, TInput, TOutputContext> {\r\n  return middlewareFn;\r\n}\r\n"],"mappings":";;;;;;;;;;AAAA,SAAS,iBAAiB;;;ACcnB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,cAAc;AACZ;AAAA,MACE;AAAA,IACF;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAG/C,YAAY,UAAqB;AAC/B,UAAM,kDAAkD,EAAE,OAAO,SAAS,CAAC;AAC3E,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS;AAAA,EACzB;AACF;;;AC5BO,IAAM,gBAA8B;AAAA,EACzC,OAAO,IAAI,SAAS,QAAQ,MAAM,GAAG,IAAI;AAAA,EACzC,MAAM,IAAI,SAAS,QAAQ,KAAK,GAAG,IAAI;AACzC;AAEA,IAAM,eAA6B;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC;AAAA,EACd,MAAM,MAAM;AAAA,EAAC;AACf;AAEO,SAAS,cAAc,QAAwD;AACpF,MAAI,WAAW,MAAO,QAAO;AAC7B,SAAO,UAAU;AACnB;AAGO,SAAS,eAAe,YAAwC;AACrE,SAAO,aAAa,eAAe,U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