{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { ValidationErrors } from \"next-safe-action\";\nimport type { FieldError, FieldErrors } from \"react-hook-form\";\nimport type { ErrorMapperProps } from \"./index.types\";\nimport type { InferOutputOrDefault, StandardSchemaV1 } from \"./standard-schema\";\n\n/**\n * Maps a validation errors object to an object of `FieldErrors` compatible with react-hook-form.\n * You should only call this function directly for advanced use cases, and prefer exported hooks.\n */\nexport function mapToHookFormErrors<Schema extends StandardSchemaV1 | undefined>(\n\tvalidationErrors: ValidationErrors<Schema> | undefined,\n\tprops?: ErrorMapperProps\n) {\n\tif (!validationErrors || Object.keys(validationErrors).length === 0) {\n\t\treturn undefined;\n\t}\n\n\tconst fieldErrors: FieldErrors<InferOutputOrDefault<Schema, any>> = {};\n\n\tfunction mapper(ve: Record<string, any>, paths: string[] = []) {\n\t\tfor (const key of Object.keys(ve)) {\n\t\t\t// `_errors` arrays are the leaf values: extract them as FieldError objects.\n\t\t\tif (key === \"_errors\" && Array.isArray(ve[key])) {\n\t\t\t\tlet ref = fieldErrors as Record<string, any>;\n\n\t\t\t\t// Build nested path structure.\n\t\t\t\tfor (let i = 0; i < paths.length - 1; i++) {\n\t\t\t\t\tconst p = paths[i]!;\n\t\t\t\t\tref[p] ??= {};\n\t\t\t\t\tref = ref[p];\n\t\t\t\t}\n\n\t\t\t\t// The actual field path is the last segment. Root-level errors use \"root\".\n\t\t\t\tconst path = paths.at(-1) ?? \"root\";\n\n\t\t\t\tref[path] = {\n\t\t\t\t\ttype: \"validate\",\n\t\t\t\t\tmessage: ve[key].join(props?.joinBy ?? \" \"),\n\t\t\t\t} as FieldError;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Recurse into nested objects (but not arrays or primitives).\n\t\t\tif (typeof ve[key] === \"object\" && ve[key] && !Array.isArray(ve[key])) {\n\t\t\t\tmapper(ve[key], [...paths, key]);\n\t\t\t}\n\t\t}\n\t}\n\n\tmapper(validationErrors ?? {});\n\treturn fieldErrors;\n}\n\nexport type * from \"./index.types\";\n"],"mappings":";;;;;AASA,SAAgB,oBACf,kBACA,OACC;CACD,IAAI,CAAC,oBAAoB,OAAO,KAAK,gBAAgB,CAAC,CAAC,WAAW,GACjE;CAGD,MAAM,cAA8D,CAAC;CAErE,SAAS,OAAO,IAAyB,QAAkB,CAAC,GAAG;EAC9D,KAAK,MAAM,OAAO,OAAO,KAAK,EAAE,GAAG;GAElC,IAAI,QAAQ,aAAa,MAAM,QAAQ,GAAG,IAAI,GAAG;IAChD,IAAI,MAAM;IAGV,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,SAAS,GAAG,KAAK;KAC1C,MAAM,IAAI,MAAM;KAChB,IAAI,OAAO,CAAC;KACZ,MAAM,IAAI;IACX;IAGA,MAAM,OAAO,MAAM,GAAG,EAAE,KAAK;IAE7B,IAAI,QAAQ;KACX,MAAM;KACN,SAAS,GAAG,IAAI,CAAC,KAAK,OAAO,UAAU,GAAG;IAC3C;IACA;GACD;GAGA,IAAI,OAAO,GAAG,SAAS,YAAY,GAAG,QAAQ,CAAC,MAAM,QAAQ,GAAG,IAAI,GACnE,OAAO,GAAG,MAAM,CAAC,GAAG,OAAO,GAAG,CAAC;EAEjC;CACD;CAEA,OAAO,oBAAoB,CAAC,CAAC;CAC7B,OAAO;AACR"}