{"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;AACD,KAAI,CAAC,oBAAoB,OAAO,KAAK,iBAAiB,CAAC,WAAW,EACjE;CAGD,MAAM,cAA8D,EAAE;CAEtE,SAAS,OAAO,IAAyB,QAAkB,EAAE,EAAE;AAC9D,OAAK,MAAM,OAAO,OAAO,KAAK,GAAG,EAAE;AAElC,OAAI,QAAQ,aAAa,MAAM,QAAQ,GAAG,KAAK,EAAE;IAChD,IAAI,MAAM;AAGV,SAAK,IAAI,IAAI,GAAG,IAAI,MAAM,SAAS,GAAG,KAAK;KAC1C,MAAM,IAAI,MAAM;AAChB,SAAI,OAAO,EAAE;AACb,WAAM,IAAI;;IAIX,MAAM,OAAO,MAAM,GAAG,GAAG,IAAI;AAE7B,QAAI,QAAQ;KACX,MAAM;KACN,SAAS,GAAG,KAAK,KAAK,OAAO,UAAU,IAAI;KAC3C;AACD;;AAID,OAAI,OAAO,GAAG,SAAS,YAAY,GAAG,QAAQ,CAAC,MAAM,QAAQ,GAAG,KAAK,CACpE,QAAO,GAAG,MAAM,CAAC,GAAG,OAAO,IAAI,CAAC;;;AAKnC,QAAO,oBAAoB,EAAE,CAAC;AAC9B,QAAO"}