@railway-ts/pipelines 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +811 -0
  2. package/dist/composition/index.cjs +72 -0
  3. package/dist/composition/index.cjs.map +1 -0
  4. package/dist/composition/index.d.cts +286 -0
  5. package/dist/composition/index.d.ts +286 -0
  6. package/dist/composition/index.mjs +65 -0
  7. package/dist/composition/index.mjs.map +1 -0
  8. package/dist/index-BdfKTZ7O.d.cts +799 -0
  9. package/dist/index-BdfKTZ7O.d.ts +799 -0
  10. package/dist/index.cjs +1074 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +3 -0
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.mjs +969 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/option/index.cjs +111 -0
  17. package/dist/option/index.cjs.map +1 -0
  18. package/dist/option/index.d.cts +1 -0
  19. package/dist/option/index.d.ts +1 -0
  20. package/dist/option/index.mjs +93 -0
  21. package/dist/option/index.mjs.map +1 -0
  22. package/dist/result/index.cjs +178 -0
  23. package/dist/result/index.cjs.map +1 -0
  24. package/dist/result/index.d.cts +1 -0
  25. package/dist/result/index.d.ts +1 -0
  26. package/dist/result/index.mjs +152 -0
  27. package/dist/result/index.mjs.map +1 -0
  28. package/dist/schema/index.cjs +794 -0
  29. package/dist/schema/index.cjs.map +1 -0
  30. package/dist/schema/index.d.cts +1867 -0
  31. package/dist/schema/index.d.ts +1867 -0
  32. package/dist/schema/index.mjs +735 -0
  33. package/dist/schema/index.mjs.map +1 -0
  34. package/examples/complete-pipelines/async-launch.ts +128 -0
  35. package/examples/complete-pipelines/async.ts +119 -0
  36. package/examples/complete-pipelines/hill-clohessy-wiltshire.ts +218 -0
  37. package/examples/complete-pipelines/hohmann-transfer.ts +159 -0
  38. package/examples/composition/advanced-composition.ts +32 -0
  39. package/examples/composition/curry-basics.ts +24 -0
  40. package/examples/composition/tupled-basics.ts +26 -0
  41. package/examples/index.ts +47 -0
  42. package/examples/interop/interop-examples.ts +110 -0
  43. package/examples/option/option-examples.ts +63 -0
  44. package/examples/result/result-examples.ts +110 -0
  45. package/examples/schema/basic.ts +78 -0
  46. package/examples/schema/union.ts +301 -0
  47. package/package.json +100 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/result/result.ts","../src/option/option.ts","../src/composition/pipe.ts","../src/composition/flow.ts","../src/composition/curry.ts","../src/composition/uncurry.ts","../src/composition/tupled.ts","../src/composition/untupled.ts","../src/schema/core.ts","../src/schema/utils.ts","../src/schema/string.ts","../src/schema/array.ts","../src/schema/number.ts","../src/schema/parsers.ts","../src/schema/date.ts","../src/schema/boolean.ts","../src/schema/union.ts","../src/schema/enum.ts","../src/schema/bigint.ts"],"names":["map","flatMap","bimap","filter","unwrap","unwrapOr","unwrapOrElse","combine","match","tap","min","max","date"],"mappings":";;;AAOO,IAAM,YAAA,GAAe,OAAO,cAAc,CAAA;AAkC1C,SAAS,GAAiB,KAAA,EAAwB;AACvD,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,IAAA;AAAA,IACJ,KAAA;AAAA,IACA,CAAC,YAAY,GAAG;AAAA,GAClB;AACF;AAWO,SAAS,IAAO,KAAA,EAA4B;AACjD,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,CAAC,YAAY,GAAG,OAAA,EAAQ;AACrD;AAeO,SAAS,KACd,MAAA,EAKA;AACA,EAAA,OAAO,MAAA,CAAO,EAAA;AAChB;AAeO,SAAS,MACd,MAAA,EAKA;AACA,EAAA,OAAO,CAAC,MAAA,CAAO,EAAA;AACjB;AAaO,SAAS,GAAA,CAAa,QAAsB,EAAA,EAAmC;AACpF,EAAA,OAAO,OAAO,EAAA,GAAK,EAAA,CAAG,GAAG,MAAA,CAAO,KAAK,CAAC,CAAA,GAAI,MAAA;AAC5C;AAaO,SAAS,MAAA,CAAgB,QAAsB,EAAA,EAAmC;AACvF,E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AAA,CAAW,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AACrE,MAAA,OAAO,GAAA,CAAI,CAAC,EAAE,IAAA,EAAM,SAAS,OAAA,IAAW,cAAA,EAAgB,CAAC,CAAA;AAAA,IAC3D;AAEA,IAAA,IAAI,cAAA,IAAkB,cAAA,CAAe,QAAA,CAAS,KAAmB,CAAA,EAAG;AAClE,MAAA,MAAM,cAAA,GAAiB,CAAA,iDAAA,CAAA;AACvB,MAAA,OAAO,GAAA,CAAI,CAAC,EAAE,IAAA,EAAM,OAAA,EAAS,GAAG,OAAA,IAAW,cAAc,CAAA,CAAA,EAAI,CAAC,CAAA;AAAA,IAChE;AAEA,IAAA,OAAO,GAAG,KAAmB,CAAA;AAAA,EAC/B,CAAA;AACF;;;ACpCO,SAAS,MAAA,CAAO,UAAkB,kBAAA,EAAgD;AACvF,EAAA,OAAO,CAAC,KAAA,EAAO,IAAA,GAAO,EAAC,KAAM;AAC3B,IAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,MAAA,OAAO,IAAI,CAAC,EAAE,IAAA,EAAM,OAAA,EAAS,CAAC,CAAA;AAAA,IAChC;AACA,IAAA,OAAO,GAAG,KAAK,CAAA;AAAA,EACjB,CAAA;AACF","file":"index.cjs","sourcesContent":["import { none, some, type Option } from '@/option';\n\n/**\n * Symbol used to identify Result objects.\n *\n * @internal\n */\nexport const RESULT_BRAND = Symbol('RESULT_BRAND');\n\n/**\n * Represents a Result type.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * const error: Result<number, string> = error(\"An error occurred\");\n *\n * @param T - The type of the value contained in the Ok variant\n * @param E - The type of the error contained in the Error variant\n * @returns A Result containing a value or an error\n */\nexport type Result<T, E> =\n | {\n readonly ok: true;\n readonly value: T;\n readonly [RESULT_BRAND]: 'ok';\n }\n | {\n readonly ok: false;\n readonly error: E;\n readonly [RESULT_BRAND]: 'error';\n };\n\n/**\n * Creates a Result containing a value.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n *\n * @param value - The value to contain\n * @returns A Result containing the value\n */\nexport function ok<T, E = never>(value: T): Result<T, E> {\n return {\n ok: true,\n value,\n [RESULT_BRAND]: 'ok',\n };\n}\n\n/**\n * Creates a Result containing an error.\n *\n * @example\n * const error: Result<number, string> = err(\"An error occurred\");\n *\n * @param error - The error to contain\n * @returns A Result containing the error\n */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error, [RESULT_BRAND]: 'error' };\n}\n\n/**\n * Type guard that checks if a Result is an Ok variant containing a value.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * if (isOk(result)) {\n * // TypeScript knows result.value exists here\n * console.log(result.value);\n * }\n *\n * @param result - The result to check\n * @returns A type predicate indicating if the result is an Ok variant\n */\nexport function isOk<T, E>(\n result: Result<T, E>,\n): result is {\n readonly ok: true;\n readonly value: T;\n readonly [RESULT_BRAND]: 'ok';\n} {\n return result.ok;\n}\n\n/**\n * Type guard that checks if a Result is an Error variant.\n *\n * @example\n * const result: Result<number, string> = err(\"error\");\n * if (isErr(result)) {\n * // TypeScript knows result.error exists here\n * console.log(result.error);\n * }\n *\n * @param result - The result to check\n * @returns A type predicate indicating if the result is an Error variant\n */\nexport function isErr<T, E>(\n result: Result<T, E>,\n): result is {\n readonly ok: false;\n readonly error: E;\n readonly [RESULT_BRAND]: 'error';\n} {\n return !result.ok;\n}\n\n/**\n * Maps the value inside a Result using a transformation function.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * const transformed: Result<string, string> = map(result, (value) => value.toString());\n *\n * @param result - The Result to transform\n * @param fn - The function to apply to the contained value\n * @returns A new Result containing the transformed value, or the original error if the input was an error\n */\nexport function map<T, E, U>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return result.ok ? ok(fn(result.value)) : result;\n}\n\n/**\n * Maps the error inside a Result using a transformation function.\n *\n * @example\n * const result: Result<number, string> = err(\"error\");\n * const transformed: Result<number, Error> = mapErr(result, (err) => new Error(err));\n *\n * @param result - The Result to transform\n * @param fn - The function to apply to the contained error\n * @returns A new Result containing the transformed error, or the original value if the input was ok\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return result.ok ? result : err(fn(result.error));\n}\n\n/**\n * Maps the value inside a Result using a transformation function that returns a Result.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * const transformed: Result<string, string> = flatMap(result, (value) => ok(value.toString()));\n *\n * @param result - The Result to transform\n * @param fn - The function to apply to the contained value, returning a Result\n * @returns The Result returned by the transformation function, or the original error if the input was an error\n */\nexport function flatMap<T, E, U>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return result.ok ? fn(result.value) : result;\n}\n\n/**\n * Maps both the value and error of a Result using separate transformation functions.\n * This is equivalent to chaining map and mapErr, but more concise.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * const transformed = bimap(\n * result,\n * (value) => value.toString(),\n * (error) => new Error(error)\n * ); // ok(\"123\")\n *\n * const error: Result<number, string> = err(\"failed\");\n * const transformed2 = bimap(\n * error,\n * (value) => value.toString(),\n * (error) => new Error(error)\n * ); // err(Error(\"failed\"))\n *\n * @param result - The Result to transform\n * @param okFn - The function to apply to the contained value if Ok\n * @param errFn - The function to apply to the contained error if Err\n * @returns A new Result with both branches transformed\n */\nexport function bimap<T, E, U, F>(result: Result<T, E>, okFn: (value: T) => U, errFn: (error: E) => F): Result<U, F> {\n return result.ok ? ok(okFn(result.value)) : err(errFn(result.error));\n}\n\n/**\n * Filters a Result based on a predicate function.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * const filtered: Result<number, string> = filter(result, value => value > 100, \"Value too small\"); // still Ok(123)\n * const filtered2: Result<number, string> = filter(result, value => value > 200, \"Value too small\"); // Err(\"Value too small\")\n *\n * @param result - The Result to filter\n * @param predicate - A function that determines if the value should be kept\n * @param error - The error to return if the predicate fails\n * @returns The original Result if it contains a value that satisfies the predicate, otherwise an Error\n */\nexport function filter<T, E>(result: Result<T, E>, predicate: (value: T) => boolean, error: E): Result<T, E> {\n return result.ok && predicate(result.value) ? result : err(error);\n}\n\n/**\n * Unwraps the value inside a Result, throwing an error if the Result is an error.\n *\n * @remarks\n * This function is intended for prototyping only and should not be used in production.\n * In production code, prefer using pattern matching or `unwrapOr` to handle both Ok and Error cases safely.\n *\n * @example\n * const result: Result<number, string> = ok(123);\n * const value: number = unwrap(result);\n *\n * // With custom error message\n * try {\n * const badResult: Result<number, string> = err(\"Invalid data\");\n * unwrap(badResult, \"Custom error message\");\n * } catch (error) {\n * // Error will contain \"Custom error message\" instead of the default\n * }\n *\n * @param result - The Result to unwrap\n * @param errorMsg - Optional custom error message to use if Result is an error\n * @returns The contained value\n * @throws If the Result is an error\n */\nexport function unwrap<T, E>(result: Result<T, E>, errorMsg?: string): T {\n if (result.ok) {\n return result.value;\n } else {\n throw new Error(errorMsg || `Cannot unwrap an error Result: ${String(result.error)}`);\n }\n}\n\n/**\n * Unwraps the value inside a Result, providing a default value if the Result is an error.\n *\n * @example\n * const result: Result<number, string> = err(\"error\");\n * const value: number = unwrapOr(result, 123);\n *\n * @param result - The Result to unwrap\n * @param defaultValue - The value to return if the Result is an error\n * @returns The contained value, or the default value if the Result is an error\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n return result.ok ? result.value : defaultValue;\n}\n\n/**\n * Unwraps the value inside a Result, calling a function to generate a default value if the Result is an error.\n * Unlike unwrapOr, this only computes the default when needed.\n *\n * @example\n * const result: Result<number, string> = err(\"error\");\n * const value = unwrapOrElse(result, () => expensiveComputation());\n *\n * @param result - The Result to unwrap\n * @param defaultFn - A function that returns a default value if the Result is an error\n * @returns The contained value, or the result of calling defaultFn if the Result is an error\n */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, defaultFn: () => T): T {\n return result.ok ? result.value : defaultFn();\n}\n\n/**\n * Combines an array of Results into a single Result containing an array of values.\n * Returns an Error if any Result in the array is an Error, using the first encountered error.\n * If an empty array is provided, returns `ok([])` (an Ok containing an empty array).\n *\n * @example\n * const results = [ok(1), ok(2), ok(3)];\n * const combined = combine(results); // ok([1, 2, 3])\n *\n * const withError = [ok(1), err(\"error\"), ok(3)];\n * const result = combine(withError); // err(\"error\")\n *\n * const emptyResults = [];\n * const emptyResult = combine(emptyResults); // ok([])\n *\n * @param results - An array of Results to combine\n * @returns A Result containing an array of all values if all inputs are Ok, or the first Error if any input is an Error\n */\n\n// Tuple-preserving overloads with error type unions\nexport function combine<T1, E1>(results: readonly [Result<T1, E1>]): Result<[T1], E1>;\nexport function combine<T1, E1, T2, E2>(results: readonly [Result<T1, E1>, Result<T2, E2>]): Result<[T1, T2], E1 | E2>;\nexport function combine<T1, E1, T2, E2, T3, E3>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>],\n): Result<[T1, T2, T3], E1 | E2 | E3>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>, Result<T4, E4>],\n): Result<[T1, T2, T3, T4], E1 | E2 | E3 | E4>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>, Result<T4, E4>, Result<T5, E5>],\n): Result<[T1, T2, T3, T4, T5], E1 | E2 | E3 | E4 | E5>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>, Result<T4, E4>, Result<T5, E5>, Result<T6, E6>],\n): Result<[T1, T2, T3, T4, T5, T6], E1 | E2 | E3 | E4 | E5 | E6>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7], E1 | E2 | E3 | E4 | E5 | E6 | E7>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7, T8, E8>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n Result<T8, E8>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7, T8], E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7, T8, E8, T9, E9>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n Result<T8, E8>,\n Result<T9, E9>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7, T8, T9], E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | E9>;\nexport function combine<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7, T8, E8, T9, E9, T10, E10>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n Result<T8, E8>,\n Result<T9, E9>,\n Result<T10, E10>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | E9 | E10>;\nexport function combine<T, E>(results: readonly Result<T, E>[]): Result<T[], E>;\nexport function combine<T, E>(results: readonly Result<T, E>[]): Result<T[], E> {\n const values: T[] = [];\n\n for (const result of results) {\n if (!result.ok) return result;\n values.push(result.value);\n }\n\n return ok(values);\n}\n\n/**\n * Combines an array of Results into a single Result containing an array of values.\n * Unlike combine, this collects all errors instead of returning just the first one.\n * If all Results are Ok, returns an Ok containing an array of all values.\n * If any Results are Error, returns an Error containing an array of all errors.\n *\n * @example\n * const results = [ok(1), ok(2), ok(3)];\n * const combined = combineAll(results); // ok([1, 2, 3])\n *\n * const withErrors = [ok(1), err(\"error1\"), ok(3), err(\"error2\")];\n * const result = combineAll(withErrors); // err([\"error1\", \"error2\"])\n *\n * const emptyResults = [];\n * const emptyResult = combineAll(emptyResults); // ok([])\n *\n * @param results - An array of Results to combine\n * @returns A Result containing an array of all values if all inputs are Ok, or an array of all errors if any input is an Error\n */\n\n// Tuple-preserving overloads with error arrays\nexport function combineAll<T1, E1>(results: readonly [Result<T1, E1>]): Result<[T1], E1[]>;\nexport function combineAll<T1, E1, T2, E2>(\n results: readonly [Result<T1, E1>, Result<T2, E2>],\n): Result<[T1, T2], (E1 | E2)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>],\n): Result<[T1, T2, T3], (E1 | E2 | E3)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>, Result<T4, E4>],\n): Result<[T1, T2, T3, T4], (E1 | E2 | E3 | E4)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>, Result<T4, E4>, Result<T5, E5>],\n): Result<[T1, T2, T3, T4, T5], (E1 | E2 | E3 | E4 | E5)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6>(\n results: readonly [Result<T1, E1>, Result<T2, E2>, Result<T3, E3>, Result<T4, E4>, Result<T5, E5>, Result<T6, E6>],\n): Result<[T1, T2, T3, T4, T5, T6], (E1 | E2 | E3 | E4 | E5 | E6)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7], (E1 | E2 | E3 | E4 | E5 | E6 | E7)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7, T8, E8>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n Result<T8, E8>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7, T8], (E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7, T8, E8, T9, E9>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n Result<T8, E8>,\n Result<T9, E9>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7, T8, T9], (E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | E9)[]>;\nexport function combineAll<T1, E1, T2, E2, T3, E3, T4, E4, T5, E5, T6, E6, T7, E7, T8, E8, T9, E9, T10, E10>(\n results: readonly [\n Result<T1, E1>,\n Result<T2, E2>,\n Result<T3, E3>,\n Result<T4, E4>,\n Result<T5, E5>,\n Result<T6, E6>,\n Result<T7, E7>,\n Result<T8, E8>,\n Result<T9, E9>,\n Result<T10, E10>,\n ],\n): Result<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], (E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | E9 | E10)[]>;\nexport function combineAll<T, E>(results: readonly Result<T, E>[]): Result<T[], E[]>;\nexport function combineAll<T, E>(results: readonly Result<T, E>[]): Result<T[], E[]> {\n const errors: E[] = [];\n const values: T[] = [];\n\n for (const result of results) {\n if (result.ok) {\n values.push(result.value);\n } else {\n errors.push(result.error);\n }\n }\n\n return errors.length > 0 ? err(errors) : ok(values);\n}\n\n/**\n * Pattern matches on a Result to handle both Ok and Error cases.\n *\n * @example\n * const result = ok(42);\n * const message = match(result, {\n * ok: (value) => `Got value: ${value}`,\n * err: (error) => `Got error: ${error}`\n * }); // \"Got value: 42\"\n *\n * @param result - The Result to match against\n * @param patterns - An object containing handler functions for Ok and Error cases\n * @returns The result of calling the appropriate handler function\n */\nexport function match<T, E, R>(\n result: Result<T, E>,\n patterns: {\n ok: (value: T) => R;\n err: (error: E) => R;\n },\n): R {\n if (isOk(result)) {\n const okFn = patterns.ok;\n return okFn(result.value);\n } else {\n const errFn = patterns.err;\n return errFn(result.error);\n }\n}\n\n/**\n * Executes a callback with the value if the Result is Ok, without changing the Result.\n * Useful for side effects like logging while maintaining a processing chain.\n *\n * @example\n * const finalResult = pipe(\n * ok(123),\n * r => map(r, x => x * 2),\n * r => tap(r, x => console.log(`Value: ${x}`)), // Logs but doesn't change the Result\n * r => filter(r, x => x > 200, \"Value too small\")\n * );\n *\n * @param result - The Result to tap into\n * @param fn - The function to execute with the value if Ok\n * @returns The original Result unchanged\n */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> {\n if (isOk(result)) {\n const callback = fn;\n callback(result.value);\n }\n return result;\n}\n\n/**\n * Executes a callback with the error if the Result is an Error, without changing the Result.\n * Useful for side effects like logging while maintaining a processing chain.\n *\n * @example\n * const finalResult = pipe(\n * err(\"something went wrong\"),\n * r => tapErr(r, e => console.error(`Error: ${e}`)), // Logs but doesn't change the Result\n * r => mapErr(r, e => new Error(e))\n * );\n *\n * @param result - The Result to tap into\n * @param fn - The function to execute with the error if Error\n * @returns The original Result unchanged\n */\nexport function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> {\n if (isErr(result)) {\n const callback = fn;\n callback(result.error);\n }\n return result;\n}\n\n/**\n * Converts a Result to an Option.\n * If the Result is Ok, returns a Some variant with the value.\n * If the Result is an Error, returns a None variant.\n *\n * @example\n * import { some, none } from \"@/option\";\n *\n * const option1 = mapToOption(ok(123)); // some(123)\n * const option2 = mapToOption(err(\"error\")); // none()\n *\n * @param result - The Result to convert\n * @returns An Option containing the value if Ok, or None if Error\n */\nexport function mapToOption<T, E>(result: Result<T, E>): Option<T> {\n return result.ok ? some(result.value) : none();\n}\n\n/**\n * Safely executes a function that might throw and converts the result into a Result type.\n * If the function executes successfully, returns an Ok variant with the return value.\n * If the function throws an error, returns an Error variant containing the error message as a string.\n *\n * @example\n * const parseJson = (str: string) => fromTry(() => JSON.parse(str));\n *\n * const validResult = parseJson('{\"name\":\"John\"}'); // ok({ name: 'John' })\n * const invalidResult = parseJson('invalid json'); // err(\"Unexpected token...\")\n *\n * @param f - The function to execute\n * @returns A Result containing either the function's return value or the error message\n */\nexport function fromTry<T>(f: () => T): Result<T, string> {\n try {\n return ok(f());\n } catch (error) {\n return err(error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Safely executes a function that might throw and converts the result into a Result type.\n * Unlike fromTry, this preserves the full Error object instead of just the message.\n * Use this when you need access to error stack traces or custom error properties.\n *\n * @example\n * const result = fromTryWithError(() => JSON.parse('invalid'));\n * if (isErr(result)) {\n * console.log(result.error.stack); // Access to full stack trace\n * }\n *\n * @param f - The function to execute\n * @returns A Result containing either the function's return value or the full Error object\n */\nexport function fromTryWithError<T>(f: () => T): Result<T, Error> {\n try {\n return ok(f());\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Converts a Promise to a Result, capturing any errors that occur during promise resolution.\n * Returns error messages as strings for simplicity.\n *\n * @example\n * const result = await fromPromise(fetch('https://api.example.com/data'));\n * if (isErr(result)) {\n * console.log(result.error); // Error message as string\n * }\n *\n * @param promise - The Promise to convert\n * @returns A Promise that resolves to a Result with string error messages\n */\nexport async function fromPromise<T>(promise: Promise<T>): Promise<Result<T, string>> {\n try {\n const value = await promise;\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Converts a Promise to a Result, preserving the full error object or custom error type.\n * Use this when you need access to error stack traces, custom properties, or specific error types.\n *\n * @example\n * // With default error handling (preserves full error)\n * const result = await fromPromiseWithError(fetch('https://api.example.com/data'));\n *\n * @example\n * // With specific error type and transformer\n * type ApiError = { code: number; message: string };\n *\n * const result = await fromPromiseWithError<Response, ApiError>(\n * fetch('https://api.example.com/data'),\n * (error) => ({\n * code: error instanceof Error ? 500 : 400,\n * message: error instanceof Error ? error.message : String(error)\n * })\n * );\n *\n * @param promise - The Promise to convert\n * @param errorFn - Optional function to transform caught errors to the expected error type\n * @returns A Promise that resolves to a Result\n */\nexport async function fromPromiseWithError<T, E = unknown>(\n promise: Promise<T>,\n errorFn: (error: unknown) => E = (error) => error as unknown as E,\n): Promise<Result<T, E>> {\n try {\n const value = await promise;\n return ok(value);\n } catch (error) {\n return err(errorFn(error));\n }\n}\n\n/**\n * Converts a Result to a Promise.\n *\n * @example\n * const result = ok(123);\n * const promise = toPromise(result);\n * const value = await promise; // 123\n *\n * @param result - The Result to convert\n * @returns A Promise that resolves to the value if Ok, or rejects with the error if Error\n */\nexport function toPromise<T, E>(result: Result<T, E>): Promise<T> {\n return result.ok ? Promise.resolve(result.value) : Promise.reject(result.error);\n}\n\n/**\n * Chains an asynchronous operation that returns a Result.\n *\n * @remarks\n * This function is the async counterpart to {@link flatMap}. It accepts either\n * a `Result` or a `Promise<Result>` and a step function that may be synchronous\n * or asynchronous, but must return a `Result` (or `Promise<Result>`). If the\n * input is an Ok, the step is invoked and awaited; if the input is an Err, the\n * same error is returned and the step is not called.\n *\n * This design keeps your core pipeline synchronous in structure while enabling\n * async effects at the boundaries (e.g., database, HTTP) without nested flows.\n *\n * @example\n * // Using with a Result input and async step\n * const r1 = await andThen(ok(2 as const), async (n) => ok(n * 3)); // Ok(6)\n *\n * @example\n * // Using with a Promise<Result> input (e.g., previous async step)\n * const r2 = await andThen(fromPromise(Promise.resolve(2)), async (n) => ok(n * 3)); // Ok(6)\n *\n * @example\n * // Skips step on Err\n * const r3 = await andThen(err<number, string>(\"boom\"), async (n) => ok(n * 3)); // Err(\"boom\")\n *\n * @param input - A Result or Promise<Result> to chain from\n * @param fn - A function invoked when input is Ok; may be sync or async but returns a Result\n * @returns A Promise that resolves to a Result of the chained operation\n */\nexport function andThen<T, E, U>(\n input: Result<T, E>,\n fn: (value: T) => Result<U, E> | Promise<Result<U, E>>,\n): Promise<Result<U, E>>;\nexport function andThen<T, E, U>(\n input: Promise<Result<T, E>>,\n fn: (value: T) => Result<U, E> | Promise<Result<U, E>>,\n): Promise<Result<U, E>>;\nexport async function andThen<T, E, U>(\n input: Result<T, E> | Promise<Result<T, E>>,\n fn: (value: T) => Result<U, E> | Promise<Result<U, E>>,\n): Promise<Result<U, E>> {\n const settled = await input;\n if (settled.ok) {\n return await fn(settled.value);\n }\n return err(settled.error);\n}\n","import { type Result, ok, err } from '@/result';\n\n/**\n * Symbol used to identify Option objects.\n *\n * @internal\n */\nexport const OPTION_BRAND = Symbol('OPTION_BRAND');\n\n/**\n * Represents an Option type.\n *\n * @example\n * const some: Option<number> = some(123);\n * const none: Option<number> = none();\n *\n * @param T - The type of the value contained in the Some variant\n * @returns An Option containing a value or nothing\n */\nexport type Option<T> =\n | {\n readonly some: true;\n readonly value: T;\n readonly [OPTION_BRAND]: 'some';\n }\n | {\n readonly some: false;\n readonly [OPTION_BRAND]: 'none';\n };\n\n/**\n * Creates an Option containing a value.\n *\n * @param value - The value to contain\n * @returns An Option containing the value\n */\nexport function some<T>(value: T): Option<T> {\n return {\n some: true,\n value,\n [OPTION_BRAND]: 'some',\n };\n}\n\n/**\n * Creates an Option containing nothing.\n *\n * @example\n * const some: Option<number> = some(123);\n * const none: Option<number> = none();\n *\n * @returns An Option containing nothing\n */\nexport function none(): Option<never>;\nexport function none<T>(): Option<T>;\nexport function none<T>(): Option<T> {\n return {\n some: false,\n [OPTION_BRAND]: 'none',\n };\n}\n\n/**\n * Type guard that checks if an Option is a Some variant containing a value.\n *\n * @example\n * const option: Option<number> = some(123);\n * if (isSome(option)) {\n * // TypeScript knows option.value exists here\n * console.log(option.value);\n * }\n *\n * @param option - The option to check\n * @returns A type predicate indicating if the option is a Some variant\n */\nexport function isSome<T>(option: Option<T>): option is {\n readonly some: true;\n readonly value: T;\n readonly [OPTION_BRAND]: 'some';\n} {\n return option.some;\n}\n\n/**\n * Type guard that checks if an Option is a None variant containing no value.\n *\n * @example\n * const option: Option<number> = none();\n * if (isNone(option)) {\n * // TypeScript knows this option has no value\n * // Attempting to access option.value would be a type error\n * }\n *\n * @param option - The option to check\n * @returns A type predicate indicating if the option is a None variant\n */\nexport function isNone<T>(option: Option<T>): option is {\n readonly some: false;\n readonly [OPTION_BRAND]: 'none';\n} {\n return !option.some;\n}\n\n/**\n * Maps the value inside an Option using a transformation function.\n *\n * @example\n * const option: Option<number> = some(123);\n * const transformed: Option<string> = map(option, (value) => value.toString());\n *\n * @param option - The Option to transform\n * @param fn - The function to apply to the contained value\n * @returns A new Option containing the transformed value, or none if the input was none\n */\nexport function map<T, U>(option: Option<T>, fn: (value: T) => U): Option<U> {\n return option.some ? some(fn(option.value)) : none();\n}\n\n/**\n * Maps the value inside an Option using a transformation function that returns an Option.\n *\n * @example\n * const option: Option<number> = some(123);\n * const transformed: Option<string> = flatMap(option, (value) => some(value.toString()));\n *\n * @param option - The Option to transform\n * @param fn - The function to apply to the contained value, returning an Option\n * @returns The Option returned by the transformation function, or none if the input was none\n */\nexport function flatMap<T, U>(option: Option<T>, fn: (value: T) => Option<U>): Option<U> {\n return option.some ? fn(option.value) : none();\n}\n\n/**\n * Maps both the Some and None branches of an Option using separate transformation functions.\n * This is similar to combining a match with flatMap: it lets you decide the resulting Option in both cases.\n *\n * @example\n * const o1 = some(123);\n * const r1 = bimap(o1, (n) => some(n.toString()), () => none()); // some(\"123\")\n *\n * const o2 = none<number>();\n * const r2 = bimap(o2, (n) => some(n.toString()), () => some('fallback')); // some(\"fallback\")\n *\n * @param option - The Option to transform\n * @param someFn - The function to apply if the Option is Some, returning a new Option\n * @param noneFn - The function to apply if the Option is None, returning a new Option\n * @returns The Option returned by the appropriate transformation function\n */\nexport function bimap<T, U>(option: Option<T>, someFn: (value: T) => Option<U>, noneFn: () => Option<U>): Option<U> {\n return option.some ? someFn(option.value) : noneFn();\n}\n\n/**\n * Filters an Option based on a predicate function.\n *\n * @example\n * const option: Option<number> = some(123);\n * const filtered: Option<number> = filter(option, value => value > 100); // still Some(123)\n * const filtered2: Option<number> = filter(option, value => value < 100); // None\n *\n * @param option - The Option to filter\n * @param predicate - A function that determines if the value should be kept\n * @returns The original Option if it contains a value that satisfies the predicate, otherwise None\n */\nexport function filter<T>(option: Option<T>, predicate: (value: T) => boolean): Option<T> {\n return option.some && predicate(option.value) ? option : none();\n}\n\n/**\n * Unwraps the value inside an Option, throwing an error if the Option is none.\n *\n * @remarks\n * This function is intended for prototyping only and should not be used in production.\n * In production code, prefer using pattern matching or `unwrapOr` to handle both Some and None cases safely.\n *\n * @example\n * const option: Option<number> = some(123);\n * const value: number = unwrap(option);\n *\n * @param option - The Option to unwrap\n * @param [errorMsg] - Optional custom error message to throw when the Option is none\n * @returns The contained value\n */\nexport function unwrap<T>(option: Option<T>, errorMsg?: string): T {\n if (option.some) {\n return option.value;\n } else {\n throw new Error(errorMsg || 'Cannot unwrap a none Option');\n }\n}\n\n/**\n * Unwraps the value inside an Option, providing a default value if the Option is none.\n *\n * @example\n * const option: Option<number> = none();\n * const value: number = unwrapOr(option, 123);\n *\n * @param option - The Option to unwrap\n * @param defaultValue - The value to return if the Option is none\n * @returns The contained value, or the default value if the Option is none\n */\nexport function unwrapOr<T>(option: Option<T>, defaultValue: T): T {\n return option.some ? option.value : defaultValue;\n}\n\n/**\n * Unwraps the value inside an Option, calling a function to generate a default value if the Option is none.\n * Unlike unwrapOr, this only computes the default when needed.\n *\n * @example\n * const option: Option<number> = none();\n * const value = unwrapOrElse(option, () => expensiveComputation());\n *\n * @param option - The Option to unwrap\n * @param defaultFn - A function that returns a default value if the Option is none\n * @returns The contained value, or the result of calling defaultFn if the Option is none\n */\nexport function unwrapOrElse<T>(option: Option<T>, defaultFn: () => T): T {\n return option.some ? option.value : defaultFn();\n}\n\n/**\n * Creates an Option from a nullable value.\n *\n * @example\n * const option = fromNullable(123); // some(123)\n * const option = fromNullable(null); // none()\n *\n * @param value - The value to wrap in the Some variant\n * @returns An Option containing the value (Some) if the value is not null or undefined, or None if the value is null or undefined\n */\nexport const fromNullable = <T>(value: T | null | undefined): Option<T> => {\n return value === null || value === undefined ? none() : some(value);\n};\n\n/**\n * Combines an array of Options into a single Option containing an array of values.\n * Returns None if any Option in the array is None.\n *\n * @example\n * const options = [some(1), some(2), some(3)];\n * const combined = combine(options); // some([1, 2, 3])\n *\n * const withNone = [some(1), none(), some(3)];\n * const result = combine(withNone); // none()\n *\n * @param options - An array of Options to combine\n * @returns An Option containing an array of all values if all inputs are Some, or None if any input is None\n */\n\n// Tuple-preserving overloads\nexport function combine<T1>(options: readonly [Option<T1>]): Option<[T1]>;\nexport function combine<T1, T2>(options: readonly [Option<T1>, Option<T2>]): Option<[T1, T2]>;\nexport function combine<T1, T2, T3>(options: readonly [Option<T1>, Option<T2>, Option<T3>]): Option<[T1, T2, T3]>;\nexport function combine<T1, T2, T3, T4>(\n options: readonly [Option<T1>, Option<T2>, Option<T3>, Option<T4>],\n): Option<[T1, T2, T3, T4]>;\nexport function combine<T1, T2, T3, T4, T5>(\n options: readonly [Option<T1>, Option<T2>, Option<T3>, Option<T4>, Option<T5>],\n): Option<[T1, T2, T3, T4, T5]>;\nexport function combine<T1, T2, T3, T4, T5, T6>(\n options: readonly [Option<T1>, Option<T2>, Option<T3>, Option<T4>, Option<T5>, Option<T6>],\n): Option<[T1, T2, T3, T4, T5, T6]>;\nexport function combine<T1, T2, T3, T4, T5, T6, T7>(\n options: readonly [Option<T1>, Option<T2>, Option<T3>, Option<T4>, Option<T5>, Option<T6>, Option<T7>],\n): Option<[T1, T2, T3, T4, T5, T6, T7]>;\nexport function combine<T1, T2, T3, T4, T5, T6, T7, T8>(\n options: readonly [Option<T1>, Option<T2>, Option<T3>, Option<T4>, Option<T5>, Option<T6>, Option<T7>, Option<T8>],\n): Option<[T1, T2, T3, T4, T5, T6, T7, T8]>;\nexport function combine<T1, T2, T3, T4, T5, T6, T7, T8, T9>(\n options: readonly [\n Option<T1>,\n Option<T2>,\n Option<T3>,\n Option<T4>,\n Option<T5>,\n Option<T6>,\n Option<T7>,\n Option<T8>,\n Option<T9>,\n ],\n): Option<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;\nexport function combine<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(\n options: readonly [\n Option<T1>,\n Option<T2>,\n Option<T3>,\n Option<T4>,\n Option<T5>,\n Option<T6>,\n Option<T7>,\n Option<T8>,\n Option<T9>,\n Option<T10>,\n ],\n): Option<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;\nexport function combine<T>(options: readonly Option<T>[]): Option<T[]>;\n\nexport function combine<T>(options: readonly Option<T>[]): Option<T[]> {\n const values: T[] = [];\n\n for (const option of options) {\n if (!option.some) return none();\n values.push(option.value);\n }\n\n return some(values);\n}\n\n/**\n * Pattern matches on an Option to handle both Some and None cases.\n *\n * @example\n * const option = some(42);\n * const result = match(option, {\n * some: (value) => `Got value: ${value}`,\n * none: () => \"Got nothing\"\n * }); // \"Got value: 42\"\n *\n * const empty = none<number>();\n * const result2 = match(empty, {\n * some: (value) => `Got value: ${value}`,\n * none: () => \"Got nothing\"\n * }); // \"Got nothing\"\n *\n * @param option - The Option to match against\n * @param patterns - An object containing handler functions for Some and None cases\n * @returns The result of calling the appropriate handler function\n */\nexport function match<T, R>(\n option: Option<T>,\n patterns: {\n some: (value: T) => R;\n none: () => R;\n },\n): R {\n if (isSome(option)) {\n const someFn = patterns.some;\n return someFn(option.value);\n } else {\n const noneFn = patterns.none;\n return noneFn();\n }\n}\n\n/**\n * Executes a callback with the value if the Option is Some, without changing the Option.\n * Useful for side effects like logging while maintaining a processing chain.\n *\n * @example\n * const result = pipe(\n * some(123),\n * opt => map(opt, x => x * 2),\n * opt => tap(opt, x => console.log(`Value: ${x}`)), // Logs but doesn't change the Option\n * opt => filter(opt, x => x > 200)\n * );\n *\n * @param option - The Option to tap into\n * @param fn - The function to execute with the value if Some\n * @returns The original Option unchanged\n */\nexport function tap<T>(option: Option<T>, fn: (value: T) => void): Option<T> {\n if (isSome(option)) {\n const callback = fn;\n callback(option.value);\n }\n return option;\n}\n\n/**\n * Converts an Option to a Result.\n * If the Option is Some, returns an Ok variant with the value.\n * If the Option is None, returns an Err variant with the provided error.\n *\n * @example\n * const result = mapToResult(some(123), 'Some error message');\n * if (isOk(result)) {\n * console.log('Value:', result.value);\n * } else {\n * console.error('Error:', result.error);\n * }\n *\n * @param option - The Option to convert\n * @param error - The error to return if the Option is None\n * @returns A Result containing either the value (Ok) or the error (Err)\n */\nexport function mapToResult<T, E>(option: Option<T>, error: E): Result<T, E> {\n return option.some ? ok(option.value) : err(error);\n}\n","type UnknownFunction = (...params: unknown[]) => unknown;\n\n/**\n * Pipes a value through a series of functions, from left to right.\n * Each function receives the output of the previous function.\n * Unlike flow, pipe immediately executes the functions with the provided initial value.\n *\n * @example\n * // Basic usage\n * const result = pipe(\n * 5,\n * (n) => n * 2, // 10\n * (n) => n + 1, // 11\n * (n) => n.toString() // \"11\"\n * );\n * // result: \"11\"\n *\n * @example\n * // With Option\n * import { some, mapOption } from \"@railway-ts/pipelines/option\";\n *\n * const optionResult = pipe(\n * some(5),\n * (o) => mapOption(o, (n) => n * 2),\n * (o) => mapOption(o, (n) => n.toString())\n * );\n * // optionResult: Option<string> containing \"10\"\n *\n * @example\n * // With Result\n * import { ok, mapResult } from \"@railway-ts/pipelines/result\";\n *\n * const resultValue = pipe(\n * ok(5),\n * (r) => mapResult(r, (n) => n * 2),\n * (r) => mapResult(r, (n) => n.toString())\n * );\n * // resultValue: Result<string, never> containing \"10\"\n *\n * @param a - The initial value to pipe through the functions\n * @param ab - The first function to apply to the initial value\n * @param functions - Additional functions to apply in sequence\n * @returns The final result after applying all functions\n */\n\nexport function pipe<A, B>(a: A, ab: (this: void, a: A) => B): B;\nexport function pipe<A, B, C>(a: A, ab: (this: void, a: A) => B, bc: (this: void, b: B) => C): C;\nexport function pipe<A, B, C, D>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n): D;\nexport function pipe<A, B, C, D, E>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n): E;\nexport function pipe<A, B, C, D, E, F>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n): F;\nexport function pipe<A, B, C, D, E, F, G>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n): G;\nexport function pipe<A, B, C, D, E, F, G, H>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n): H;\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n hi: (this: void, h: H) => I,\n): I;\nexport function pipe<A, B, C, D, E, F, G, H, I, J>(\n a: A,\n ab: (this: void, a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n hi: (this: void, h: H) => I,\n ij: (this: void, i: I) => J,\n): J;\nexport function pipe(value: unknown, ...fns: UnknownFunction[]): unknown {\n let result = value;\n for (const fn of fns) {\n result = fn(result);\n }\n return result;\n}\n","type UnknownFunction = (...params: unknown[]) => unknown;\n\n/**\n * Creates a new function that is the composition of the provided functions, applied from left to right.\n * Unlike pipe, flow doesn't immediately execute the functions but returns a new function that,\n * when called, will run the composed functions in sequence.\n *\n * @example\n * // Basic usage\n * const processNumber = flow(\n * (n: number) => n * 2,\n * (n) => n + 1,\n * (n) => n.toString()\n * );\n *\n * const result = processNumber(5); // \"11\"\n *\n * @example\n * // With multiple arguments\n * const formatName = flow(\n * (first: string, last: string) => `${first} ${last}`,\n * (name) => name.toUpperCase()\n * );\n *\n * const name = formatName(\"John\", \"Doe\"); // \"JOHN DOE\"\n *\n * @example\n * // With Option type\n * import { some, none, mapOption, flatMapOption, type Option } from \"@railway-ts/pipelines/option\";\n *\n * const safeParseInt = (radix: number) => (str: string): Option<number> => {\n * const n = Number.parseInt(str, radix);\n * return Number.isNaN(n) ? none() : some(n);\n * };\n *\n * const processString = flow(\n * (s: string) => some(s),\n * (o) => mapOption(o, (s) => s + \"0\"),\n * (o) => flatMapOption(o, safeParseInt(10))\n * );\n *\n * const option = processString(\"42\"); // Option<number> containing 420\n *\n * @example\n * // With Result type\n * import { ok, err, flatMapResult } from \"@railway-ts/pipelines/result\";\n *\n * const validatePositive = (n: number) => (n > 0 ? ok(n) : err(\"Not positive\"));\n *\n * const validateNumber = flow(\n * (n: number) => ok(n),\n * (r) => flatMapResult(r, validatePositive),\n * (r) => flatMapResult(r, (n) => ok(n * 2))\n * );\n *\n * const result = validateNumber(5); // Result<number, string> containing 10\n *\n * @param ab - The first function in the composition\n * @param functions - Additional functions to compose in sequence\n * @returns A new function that applies all the composed functions in sequence\n */\nexport function flow<A extends unknown[], B>(ab: (this: void, ...a: A) => B): (...a: A) => B;\nexport function flow<A extends unknown[], B, C>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends unknown[], B, C, D>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends unknown[], B, C, D, E>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends unknown[], B, C, D, E, F>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n): (...a: A) => F;\nexport function flow<A extends unknown[], B, C, D, E, F, G>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n): (...a: A) => G;\nexport function flow<A extends unknown[], B, C, D, E, F, G, H>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n): (...a: A) => H;\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n hi: (this: void, h: H) => I,\n): (...a: A) => I;\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n hi: (this: void, h: H) => I,\n ij: (this: void, i: I) => J,\n): (...a: A) => J;\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K>(\n ab: (this: void, ...a: A) => B,\n bc: (this: void, b: B) => C,\n cd: (this: void, c: C) => D,\n de: (this: void, d: D) => E,\n ef: (this: void, e: E) => F,\n fg: (this: void, f: F) => G,\n gh: (this: void, g: G) => H,\n hi: (this: void, h: H) => I,\n ij: (this: void, i: I) => J,\n jk: (this: void, j: J) => K,\n): (...a: A) => K;\nexport function flow(...fns: [UnknownFunction, ...UnknownFunction[]]): UnknownFunction {\n if (fns.length === 1) {\n return fns[0];\n }\n\n const [first, ...rest] = fns;\n return (...args: unknown[]): unknown => {\n let result = first(...args);\n for (const fn of rest) {\n result = fn(result);\n }\n return result;\n };\n}\n","type UnknownFunction = (...params: unknown[]) => unknown;\n\n/**\n * Curries a multi-parameter function into a sequence of unary functions.\n * Enables partial application at any depth and composes cleanly with `pipe`.\n *\n * Note: This curry is unary-only at each step to ensure compatibility with `pipe` and `flow`.\n *\n * @example\n * // Basic (2-arity)\n * const add = (a: number, b: number) => a + b;\n * const add5 = curry(add)(5);\n * add5(3); // 8\n *\n * @example\n * // 3-arity and partial application\n * const multiply = (a: number, b: number, c: number) => a * b * c;\n * const curriedMultiply = curry(multiply);\n * curriedMultiply(2)(3)(4); // 24\n *\n * @example\n * // With pipe\n * import { pipe } from \"@/utils\";\n * const divide = (divisor: number, dividend: number) => dividend / divisor;\n * const result = pipe(100, curry(divide)(2), (n) => n + 1); // 51\n *\n * @example\n * // With Result validators\n * import { ok, err, flatMapResult, type Result } from \"@/index\";\n * const between = (min: number, max: number, n: number): Result<number, string> =>\n * n >= min && n <= max ? ok(n) : err(`Value must be between ${min} and ${max}`);\n * const validateAge = curry(between)(0)(120);\n * pipe(ok(25), (r) => flatMapResult(r, validateAge)); // ok(25)\n *\n * @param fn - The multi-argument function to transform into a unary curried chain\n * @returns A curried function that takes one argument at each application step\n */\n\n// 2-arity\nexport function curry<A, B, R>(fn: (a: A, b: B) => R): (a: A) => (b: B) => R;\n\n// 3-arity\nexport function curry<A, B, C, R>(fn: (a: A, b: B, c: C) => R): (a: A) => (b: B) => (c: C) => R;\n\n// 4-arity\nexport function curry<A, B, C, D, R>(fn: (a: A, b: B, c: C, d: D) => R): (a: A) => (b: B) => (c: C) => (d: D) => R;\n\n// 5-arity\nexport function curry<A, B, C, D, E, R>(\n fn: (a: A, b: B, c: C, d: D, e: E) => R,\n): (a: A) => (b: B) => (c: C) => (d: D) => (e: E) => R;\n\n// Implementation\nexport function curry<T extends UnknownFunction>(fn: T): UnknownFunction {\n const arity = fn.length;\n\n return function curried(...args: unknown[]): unknown {\n if (args.length >= arity) {\n return (fn as UnknownFunction)(...args);\n }\n\n return function (...nextArgs: unknown[]): unknown {\n return curried(...args, ...nextArgs);\n };\n };\n}\n","type UnknownFunction = (...params: unknown[]) => unknown;\n\n/**\n * Uncurries a curried unary function chain back into a multi-argument function.\n * Inverse of `curry`. Useful when calling curried APIs with positional arguments.\n *\n * Note: Expects strictly unary nesting (the shape produced by `curry`).\n *\n * @example\n * // 2-arity\n * const addCurried = (a: number) => (b: number) => a + b;\n * const add = uncurry(addCurried);\n * add(5, 3); // 8\n *\n * @example\n * // 3-arity\n * const multiplyCurried = (a: number) => (b: number) => (c: number) => a * b * c;\n * const multiply = uncurry(multiplyCurried);\n * multiply(2, 3, 4); // 24\n *\n * @example\n * // Round-trip with curry\n * import { curry } from \"@railway-ts/pipelines\";\n * const divide = (divisor: number, dividend: number) => dividend / divisor;\n * const divideCurried = curry(divide);\n * const divideUncurried = uncurry(divideCurried);\n * divideUncurried(2, 100); // 50\n *\n * @param fn - A curried unary function chain (e.g., a => b => c => r)\n * @returns A multi-argument function equivalent to applying the curried chain in sequence\n */\n\n// Overloads ordered from most specific (5-arity) to least specific (2-arity)\n// This ensures TypeScript matches the correct overload\n\n// 5-arity\nexport function uncurry<A, B, C, D, E, R>(\n fn: (a: A) => (b: B) => (c: C) => (d: D) => (e: E) => R,\n): (a: A, b: B, c: C, d: D, e: E) => R;\n\n// 5-arity\nexport function uncurry<A, B, C, D, E, R>(\n fn: (a: A) => (b: B) => (c: C) => (d: D) => (e: E) => R,\n): (a: A, b: B, c: C, d: D, e: E) => R;\n\n// 4-arity\nexport function uncurry<A, B, C, D, R>(fn: (a: A) => (b: B) => (c: C) => (d: D) => R): (a: A, b: B, c: C, d: D) => R;\n\n// 3-arity\nexport function uncurry<A, B, C, R>(fn: (a: A) => (b: B) => (c: C) => R): (a: A, b: B, c: C) => R;\n\n// 2-arity\nexport function uncurry<A, B, R>(fn: (a: A) => (b: B) => R): (a: A, b: B) => R;\n\n// 1-arity (identity - technically not curried, but allows for consistent API)\nexport function uncurry<A, R>(fn: (a: A) => R): (a: A) => R;\n\n// Implementation - looser types allow overloads to work correctly\nexport function uncurry(fn: unknown): unknown {\n return function uncurried(...args: unknown[]): unknown {\n // Apply arguments sequentially to the curried function chain\n let result = fn;\n\n for (const arg of args) {\n result = (result as UnknownFunction)(arg);\n }\n\n return result;\n };\n}\n","type UnknownFunction = (...params: unknown[]) => unknown;\n\n/**\n * Transforms a multi-argument function into one that accepts a single tuple argument.\n * This makes multi-arg functions composable in `pipe`/`flow` when your data is a tuple.\n *\n * @example\n * // Basic\n * const add = (a: number, b: number) => a + b;\n * const tupledAdd = tupled(add);\n * tupledAdd([5, 3]); // 8\n *\n * @example\n * // With pipe (tuple input)\n * import { pipe } from \"@/utils\";\n * const distance = (x: number, y: number) => Math.hypot(x, y);\n * pipe([3, 4] as [number, number], tupled(distance)); // 5\n *\n * @example\n * // With Result\n * import { ok, err, flatMapResult, mapResult, type Result } from \"@railway-ts/pipelines/result\";\n * const divide = (dividend: number, divisor: number): Result<number, string> =>\n * divisor === 0 ? err(\"Division by zero\") : ok(dividend / divisor);\n * const tupledDivide = tupled(divide);\n * pipe(ok<[number, number], string>([10, 2]),\n * (r) => flatMapResult(r, tupledDivide),\n * (r) => mapResult(r, (n) => n * 2)\n * ); // ok(10)\n *\n * @example\n * // With Option\n * import { some, none, flatMapOption, type Option } from \"@railway-ts/pipelines/option\";\n * const safeParse = (str: string, radix: number): Option<number> => {\n * const n = Number.parseInt(str, radix);\n * return Number.isNaN(n) ? none() : some(n);\n * };\n * const tupledParse = tupled(safeParse);\n * flatMapOption(some([\"FF\", 16] as [string, number]), tupledParse); // some(255)\n *\n * @param fn - A function taking positional arguments to be adapted to a single tuple argument\n * @returns A function that takes a tuple and applies it to `fn` as positional args\n */\n\n// 2-arity\nexport function tupled<A, B, R>(fn: (a: A, b: B) => R): (args: [A, B]) => R;\n\n// 3-arity\nexport function tupled<A, B, C, R>(fn: (a: A, b: B, c: C) => R): (args: [A, B, C]) => R;\n\n// 4-arity\nexport function tupled<A, B, C, D, R>(fn: (a: A, b: B, c: C, d: D) => R): (args: [A, B, C, D]) => R;\n\n// 5-arity\nexport function tupled<A, B, C, D, E, R>(fn: (a: A, b: B, c: C, d: D, e: E) => R): (args: [A, B, C, D, E]) => R;\n\n// Implementation\nexport function tupled<T extends UnknownFunction>(fn: T): (args: unknown[]) => unknown {\n return function tupledFn(args: unknown[]): unknown {\n return fn(...args);\n };\n}\n","type UnknownFunction = (...params: unknown[]) => unknown;\n\n/**\n * Transforms a function that accepts a tuple into a multi-argument function.\n * Inverse of `tupled`. Useful when callers have positional arguments but your core API uses tuples.\n *\n * @example\n * // Basic\n * const tupledAdd = ([a, b]: [number, number]) => a + b;\n * const add = untupled(tupledAdd);\n * add(5, 3); // 8\n *\n * @example\n * // 3-arity\n * const sum3Tupled = ([a, b, c]: [number, number, number]) => a + b + c;\n * const sum3 = untupled(sum3Tupled);\n * sum3(1, 2, 3); // 6\n *\n * @example\n * // With Result\n * import { ok, err, flatMapResult, type Result } from \"@railway-ts/pipelines/result\";\n * const validateRange = ([min, max, value]: [number, number, number]): Result<number, string> =>\n * value >= min && value <= max ? ok(value) : err(`Value ${value} not between ${min} and ${max}`);\n * const validate = untupled(validateRange);\n * flatMapResult(ok(50), (n) => validate(0, 100, n)); // ok(50)\n *\n * @example\n * // With Option\n * import { some, none, type Option } from \"@railway-ts/pipelines/option\";\n * const parsePair = ([x, y]: [string, string]): Option<number> => {\n * const a = Number(x), b = Number(y);\n * return Number.isNaN(a) || Number.isNaN(b) ? none() : some(a + b);\n * };\n * const parse = untupled(parsePair);\n * parse(\"2\", \"3\"); // some(5)\n *\n * @param fn - A function that accepts a tuple of arguments\n * @returns A function that accepts the same arguments positionally\n */\n\n// 2-arity\nexport function untupled<A, B, R>(fn: (args: [A, B]) => R): (a: A, b: B) => R;\n\n// 3-arity\nexport function untupled<A, B, C, R>(fn: (args: [A, B, C]) => R): (a: A, b: B, c: C) => R;\n\n// 4-arity\nexport function untupled<A, B, C, D, R>(fn: (args: [A, B, C, D]) => R): (a: A, b: B, c: C, d: D) => R;\n\n// 5-arity\nexport function untupled<A, B, C, D, E, R>(fn: (args: [A, B, C, D, E]) => R): (a: A, b: B, c: C, d: D, e: E) => R;\n\n// Implementation\nexport function untupled<T extends UnknownFunction>(fn: T): UnknownFunction {\n return function untupledFn(...args: unknown[]): unknown {\n return fn(args);\n };\n}\n","/* eslint-disable security/detect-object-injection */\nimport { err, isOk, ok, type Result } from '../result';\n\n/**\n * Represents a validation error with path information and a message.\n *\n * @typedef {Object} ValidationError\n * @property {string[]} path - The path to the field that failed validation\n * @property {string} message - The error message describing the validation failure\n */\nexport type ValidationError = {\n path: string[];\n message: string;\n};\n\n/**\n * A validator function that checks if a value meets certain criteria.\n *\n * @template I - The input type to validate\n * @template O - The output type (defaults to the input type if not specified)\n * @callback Validator\n * @param {I} value - The value to validate\n * @param {string[]} [path=[]] - The path to the current value (used for nested objects)\n * @returns {Result<O, ValidationError[]>} A Result containing either the validated value or validation errors\n */\nexport type Validator<I, O = I> = (value: I, path?: string[]) => Result<O, ValidationError[]>;\n\ntype AtomicType = string | number | boolean | Date | null | undefined | bigint;\n\ntype RemoveUndefined<T> = T extends undefined ? never : T;\n\ntype ProcessType<T> = T extends AtomicType\n ? T\n : T extends Array<infer U>\n ? Array<ProcessType<U>>\n : T extends object\n ? {\n [K in keyof T as undefined extends T[K] ? never : K]: ProcessType<T[K]>;\n } & {\n [K in keyof T as undefined extends T[K] ? K : never]?: ProcessType<RemoveUndefined<T[K]>>;\n } extends infer O\n ? { [K in keyof O]: O[K] }\n : never\n : T;\n\n// Infer the output type of a validator or schema\ntype InferType<V> = V extends Validator<unknown, infer O> ? O : never;\n\n// Combines inference, processing, and flattening\n/**\n * Infers the output type of a validator or schema after processing.\n * This is useful for getting the TypeScript type that a validator will produce.\n *\n * @template V - The validator or schema to infer the type from\n */\nexport type InferSchemaType<V> = ProcessType<InferType<V>>;\n\n/**\n * Represents a validation schema where each key maps to a validator for that field.\n *\n * @template T - The shape of the object being validated\n */\nexport type Schema<T = Record<string, unknown>> = {\n [K in keyof T]: Validator<unknown, T[K]>;\n};\n\n/**\n * The result of a validation operation.\n *\n * @template T - The type of the validated data\n * @property {boolean} valid - Whether the validation was successful\n * @property {T} [data] - The validated data (only present if validation was successful)\n * @property {Record<string, string>} [errors] - Object mapping field paths to error messages (only present if validation failed)\n */\nexport type ValidationResult<T> = { valid: true; data: T } | { valid: false; errors: Record<string, string> };\n\n/**\n * Creates a validator for objects based on a schema.\n *\n * @template T - The shape of the object being validated\n * @param {Schema<T>} schema - An object where each key contains a validator for that property\n * @param {{ strict?: boolean }} [options={ strict: true }] - Options object\n * @param {boolean} [options.strict=true] - If true, rejects objects with properties not in the schema\n * @returns {Validator<unknown, T>} A validator that validates objects against the schema\n *\n * @example\n * // Define a user schema\n * const userSchema = object({\n * name: required(string()),\n * age: required(chain(parseNumber(), min(18))),\n * email: required(email())\n * });\n *\n * @example\n * // Validate an object against the schema\n * const userData = { name: 'John', age: 25, email: 'john@example.com' };\n * const result = userSchema(userData);\n * // If valid: { ok: true, value: { name: 'John', age: 25, email: 'john@example.com' }, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With validation errors\n * const invalidUser = { name: 'John', age: 15, email: 'not-an-email' };\n * const result = userSchema(invalidUser);\n * // If invalid: { ok: false, error: [\n * // { path: ['age'], message: 'Must be at least 18' },\n * // { path: ['email'], message: 'Invalid email format' }\n * // ], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Non-strict mode (allows extra fields)\n * const lenientSchema = object({ name: required(string()) }, { strict: false });\n * const result = lenientSchema({ name: 'John', extraField: 'value' });\n * // If valid: { ok: true, value: { name: 'John', extraField: 'value' }, [RESULT_BRAND]: 'ok' }\n */\nexport function object<T extends Record<string, unknown>>(\n schema: Schema<T>,\n { strict = true }: { strict?: boolean } = {},\n): Validator<unknown, T> {\n return (obj, parentPath = []) => {\n if (obj === null || typeof obj !== 'object') {\n return err([{ path: parentPath, message: 'Expected an object' }]);\n }\n\n const allErrors: ValidationError[] = [];\n const validatedObj: Record<string, unknown> = {};\n\n if (strict !== false) {\n const extraKeys = Object.keys(obj as object).filter((key) => !Object.prototype.hasOwnProperty.call(schema, key));\n\n if (extraKeys.length > 0) {\n for (const key of extraKeys) {\n allErrors.push({\n path: [...parentPath, key],\n message: `Unexpected field: '${key}'`,\n });\n }\n }\n }\n\n for (const key in schema) {\n if (!Object.prototype.hasOwnProperty.call(schema, key)) continue;\n\n const validator = schema[key];\n if (!validator) continue;\n\n const value = (obj as Record<string, unknown>)[key];\n const fieldPath = [...parentPath, key];\n\n const result = validator(value, fieldPath);\n\n if (isOk(result)) {\n validatedObj[key] = result.value;\n } else {\n allErrors.push(...result.error);\n }\n }\n\n if (allErrors.length > 0) {\n return err(allErrors);\n }\n\n return ok(validatedObj as T);\n };\n}\n\n/**\n * Creates a validator that requires a value to be defined (not null or undefined)\n * before applying the underlying validator.\n *\n * @template I - The input type of the underlying validator\n * @template O - The output type of the underlying validator\n * @param {Validator<I, O>} validator - The validator to apply if the value is defined\n * @param {string} [message='Field is required'] - Error message when value is null or undefined\n * @returns {Validator<I | undefined | null, O>} A validator that checks the value is defined\n *\n * @example\n * // Basic required field\n * const nameValidator = required(string());\n * const result = nameValidator(undefined);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Field is required' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const emailValidator = required(email(), 'Email address is required');\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * name: required(string()), // Required field\n * email: required(email()), // Required email\n * phone: optional(parsePhoneNumber()) // Optional field\n * });\n */\nexport function required<I, O>(\n validator: Validator<I, O>,\n message: string = 'Field is required',\n): Validator<I | undefined | null, O> {\n return (value, path = []) => {\n if (value === undefined || value === null) {\n return err([{ path, message }]);\n }\n return validator(value as I, path);\n };\n}\n\n/**\n * Creates a validator that makes a field optional.\n * If the value is null or undefined, validation passes and returns undefined.\n * Otherwise, applies the underlying validator.\n *\n * @template I - The input type of the underlying validator\n * @template O - The output type of the underlying validator\n * @param {Validator<I, O>} validator - The validator to apply if the value is defined\n * @returns {Validator<I | undefined | null, O | undefined>} A validator that allows undefined values\n *\n * @example\n * // Basic optional field\n * const profileValidator = optional(string());\n * const result = profileValidator(undefined);\n * // If valid: { ok: true, value: undefined, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With defined value\n * const result = optional(number())(42);\n * // If valid: { ok: true, value: 42, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * name: required(string()), // Required field\n * email: required(email()), // Required email\n * phone: optional(parsePhoneNumber()), // Optional field\n * bio: optional(chain(string(), maxLength(500))) // Optional with extra validation\n * });\n */\nexport function optional<I, O>(validator: Validator<I, O>): Validator<I | undefined | null, O | undefined> {\n return (value, path = []) => {\n if (value === undefined || value === null) {\n // eslint-disable-next-line unicorn/no-useless-undefined\n return ok(undefined);\n }\n return validator(value, path);\n };\n}\n\n/**\n * Creates a validator that only accepts null values\n *\n * @param {string} [message=\"Must be null\"] - Custom error message when the value is not null\n * @returns {Validator<unknown, null>} A validator that ensures the value is exactly null\n *\n * @example\n * // Field that must be explicitly null\n * const resetField = nullable();\n *\n * @example\n * // With valid null value\n * const validator = nullable();\n * const result = validator(null);\n * // If valid: { ok: true, value: null, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input (not null)\n * const result = nullable()(\"some value\");\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be null' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const nullOnlyField = nullable(\"This field must be null\");\n *\n * @example\n * // Used in an object schema for nullable fields\n * const userSchema = object({\n * deletedAt: nullable(),\n * resetToken: nullable(\"Reset token must be null when not in use\")\n * });\n */\nexport function nullable(message: string = 'Must be null'): Validator<unknown, null> {\n return (value, path = []) => {\n if (value !== null) {\n return err([{ path, message }]);\n }\n // eslint-disable-next-line unicorn/no-null\n return ok(null);\n };\n}\n\n/**\n * Creates a validator that treats empty strings, empty arrays, and empty objects as optional\n *\n * @template I - Input type for the validator\n * @template O - Output type for the validator\n * @param {Validator<I, O>} validator - The validator to apply if the value is not empty\n * @returns {Validator<I | undefined | null, O | undefined>} A validator that treats empty strings, empty arrays, and empty objects as optional\n *\n * @example\n * // Optional bio field that treats empty string as undefined\n * const userSchema = object({\n * username: required(string()),\n * bio: emptyAsOptional(chain(string(), maxLength(500)))\n * });\n *\n * const result1 = validate({ username: \"john\", bio: \"\" }, userSchema);\n * // If valid: { ok: true, value: { username: \"john\", bio: undefined }, [RESULT_BRAND]: 'ok' }\n *\n * const result2 = validate({ username: \"john\", bio: \"My bio\" }, userSchema);\n * // If valid: { ok: true, value: { username: \"john\", bio: \"My bio\" }, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Optional tags array that treats empty array as undefined\n * const postSchema = object({\n * title: required(string()),\n * tags: emptyAsOptional(array(string()))\n * });\n *\n * const result = validate({ title: \"My Post\", tags: [] }, postSchema);\n * // If valid: { ok: true, value: { title: \"My Post\", tags: undefined }, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Optional nested address object that treats empty object as undefined\n * const profileSchema = object({\n * name: required(string()),\n * address: emptyAsOptional(object({\n * street: required(string()),\n * city: required(string()),\n * zipCode: required(string())\n * }))\n * });\n *\n * const result = validate({ name: \"Alice\", address: {} }, profileSchema);\n * // If valid: { ok: true, value: { name: \"Alice\", address: undefined }, [RESULT_BRAND]: 'ok' }\n */\nexport function emptyAsOptional<I, O>(validator: Validator<I, O>): Validator<I | undefined | null, O | undefined> {\n return (value, path = []) => {\n // Handle empty strings, empty arrays, etc.\n if (\n value === '' ||\n (Array.isArray(value) && value.length === 0) ||\n (typeof value === 'object' && value !== null && Object.keys(value).length === 0)\n ) {\n // eslint-disable-next-line unicorn/no-useless-undefined\n return ok(undefined);\n }\n\n // Delegate to the built-in optional for other cases\n return optional(validator)(value, path);\n };\n}\n\n/**\n * Creates a validator that checks if a value exactly matches the expected literal value\n *\n * @template T - Type of the literal value\n * @param {T} expectedValue - The exact value that should be matched\n * @param {string} [message] - Custom error message when validation fails\n * @returns {Validator<unknown, T>} A validator that checks if the value matches the literal\n *\n * @example\n * // Validate a specific string literal\n * const statusValidator = literal('active');\n * const result = statusValidator('active');\n * // If valid: { ok: true, value: 'active', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = literal('pending')('completed');\n * // If invalid: { ok: false, error: [{ path: [], message: \"Value must be 'pending'\" }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const envValidator = literal('production', 'Environment must be production');\n *\n * @example\n * // With number literal\n * const versionValidator = literal(42);\n * const result = versionValidator(42);\n * // If valid: { ok: true, value: 42, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Used in an object schema for type discrimination\n * const userSchema = object({\n * type: required(literal('user')),\n * name: required(string()),\n * role: required(literal('admin'))\n * });\n */\nexport function literal<T>(\n expectedValue: T,\n message: string = `Value must be '${String(expectedValue)}'`,\n): Validator<unknown, T> {\n return (value, path = []) => {\n if (value !== expectedValue) {\n return err([{ path, message }]);\n }\n return ok(expectedValue);\n };\n}\n","/* eslint-disable unicorn/no-array-reduce */\nimport { isErr, ok, err, type Result, match } from '../result';\n\nimport type { ValidationError, ValidationResult, Validator } from './core';\n\n/**\n * Combines multiple validators into a single validator, applying them in sequence (left to right).\n * Each validator's result is passed to the next validator in the chain.\n * The sequence stops and returns an error if any validator in the chain fails.\n */\nexport function chain<A, B>(v1: Validator<A, B>): Validator<A, B>;\nexport function chain<A, B, C>(v1: Validator<A, B>, v2: Validator<B, C>): Validator<A, C>;\nexport function chain<A, B, C, D>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>): Validator<A, D>;\nexport function chain<A, B, C, D, E>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n): Validator<A, E>;\nexport function chain<A, B, C, D, E, F>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n v5: Validator<E, F>,\n): Validator<A, F>;\nexport function chain<A, B, C, D, E, F, G>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n v5: Validator<E, F>,\n v6: Validator<F, G>,\n): Validator<A, G>;\nexport function chain<A, B, C, D, E, F, G, H>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n v5: Validator<E, F>,\n v6: Validator<F, G>,\n v7: Validator<G, H>,\n): Validator<A, H>;\nexport function chain<A, B, C, D, E, F, G, H, I>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n v5: Validator<E, F>,\n v6: Validator<F, G>,\n v7: Validator<G, H>,\n v8: Validator<H, I>,\n): Validator<A, I>;\nexport function chain<A, B, C, D, E, F, G, H, I, J>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n v5: Validator<E, F>,\n v6: Validator<F, G>,\n v7: Validator<G, H>,\n v8: Validator<H, I>,\n v9: Validator<I, J>,\n): Validator<A, J>;\nexport function chain<A, B, C, D, E, F, G, H, I, J, K>(\n v1: Validator<A, B>,\n v2: Validator<B, C>,\n v3: Validator<C, D>,\n v4: Validator<D, E>,\n v5: Validator<E, F>,\n v6: Validator<F, G>,\n v7: Validator<G, H>,\n v8: Validator<H, I>,\n v9: Validator<I, J>,\n v10: Validator<J, K>,\n): Validator<A, K>;\n\n/**\n * Implementation of chain that combines multiple validators into a single validator,\n * applying them in sequence (left to right).\n *\n * @template A - The input type for the first validator\n * @template B - The output type of the first validator and input type for the second validator (if any)\n * @template C, D, E, F, G, H, I, J, K - Types for subsequent validators in the chain\n *\n * @param {...Validator[]} validators - A list of validators to compose\n * @returns {Validator<unknown, unknown>} A combined validator that applies all validators in sequence\n *\n * @example\n * // Basic composition of string validators\n * const passwordValidator = chain(\n * string(),\n * nonEmpty(),\n * minLength(8)\n * );\n *\n * const result = passwordValidator('password123');\n * // If valid: { ok: true, value: 'password123', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Chain validators with type conversion\n * const ageValidator = chain(\n * parseString(), // Converts to string\n * nonEmpty(), // Ensures not empty\n * parseNumber() // Converts to number\n * );\n *\n * const result = ageValidator('25');\n * // If valid: { ok: true, value: 25, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Validation fails at first error\n * const result = chain(string(), minLength(5))('abc');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be at least 5 characters' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * name: required(string()),\n * email: required(chain(string(), email())),\n * age: required(chain(parseString(), parseNumber(), min(18)))\n * });\n */\nexport function chain(...validators: Validator<unknown, unknown>[]): Validator<unknown, unknown> {\n return (value, path = []) => {\n let result: Result<unknown, ValidationError[]> = ok(value);\n\n for (const validator of validators) {\n if (isErr(result)) return result;\n\n const nextResult = validator(result.value, path);\n result = isErr(nextResult) ? nextResult : ok(nextResult.value);\n }\n\n return result;\n };\n}\n\n/**\n * Validates a value against a validator.\n * This is a simple utility function that directly applies a validator to a value.\n *\n * @template T - The expected output type of the validator\n * @param {unknown} value - The value to validate\n * @param {Validator<unknown, T>} validator - The validator to apply to the value\n * @returns {Result<T, ValidationError[]>} A Result containing either the validated value or validation errors\n *\n * @example\n * // Validate a simple value\n * const numberValidator = chain(parseNumber(), min(5));\n * const result = validate(10, numberValidator);\n * // If valid: { ok: true, value: 10, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Validation with errors\n * const result = validate('hello', number());\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Check the result\n * const result = validate(userInput, userSchema);\n * if (isErr(result)) {\n * // Handle validation errors\n * const formattedErrors = formatErrors(result.error);\n * displayErrors(formattedErrors);\n * } else {\n * // Use the validated data\n * saveUser(result.value);\n * }\n */\nexport function validate<T>(value: unknown, validator: Validator<unknown, T>): Result<T, ValidationError[]>;\nexport function validate<T>(\n value: unknown,\n validator: Validator<unknown, T>,\n path: string[],\n): Result<T, ValidationError[]>;\nexport function validate<T>(\n value: unknown,\n validator: Validator<unknown, T>,\n path: string[] = [],\n): Result<T, ValidationError[]> {\n return validator(value, path);\n}\n\n/**\n * Formats validation errors into a more user-friendly object structure.\n * Converts array paths to a dot notation string format, suitable for form libraries or error displays.\n *\n * @param {ValidationError[]} errors - The array of validation errors to format\n * @returns {Record<string, string>} An object mapping paths to error messages\n *\n * @example\n * // Simple errors\n * const result = validate(data, schema);\n * if (isErr(result)) {\n * const formatted = formatErrors(result.error);\n * // { name: 'Name is required', 'address.zipCode': 'Invalid ZIP code' }\n * }\n *\n * @example\n * // Formatting errors with array indices\n * const schema = object({\n * items: array(number())\n * });\n * const result = validate({ items: [1, 'two', 3] }, schema);\n * if (isErr(result)) {\n * const formatted = formatErrors(result.error);\n * // { 'items[1]': 'Must be a number' }\n * }\n *\n * @example\n * // Using formatted errors with a form library\n * const formErrors = formatErrors(validationErrors);\n * form.setErrors(formErrors);\n */\nexport function formatErrors(errors: ValidationError[]): Record<string, string> {\n return errors.reduce(\n (acc, error) => {\n const formattedPath = error.path.reduce((path, segment, index) => {\n if (/^\\d+$/.test(segment)) {\n return `${path}[${segment}]`;\n } else {\n return index === 0 ? segment : `${path}.${segment}`;\n }\n }, '');\n\n // eslint-disable-next-line security/detect-object-injection\n acc[formattedPath] = error.message;\n return acc;\n },\n {} as Record<string, string>,\n );\n}\n\n/**\n * Validates input and returns a formatted ValidationResult in one call.\n * Convenience function that combines validate() + formatErrors() + match() into a single operation.\n *\n * This is a shorthand for the common pattern of validating input and immediately formatting\n * errors into a simple Record<string, string> format, typically used for API responses or\n * client-facing error messages.\n *\n * @template T - The expected output type after successful validation\n * @param {unknown} input - The untrusted input to validate\n * @param {Validator<unknown, T>} schema - The validator/schema to validate against\n * @returns {ValidationResult<T>} An object with either { valid: true, data: T } or { valid: false, errors: Record<string, string> }\n *\n * @example\n * // Basic usage - replaces manual validation + formatting\n * const userSchema = object({\n * email: required(chain(string(), email())),\n * age: required(chain(parseNumber(), min(18)))\n * });\n *\n * const result = validateAndFormatResult(input, userSchema);\n * // If valid: { valid: true, data: { email: \"user@example.com\", age: 25 } }\n * // If invalid: { valid: false, errors: { email: \"Invalid email\", age: \"Must be at least 18\" } }\n *\n * @example\n * // API endpoint usage\n * async function registerUser(req: Request) {\n * const result = validateAndFormatResult(req.body, registrationSchema);\n *\n * if (!result.valid) {\n * return res.status(400).json({ errors: result.errors });\n * }\n *\n * const user = await createUser(result.data);\n * return res.json({ user });\n * }\n *\n * @example\n * // Replaces this manual pattern:\n * // const validationResult = validate(input, schema);\n * // const output = match(validationResult, {\n * // ok: (data) => ({ valid: true, data }),\n * // err: (errors) => ({ valid: false, errors: formatErrors(errors) })\n * // });\n *\n * // With this one-liner:\n * const output = validateAndFormatResult(input, schema);\n *\n * @example\n * // Type-safe destructuring\n * const { valid, data, errors } = validateAndFormatResult(input, schema);\n *\n * if (valid) {\n * // TypeScript knows 'data' exists here\n * console.log(data.email);\n * } else {\n * // TypeScript knows 'errors' exists here\n * console.log(errors.email);\n * }\n */\nexport function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>): ValidationResult<T> {\n const result = validate(input, schema);\n return match<T, ValidationError[], ValidationResult<T>>(result, {\n ok: (data) => ({ valid: true, data }),\n err: (errors) => ({ valid: false, errors: formatErrors(errors) }),\n });\n}\n\n/**\n * Creates a validator that transforms a value during validation\n *\n * IMPORTANT: The transformer function must be pure and not throw exceptions.\n * This validator always succeeds and returns the transformed value.\n * For transformations that might fail, use proper validators or chain with validation:\n *\n * @template I - The input type\n * @template O - The output type after transformation\n * @param {(value: I) => O} transformer - A pure function that transforms the input value\n * @returns {Validator<I, O>} A validator that applies the transformation\n *\n * @example\n * // Safe transformation after validation\n * const normalizeEmail = chain(\n * string(),\n * email(),\n * transform(s => s.toLowerCase()) // Safe because we know it's a valid email string\n * );\n *\n * @example\n * // Transform for normalization\n * const trimmedString = chain(\n * string(),\n * transform(s => s.trim())\n * );\n *\n * @example\n * // Type conversion\n * const numberToString = transform<number, string>(n => n.toString());\n *\n * @example\n * // DON'T use for risky transformations:\n * // transform(s => JSON.parse(s)) // Could throw!\n * // Instead use: parseJSON() // Handles errors properly\n */\nexport function transform<I, O>(transformer: (value: I) => O): Validator<I, O> {\n return (value) => ok(transformer(value));\n}\n\n/**\n * Creates a validator that refines a value with a custom predicate\n * Useful for adding custom validation logic that can't be expressed with existing validators\n *\n * @template T - The type of the value being refined\n * @param {(value: T) => boolean} predicate - A function that returns true if the value is valid\n * @param {string} [message='Custom validation failed'] - The error message to return if validation fails\n * @returns {Validator<T, T>} A validator that checks the predicate\n *\n * @example\n * // Check if a number is even\n * const isEven = refine<number>(\n * n => n % 2 === 0,\n * \"Must be an even number\"\n * );\n *\n * @example\n * // Complex business logic\n * const validPassword = chain(\n * string(),\n * minLength(8),\n * refine(\n * password => /[A-Z]/.test(password) && /[0-9]/.test(password),\n * \"Password must contain at least one uppercase letter and one number\"\n * )\n * );\n *\n * @example\n * // Cross-field validation (when used with object schemas)\n * const dateRange = refine<{ start: Date; end: Date }>(\n * ({ start, end }) => start <= end,\n * \"Start date must be before or equal to end date\"\n * );\n *\n * @example\n * // Multiple refinements\n * const positiveEven = chain(\n * number(),\n * refine(n => n > 0, \"Must be positive\"),\n * refine(n => n % 2 === 0, \"Must be even\")\n * );\n */\nexport function refine<T>(\n predicate: (value: T) => boolean,\n message: string = 'Custom validation failed',\n): Validator<T, T> {\n return (value, path = []) => {\n if (!predicate(value)) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n","import { err, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator that ensures a value is a string.\n *\n * @param {string} [message='Must be a string'] - Custom error message\n * @returns {Validator<unknown, string>} A validator that checks if a value is a string\n *\n * @example\n * // Validate that a value is a string\n * const nameValidator = string();\n * const result = nameValidator('John');\n * // If valid: { ok: true, value: 'John', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = string()(42);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a string' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const labelValidator = string('Label must be text');\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * name: required(string())\n * });\n */\nexport function string(message: string = 'Must be a string'): Validator<unknown, string> {\n return (value, path = []) => {\n if (typeof value !== 'string') {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a string's length is at least a minimum value.\n *\n * @param {number} min - The minimum length (inclusive)\n * @param {string} [message] - Custom error message (defaults to 'Must be at least {min} characters')\n * @returns {Validator<string>} A validator that checks if a string meets the minimum length\n *\n * @example\n * // Validate that a string is at least 3 characters long\n * const usernameValidator = minLength(3);\n * const result = usernameValidator('john_doe');\n * // If valid: { ok: true, value: 'john_doe', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = minLength(3)('jo');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be at least 3 characters' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const passwordValidator = minLength(8, 'Password must be at least 8 characters long');\n *\n * @example\n * // Used in an object schema with composition\n * const userSchema = object({\n * username: required(chain(string(), nonEmpty(), minLength(3)))\n * });\n */\nexport function minLength(min: number, message: string = `Must be at least ${min} characters`): Validator<string> {\n return (value, path = []) => {\n if (value.length < min) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a string's length is at most a maximum value.\n *\n * @param {number} max - The maximum length (inclusive)\n * @param {string} [message] - Custom error message (defaults to 'Must be at most {max} characters')\n * @returns {Validator<string>} A validator that checks if a string meets the maximum length\n *\n * @example\n * // Validate that a string is at most 50 characters long\n * const titleValidator = maxLength(50);\n * const result = titleValidator('This is a short title');\n * // If valid: { ok: true, value: 'This is a short title', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input (too long)\n * const veryLongString = 'This string is more than 10 characters long';\n * const result = maxLength(10)(veryLongString);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be at most 10 characters' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const bioValidator = maxLength(150, 'Bio must be 150 characters or less');\n *\n * @example\n * // Used in an object schema with composition\n * const postSchema = object({\n * title: required(chain(string(), maxLength(100)))\n * });\n */\nexport function maxLength(max: number, message: string = `Must be at most ${max} characters`): Validator<string> {\n return (value, path = []) => {\n if (value.length > max) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a string matches a regular expression pattern.\n *\n * @param {RegExp} regex - The regular expression to test against\n * @param {string} [message='Invalid format'] - Custom error message\n * @returns {Validator<string>} A validator that checks if a string matches the pattern\n *\n * @example\n * // Validate that a string matches a pattern (alphanumeric)\n * const alphanumericValidator = pattern(/^[a-zA-Z0-9]+$/);\n * const result = alphanumericValidator('abc123');\n * // If valid: { ok: true, value: 'abc123', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = pattern(/^\\d{5}$/)('abc');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Invalid format' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const zipCodeValidator = pattern(/^\\d{5}$/, 'ZIP code must be 5 digits');\n *\n * @example\n * // Used in an object schema\n * const addressSchema = object({\n * zipCode: optional(chain(string(), pattern(/^\\d{5}$/, 'Invalid ZIP code format')))\n * });\n */\nexport function pattern(regex: RegExp, message: string = 'Invalid format'): Validator<string> {\n return (value, path = []) => {\n if (!regex.test(value)) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a string is not empty after trimming whitespace.\n *\n * @param {string} [message='String must not be empty'] - Custom error message\n * @returns {Validator<string>} A validator that checks if a string is not empty\n *\n * @example\n * // Validate that a string is not empty\n * const nameValidator = nonEmpty();\n * const result = nameValidator('John');\n * // If valid: { ok: true, value: 'John', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input (empty string)\n * const result = nonEmpty()('');\n * // If invalid: { ok: false, error: [{ path: [], message: 'String must not be empty' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With invalid input (only whitespace)\n * const result = nonEmpty()(' ');\n * // If invalid: { ok: false, error: [{ path: [], message: 'String must not be empty' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const requiredFieldValidator = nonEmpty('This field is required');\n *\n * @example\n * // Used in an object schema with composition\n * const userSchema = object({\n * name: required(chain(string(), nonEmpty()))\n * });\n */\nexport function nonEmpty(message: string = 'String must not be empty'): Validator<string> {\n return (value, path = []) => {\n if (value.trim().length === 0) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a string is formatted as a valid email address.\n * Uses a simple regular expression to validate basic email format.\n *\n * @param {string} [message='Invalid email format'] - Custom error message\n * @returns {Validator<string>} A validator that checks if a string is a valid email\n *\n * @example\n * // Validate that a string is a valid email\n * const emailValidator = email();\n * const result = emailValidator('user@example.com');\n * // If valid: { ok: true, value: 'user@example.com', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = email()('not-an-email');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Invalid email format' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const contactEmailValidator = email('Please enter a valid email address');\n *\n * @example\n * // Used in an object schema with composition\n * const userSchema = object({\n * email: required(chain(string(), nonEmpty(), email()))\n * });\n */\nexport function email(message: string = 'Invalid email format'): Validator<string> {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return pattern(emailRegex, message);\n}\n\n/**\n * Creates a validator that ensures a string is formatted as a valid phone number.\n * Uses a flexible regex that accepts common phone number formats including:\n * - International format with + prefix\n * - Numbers with spaces, dashes, or parentheses\n * - 8 to 20 digits total\n *\n * @param {string} [message='Invalid phone number format'] - Custom error message\n * @returns {Validator<string>} A validator that checks if a string is a valid phone number\n *\n * @example\n * // Validate that a string is a valid phone number\n * const phoneValidator = phoneNumber();\n * const result = phoneValidator('+1-555-123-4567');\n * // If valid: { ok: true, value: '+1-555-123-4567', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Accepts various formats\n * phoneNumber()('123-456-7890'); // ok\n * phoneNumber()('(555) 123-4567'); // ok\n * phoneNumber()('+44 20 7123 1234'); // ok\n * phoneNumber()('555 123 4567'); // ok\n *\n * @example\n * // With invalid input\n * const result = phoneNumber()('not-a-phone');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Invalid phone number format' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const contactPhoneValidator = phoneNumber('Please enter a valid phone number');\n *\n * @example\n * // Used in an object schema with composition\n * const contactSchema = object({\n * phone: optional(chain(string(), phoneNumber()))\n * });\n *\n * @example\n * // For stricter validation, use pattern() with a custom regex\n * const usPhoneValidator = pattern(/^\\d{3}-\\d{3}-\\d{4}$/, 'Must be in format XXX-XXX-XXXX');\n */\nexport function phoneNumber(message: string = 'Invalid phone number format'): Validator<string> {\n // Flexible regex that accepts common phone formats\n // Allows optional + prefix, digits, spaces, dashes, and parentheses\n // Total length should be reasonable for a phone number (8-20 chars after removing spaces)\n const phoneRegex = /^\\+?[\\d\\s\\-()]{8,20}$/;\n return (value, path = []) => {\n // Remove all spaces for validation\n const cleanedValue = value.replaceAll(/\\s+/g, '');\n if (!phoneRegex.test(cleanedValue)) {\n return err([{ path, message }]);\n }\n return ok(value); // Return original value, not cleaned\n };\n}\n","import { err, isOk, ok } from '../result';\n\nimport { string } from './string';\nimport { chain } from './utils';\n\nimport type { ValidationError, Validator } from './core';\n\n/**\n * Creates a validator for arrays where each item is validated by the provided item validator.\n *\n * @template I - The input type of items the validator accepts\n * @template O - The output type of items after validation\n *\n * @param {Validator<I, O>} itemValidator - The validator to apply to each array item\n * @returns {Validator<unknown, O[]>} A validator that validates arrays of items\n *\n * @example\n * // Validate an array of strings\n * const stringArrayValidator = array(string());\n *\n * @example\n * // Validate an array of enum values\n * const contactsValidator = array(stringEnum(['email', 'phone']));\n * const result = contactsValidator(['email', 'phone']);\n * // If valid: { ok: true, value: ['email', 'phone'], [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * contacts: optional(array(stringEnum(['email', 'phone'])))\n * });\n */\nexport function array<I, O>(itemValidator: Validator<I, O>): Validator<unknown, O[]> {\n return (value, parentPath = []) => {\n if (!Array.isArray(value)) {\n return err([{ path: parentPath, message: 'Expected an array' }]);\n }\n\n const allErrors: ValidationError[] = [];\n const validatedItems: O[] = [];\n\n for (const [i, item] of value.entries()) {\n const itemPath = [...parentPath, i.toString()];\n\n const result = itemValidator(item as I, itemPath);\n\n if (isOk(result)) {\n validatedItems.push(result.value);\n } else {\n allErrors.push(...result.error);\n }\n }\n\n if (allErrors.length > 0) {\n return err(allErrors);\n }\n\n return ok(validatedItems);\n };\n}\n\n/**\n * Validates that an array has at least a minimum number of items\n *\n * @template T - The type of array elements\n * @param {number} min - The minimum number of items required\n * @param {string} [message] - Custom error message\n * @returns {Validator<T[], T[]>} A validator that checks minimum array length\n *\n * @example\n * // Validate that an array has at least 2 items\n * const validator = minItems(2);\n * const result = validator([1, 2, 3]);\n * // If valid: { ok: true, value: [1, 2, 3], [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With custom error message\n * const validator = minItems(3, 'Need at least 3 items');\n * const result = validator([1, 2]);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Need at least 3 items' }], [RESULT_BRAND]: 'err' }\n */\nexport function minItems<T>(\n min: number,\n message: string = `Array must have at least ${min} items`,\n): Validator<T[], T[]> {\n return (value, path = []) => {\n if (value.length < min) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Validates that an array has at most a maximum number of items\n *\n * @template T - The type of array elements\n * @param {number} max - The maximum number of items allowed\n * @param {string} [message] - Custom error message\n * @returns {Validator<T[], T[]>} A validator that checks maximum array length\n *\n * @example\n * // Validate that an array has at most 5 items\n * const validator = maxItems(5);\n * const result = validator([1, 2, 3]);\n * // If valid: { ok: true, value: [1, 2, 3], [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With custom error message\n * const validator = maxItems(2, 'Cannot exceed 2 items');\n * const result = validator([1, 2, 3]);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Cannot exceed 2 items' }], [RESULT_BRAND]: 'err' }\n */\nexport function maxItems<T>(\n max: number,\n message: string = `Array must have at most ${max} items`,\n): Validator<T[], T[]> {\n return (value, path = []) => {\n if (value.length > max) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Validates that an array is not empty\n *\n * @template T - The type of array elements\n * @param {string} [message='Array must not be empty'] - Custom error message\n * @returns {Validator<T[], T[]>} A validator that checks the array is not empty\n *\n * @example\n * // Validate that an array is not empty\n * const validator = notEmpty();\n * const result = validator([1]);\n * // If valid: { ok: true, value: [1], [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With empty array\n * const validator = notEmpty('Please provide at least one item');\n * const result = validator([]);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Please provide at least one item' }], [RESULT_BRAND]: 'err' }\n */\nexport function notEmpty<T>(message: string = 'Array must not be empty'): Validator<T[], T[]> {\n return minItems(1, message);\n}\n\n/**\n * Validates that an array contains only unique values\n *\n * @template T - The type of array elements\n * @param {string} [message='Array must contain unique values'] - Custom error message\n * @param {(item: T) => unknown} [keyExtractor] - Optional function to extract a comparison key from each item\n * @returns {Validator<T[], T[]>} A validator that checks for unique array values\n *\n * @example\n * // Validate unique primitive values\n * const validator = unique();\n * const result = validator([1, 2, 3]);\n * // If valid: { ok: true, value: [1, 2, 3], [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With duplicate values\n * const validator = unique();\n * const result = validator([1, 2, 2, 3]);\n * // If invalid: { ok: false, error: [{ path: ['2'], message: 'Array must contain unique values' }], [RESULT_BRAND]: 'err' }\n *\n * @example\n * // With custom key extractor for objects\n * const validator = unique<{ id: number }>(\n * 'Duplicate ID found',\n * (item) => item.id\n * );\n * const result = validator([{ id: 1 }, { id: 2 }]);\n * // If valid: { ok: true, value: [{ id: 1 }, { id: 2 }], [RESULT_BRAND]: 'ok' }\n */\nexport function unique<T>(\n message: string = 'Array must contain unique values',\n keyExtractor?: (item: T) => unknown,\n): Validator<T[], T[]> {\n return (value, path = []) => {\n const seen = new Set();\n\n for (const [i, item] of value.entries()) {\n const key = keyExtractor ? keyExtractor(item) : item;\n\n if (seen.has(key)) {\n return err([\n {\n path: [...path, i.toString()],\n message,\n },\n ]);\n }\n seen.add(key);\n }\n\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a value is one of the allowed values.\n *\n * @template T - The type of the values being validated\n *\n * @param {T[]} allowedValues - Array of acceptable values\n * @param {string} [message] - Custom error message (defaults to a list of allowed values)\n * @returns {Validator<T>} A validator that checks if a value is in the allowed list\n *\n * @example\n * // Validate that a value is one of the specified options\n * const statusValidator = oneOf(['pending', 'approved', 'rejected']);\n * const result = statusValidator('approved');\n * // If valid: { ok: true, value: 'approved', [RESULT_BRAND]: 'ok' }\n * // If invalid: { ok: false, error: [{ path: [], message: 'Value must be one of: pending, approved, rejected' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const priorityValidator = oneOf([1, 2, 3], 'Priority must be between 1 and 3');\n */\nexport function oneOf<T>(\n allowedValues: T[],\n message: string = `Value must be one of: ${allowedValues.join(', ')}`,\n): Validator<T> {\n return (value, path = []) => {\n if (!allowedValues.includes(value)) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a value is a string and one of the allowed enum values.\n * This validator first checks that the input is a string, then validates it against the allowed values.\n *\n * @template T - The string literal union type of allowed values\n *\n * @param {T[]} allowedValues - Array of acceptable string enum values\n * @param {string} [message] - Custom error message (defaults to a list of allowed values)\n * @returns {Validator<unknown, T>} A validator that checks if a value is a string and in the allowed list\n *\n * @example\n * // Validate that a value is one of the specified string options\n * const roleValidator = stringEnum(['admin', 'user']);\n * const result = roleValidator('admin');\n * // If valid: { ok: true, value: 'admin', [RESULT_BRAND]: 'ok' }\n * // If invalid: { ok: false, error: [{ path: [], message: 'Value must be one of: admin, user' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * role: required(stringEnum(['admin', 'user'])),\n * contacts: optional(array(stringEnum(['email', 'phone'])))\n * });\n */\nexport function stringEnum<T extends string>(\n allowedValues: T[],\n message: string = `Value must be one of: ${allowedValues.join(', ')}`,\n): Validator<unknown, T> {\n return chain(string('Value must be a string'), (value: string, path = []) => {\n if (!allowedValues.includes(value as T)) {\n return err([{ path, message }]);\n }\n return ok(value as T);\n });\n}\n","import { err, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator that ensures a value is a number and not NaN.\n *\n * @param {string} [message='Must be a number'] - Custom error message\n * @returns {Validator<unknown, number>} A validator that checks if a value is a number\n *\n * @example\n * // Validate that a value is a number\n * const ageValidator = number();\n * const result = ageValidator(25);\n * // If valid: { ok: true, value: 25, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = number()('not a number');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * price: required(number())\n * });\n */\nexport function number(message: string = 'Must be a number'): Validator<unknown, number> {\n return (value, path = []) => {\n if (typeof value !== 'number' || Number.isNaN(value)) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number is greater than or equal to a minimum value.\n *\n * @param {number} value - The minimum value (inclusive)\n * @param {string} [message] - Custom error message (defaults to 'Must be at least {value}')\n * @returns {Validator<number>} A validator that checks if a number is at least the minimum value\n *\n * @example\n * // Validate that a number is at least 18\n * const adultAgeValidator = min(18);\n * const result = adultAgeValidator(21);\n * // If valid: { ok: true, value: 21, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = min(18)(16);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be at least 18' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const priceValidator = min(10, 'Price must be at least $10');\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * age: required(chain(parseNumber(), min(18, 'Must be at least 18 years old')))\n * });\n */\nexport function min(value: number, message: string = `Must be at least ${value}`): Validator<number> {\n return (input, path = []) => {\n if (input < value) {\n return err([{ path, message }]);\n }\n return ok(input);\n };\n}\n\n/**\n * Creates a validator that ensures a number is less than or equal to a maximum value.\n *\n * @param {number} value - The maximum value (inclusive)\n * @param {string} [message] - Custom error message (defaults to 'Must be at most {value}')\n * @returns {Validator<number>} A validator that checks if a number is at most the maximum value\n *\n * @example\n * // Validate that a number is at most 100\n * const percentageValidator = max(100);\n * const result = percentageValidator(75);\n * // If valid: { ok: true, value: 75, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = max(100)(150);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be at most 100' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const quantityValidator = max(10, 'Maximum quantity is 10 items');\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * quantity: required(chain(parseNumber(), max(100, 'Maximum quantity is 100')))\n * });\n */\nexport function max(value: number, message: string = `Must be at most ${value}`): Validator<number> {\n return (input, path = []) => {\n if (input > value) {\n return err([{ path, message }]);\n }\n return ok(input);\n };\n}\n\n/**\n * Creates a validator that ensures a number is between a minimum and maximum value (inclusive).\n *\n * @param {number} min - The minimum value (inclusive)\n * @param {number} max - The maximum value (inclusive)\n * @param {string} [message] - Custom error message (defaults to 'Must be between {min} and {max}')\n * @returns {Validator<number>} A validator that checks if a number is between min and max\n *\n * @example\n * // Validate that a number is between 1 and 10\n * const ratingValidator = between(1, 10);\n * const result = ratingValidator(7);\n * // If valid: { ok: true, value: 7, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = between(1, 10)(15);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be between 1 and 10' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const ageValidator = between(18, 65, 'Age must be between 18 and 65');\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * rating: required(chain(parseNumber(), between(1, 5, 'Rating must be between 1 and 5')))\n * });\n */\nexport function between(\n min: number,\n max: number,\n message: string = `Must be between ${min} and ${max}`,\n): Validator<number> {\n return (input, path = []) => {\n if (input < min || input > max) {\n return err([{ path, message }]);\n }\n return ok(input);\n };\n}\n\n/**\n * Creates a validator that ensures a number is an integer (no decimal places).\n *\n * @param {string} [message='Must be an integer'] - Custom error message\n * @returns {Validator<number>} A validator that checks if a number is an integer\n *\n * @example\n * // Validate that a number is an integer\n * const countValidator = integer();\n * const result = countValidator(42);\n * // If valid: { ok: true, value: 42, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = integer()(3.14);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be an integer' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const quantityValidator = integer('Quantity must be a whole number');\n *\n * @example\n * // Used in an object schema\n * const orderSchema = object({\n * quantity: required(chain(parseNumber(), integer()))\n * });\n */\nexport function integer(message: string = 'Must be an integer'): Validator<number> {\n return (value, path = []) => {\n if (!Number.isInteger(value)) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number is positive (greater than zero).\n *\n * @param {string} [message='Must be a positive number'] - Custom error message\n * @returns {Validator<number>} A validator that checks if a number is positive\n *\n * @example\n * // Validate that a number is positive\n * const priceValidator = positive();\n * const result = priceValidator(29.99);\n * // If valid: { ok: true, value: 29.99, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = positive()(0); // Note: 0 is not considered positive\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a positive number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const volumeValidator = positive('Volume must be greater than zero');\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * price: required(chain(parseNumber(), positive()))\n * });\n */\nexport function positive(message: string = 'Must be a positive number'): Validator<number> {\n return (value, path = []) => {\n if (value <= 0) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number is negative (less than zero).\n *\n * @param {string} [message='Must be a negative number'] - Custom error message\n * @returns {Validator<number>} A validator that checks if a number is negative\n *\n * @example\n * // Validate that a number is negative\n * const temperatureValidator = negative();\n * const result = temperatureValidator(-5);\n * // If valid: { ok: true, value: -5, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = negative()(0); // Note: 0 is not considered negative\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a negative number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const deficitValidator = negative('Must be a deficit (negative amount)');\n *\n * @example\n * // Used in an object schema\n * const temperatureSchema = object({\n * freezingTemp: required(chain(parseNumber(), negative()))\n * });\n */\nexport function negative(message: string = 'Must be a negative number'): Validator<number> {\n return (value, path = []) => {\n if (value >= 0) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number is not zero.\n *\n * @param {string} [message='Must not be zero'] - Custom error message\n * @returns {Validator<number>} A validator that checks if a number is not zero\n *\n * @example\n * // Validate that a number is not zero\n * const divisorValidator = nonZero();\n * const result = divisorValidator(5);\n * // If valid: { ok: true, value: 5, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = nonZero()(0);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must not be zero' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const speedValidator = nonZero('Speed cannot be zero');\n *\n * @example\n * // Used in an object schema\n * const calculationSchema = object({\n * divisor: required(chain(parseNumber(), nonZero('Division by zero is not allowed')))\n * });\n */\nexport function nonZero(message: string = 'Must not be zero'): Validator<number> {\n return (value, path = []) => {\n if (value === 0) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number is divisible by a specific divisor.\n *\n * @param {number} divisor - The number that the input must be divisible by\n * @param {string} [message] - Custom error message (defaults to 'Must be divisible by {divisor}')\n * @returns {Validator<number>} A validator that checks if a number is divisible by the divisor\n *\n * @example\n * // Validate that a number is divisible by 5\n * const multipleOf5Validator = divisibleBy(5);\n * const result = multipleOf5Validator(15);\n * // If valid: { ok: true, value: 15, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = divisibleBy(5)(12);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be divisible by 5' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const evenValidator = divisibleBy(2, 'Number must be even');\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * itemsPerBox: required(chain(parseNumber(), divisibleBy(6, 'Items must be packaged in multiples of 6')))\n * });\n */\nexport function divisibleBy(divisor: number, message: string = `Must be divisible by ${divisor}`): Validator<number> {\n return (value, path = []) => {\n if (value % divisor !== 0) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number has at most the specified number of decimal places.\n *\n * @param {number} maxDecimalPlaces - The maximum number of decimal places allowed\n * @param {string} [message] - Custom error message (defaults to 'Must have at most {maxDecimalPlaces} decimal places')\n * @returns {Validator<number>} A validator that checks the number's decimal precision\n *\n * @example\n * // Validate that a number has at most 2 decimal places\n * const currencyValidator = precision(2);\n * const result = currencyValidator(10.99);\n * // If valid: { ok: true, value: 10.99, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = precision(2)(10.999);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must have at most 2 decimal places' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With custom error message\n * const percentValidator = precision(2, 'Percentage can have at most 2 decimal places');\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * price: required(chain(parseNumber(), precision(2, 'Price must have at most 2 decimal places')))\n * });\n */\nexport function precision(\n maxDecimalPlaces: number,\n message: string = `Must have at most ${maxDecimalPlaces} decimal places`,\n): Validator<number> {\n return (value, path = []) => {\n const str = value.toString();\n const decimalPlaces = (str.split('.')[1] || '').length;\n\n if (decimalPlaces > maxDecimalPlaces) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a number is finite (not Infinity or -Infinity).\n *\n * @param {string} [message='Must be a finite number'] - Custom error message\n * @returns {Validator<number>} A validator that checks if a number is finite\n *\n * @example\n * // Validate that a number is finite\n * const finiteValidator = finite();\n * const result = finiteValidator(42);\n * // If valid: { ok: true, value: 42, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input (Infinity)\n * const result = finite()(Infinity);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a finite number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With invalid input (-Infinity)\n * const result = finite()(-Infinity);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a finite number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in a chain\n * const validRatioValidator = chain(\n * number(),\n * finite(),\n * between(0, 1)\n * );\n *\n * @example\n * // Used in an object schema\n * const calculationSchema = object({\n * result: required(chain(number(), finite()))\n * });\n */\nexport function finite(message: string = 'Must be a finite number'): Validator<number> {\n return (value, path = []) => {\n if (!Number.isFinite(value)) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n","import { err, fromTry, mapErr, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator that parses input into a number.\n * Accepts both numbers and string representations of numbers.\n *\n * @param {string} [message='Must be a valid number'] - Custom error message\n * @returns {Validator<unknown, number>} A validator that parses and validates numbers\n *\n * @example\n * // Parse a string into a number\n * const ageValidator = parseNumber();\n * const result = ageValidator('25');\n * // If valid: { ok: true, value: 25, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Already a number\n * const result = parseNumber()(42);\n * // If valid: { ok: true, value: 42, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = parseNumber()('not a number');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a valid number' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * age: required(parseNumber('Age must be a valid number'))\n * });\n */\nexport function parseNumber(message: string = 'Must be a valid number'): Validator<unknown, number> {\n return (value, path = []) => {\n if (typeof value === 'number') {\n return ok(value);\n }\n\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed === '') {\n return err([{ path, message }]);\n }\n\n const num = Number(trimmed);\n if (!Number.isNaN(num)) {\n return ok(num);\n }\n }\n\n return err([{ path, message }]);\n };\n}\n\n/**\n * Creates a validator that parses input into a BigInt\n * Accepts BigInt, strings, and numbers that can be converted to BigInt\n *\n * @param {string} [message='Must be a valid BigInt'] - Custom error message\n * @returns {Validator<unknown, bigint>} A validator that parses and validates BigInt values\n *\n * @example\n * // Parse string to BigInt\n * const validator = parseBigInt();\n * const result = validator(\"9007199254740993\");\n * // If valid: { ok: true, value: 9007199254740993n, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Already a BigInt\n * const result = parseBigInt()(123n);\n * // If valid: { ok: true, value: 123n, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // From number (must be integer)\n * const result = parseBigInt()(42);\n * // If valid: { ok: true, value: 42n, [RESULT_BRAND]: 'ok' }\n */\nexport function parseBigInt(message: string = 'Must be a valid BigInt'): Validator<unknown, bigint> {\n return (value, path = []) => {\n // Already a BigInt\n if (typeof value === 'bigint') {\n return ok(value);\n }\n\n // Try to convert string or number to BigInt\n if (typeof value === 'string' || typeof value === 'number') {\n try {\n // For numbers, check they're integers first\n if (typeof value === 'number' && !Number.isInteger(value)) {\n return err([\n {\n path,\n message: 'Cannot convert non-integer number to BigInt',\n },\n ]);\n }\n\n const bigIntValue = BigInt(value);\n return ok(bigIntValue);\n } catch {\n return err([{ path, message }]);\n }\n }\n\n return err([{ path, message }]);\n };\n}\n\n/**\n * Creates a validator that parses input into enum values\n * Handles string/number to enum conversions with flexible matching\n *\n * @template T - The enum object type\n * @param {T} enumObject - The enum object to parse values into\n * @param {string} [message] - Custom error message\n * @returns {Validator<unknown, T[keyof T]>} A validator that parses to enum values\n *\n * @example\n * // String enum\n * enum Status {\n * Pending = \"PENDING\",\n * Approved = \"APPROVED\"\n * }\n *\n * const parser = parseEnum(Status);\n * const result = parser(\"PENDING\");\n * // If valid: { ok: true, value: \"PENDING\", [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Case-insensitive key matching\n * const result = parser(\"pending\"); // Matches Status.Pending\n *\n * @example\n * // Numeric enum\n * enum Priority {\n * Low = 0,\n * High = 1\n * }\n * const parser = parseEnum(Priority);\n * const result = parser(\"0\"); // Parses to Priority.Low\n */\nexport function parseEnum<T extends Record<string, string | number>>(\n enumObject: T,\n message: string = `Must be a valid enum value`,\n): Validator<unknown, T[keyof T]> {\n return (value, path = []) => {\n // Get only the actual enum values (filter out reverse mappings for numeric enums)\n const enumEntries = Object.entries(enumObject).filter(\n ([key]) => Number.isNaN(Number(key)) || !Number.isInteger(Number(key)),\n );\n // eslint-disable-next-line unicorn/prefer-set-has\n const enumValues = enumEntries.map(([, val]) => val);\n\n // Already a valid enum value\n if (enumValues.includes(value as T[keyof T])) {\n return ok(value as T[keyof T]);\n }\n\n // For strings\n if (typeof value === 'string') {\n // Try parsing as a number first for numeric enums\n const parsed = Number(value);\n if (!Number.isNaN(parsed) && enumValues.includes(parsed as T[keyof T])) {\n return ok(parsed as T[keyof T]);\n }\n\n // Try exact key match\n const exactEntry = enumEntries.find(([key]) => key === value);\n if (exactEntry) {\n return ok(exactEntry[1] as T[keyof T]);\n }\n\n // Try case-insensitive key match\n const lowerValue = value.toLowerCase();\n const caseInsensitiveEntry = enumEntries.find(([key]) => key.toLowerCase() === lowerValue);\n if (caseInsensitiveEntry) {\n return ok(caseInsensitiveEntry[1] as T[keyof T]);\n }\n }\n\n return err([\n {\n path,\n message,\n },\n ]);\n };\n}\n\n/**\n * Creates a validator that parses input into a Date object.\n * Accepts Date objects, strings that can be parsed as dates, and numeric timestamps.\n *\n * @param {string} [message='Must be a valid date'] - Custom error message\n * @returns {Validator<unknown, Date>} A validator that parses and validates dates\n *\n * @example\n * // Parse a string into a Date\n * const birthdateValidator = parseDate();\n * const result = birthdateValidator('1990-05-15');\n * // If valid: { ok: true, value: Date(1990-05-15), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Already a Date object\n * const today = new Date();\n * const result = parseDate()(today);\n * // If valid: { ok: true, value: today, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With timestamp\n * const result = parseDate()(1621036800000); // May 15, 2021\n * // If valid: { ok: true, value: Date(2021-05-15), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = parseDate()('not a date');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a valid date' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const eventSchema = object({\n * eventDate: required(parseDate('Event date must be valid'))\n * });\n */\nexport function parseDate(message: string = 'Must be a valid date'): Validator<unknown, Date> {\n return (value, path = []) => {\n if (value instanceof Date) {\n return ok(value);\n }\n\n let dateValue: Date;\n\n if (typeof value === 'string') {\n dateValue = new Date(value);\n } else if (typeof value === 'number') {\n dateValue = new Date(value);\n } else {\n return err([{ path, message }]);\n }\n\n if (Number.isNaN(dateValue.getTime())) {\n return err([{ path, message }]);\n }\n\n return ok(dateValue);\n };\n}\n\n/**\n * Creates a validator that parses input into a boolean.\n * Accepts booleans, 0/1, and strings like 'true'/'false', 'yes'/'no'.\n *\n * @param {string} [message='Must be a valid boolean value'] - Custom error message\n * @returns {Validator<unknown, boolean>} A validator that parses and validates booleans\n *\n * @example\n * // Parse a string into a boolean\n * const consentValidator = parseBool();\n * const result = consentValidator('yes');\n * // If valid: { ok: true, value: true, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Various truthy values\n * parseBool()('true'); // { ok: true, value: true }\n * parseBool()('yes'); // { ok: true, value: true }\n * parseBool()('1'); // { ok: true, value: true }\n * parseBool()(1); // { ok: true, value: true }\n *\n * @example\n * // Various falsy values\n * parseBool()('false'); // { ok: true, value: false }\n * parseBool()('no'); // { ok: true, value: false }\n * parseBool()('0'); // { ok: true, value: false }\n * parseBool()(0); // { ok: true, value: false }\n *\n * @example\n * // With invalid input\n * const result = parseBool()('maybe');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a valid boolean value' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const userSchema = object({\n * hasAcceptedTerms: required(parseBool('Please indicate whether you accept the terms'))\n * });\n */\nexport function parseBool(message: string = 'Must be a valid boolean value'): Validator<unknown, boolean> {\n return (value, path = []) => {\n if (typeof value === 'boolean') {\n return ok(value);\n }\n\n if (typeof value === 'string') {\n const normalized = value.toLowerCase().trim();\n if (normalized === 'true' || normalized === '1' || normalized === 'yes') {\n return ok(true);\n }\n if (normalized === 'false' || normalized === '0' || normalized === 'no') {\n return ok(false);\n }\n }\n\n if (typeof value === 'number') {\n if (value === 1) return ok(true);\n if (value === 0) return ok(false);\n }\n\n return err([{ path, message }]);\n };\n}\n\n/**\n * Creates a validator that parses input into a string.\n * Accepts strings and any value that can be converted to a string, except null and undefined.\n *\n * @param {string} [message='Must be convertible to string'] - Custom error message\n * @returns {Validator<unknown, string>} A validator that parses and validates strings\n *\n * @example\n * // Convert a number to string\n * const codeValidator = parseString();\n * const result = codeValidator(12345);\n * // If valid: { ok: true, value: '12345', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Already a string\n * const result = parseString()('hello');\n * // If valid: { ok: true, value: 'hello', [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = parseString()(null);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be convertible to string' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const productSchema = object({\n * sku: required(parseString('Product SKU is required'))\n * });\n */\nexport function parseString(message: string = 'Must be convertible to string'): Validator<unknown, string> {\n return (value, path = []) => {\n if (typeof value === 'string') {\n return ok(value);\n }\n\n if (value === null || value === undefined) {\n return err([{ path, message }]);\n }\n\n return ok(String(value));\n };\n}\n\n/**\n * Creates a validator that parses JSON strings into objects.\n * Accepts JSON strings or already parsed objects.\n *\n * @param {string} [message='Must be valid JSON'] - Custom error message\n * @returns {Validator<unknown, unknown>} A validator that parses and validates JSON\n *\n * @example\n * // Parse a JSON string\n * const configValidator = parseJSON();\n * const result = configValidator('{\"name\":\"John\",\"age\":30}');\n * // If valid: { ok: true, value: {name: 'John', age: 30}, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Already an object\n * const result = parseJSON()({name: 'John', age: 30});\n * // If valid: { ok: true, value: {name: 'John', age: 30}, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = parseJSON()('{name: John}'); // Invalid JSON syntax\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be valid JSON' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const configSchema = object({\n * settings: required(parseJSON('Settings must be valid JSON'))\n * });\n */\nexport function parseJSON(message: string = 'Must be valid JSON'): Validator<unknown, unknown> {\n return (value, path = []) => {\n if (typeof value === 'string') {\n return mapErr(\n fromTry(() => JSON.parse(value)),\n () => [{ path, message }],\n );\n }\n\n if (typeof value === 'object' && value !== null) {\n return ok(value);\n }\n\n return err([{ path, message }]);\n };\n}\n\n/**\n * Creates a validator that parses ISO format date strings (YYYY-MM-DD) into Date objects.\n * Performs strict validation of the date format and validity.\n *\n * @param {string} [message='Must be a valid ISO date string'] - Custom error message\n * @returns {Validator<unknown, Date>} A validator that parses and validates ISO date strings\n *\n * @example\n * // Parse an ISO date string\n * const birthdateValidator = parseISODate();\n * const result = birthdateValidator('2021-05-15');\n * // If valid: { ok: true, value: Date(2021-05-15), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid format\n * const result = parseISODate()('15/05/2021');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a valid ISO date string' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // With invalid date\n * const result = parseISODate()('2021-02-30'); // February doesn't have 30 days\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a valid ISO date string' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const eventSchema = object({\n * startDate: required(parseISODate('Start date must be in YYYY-MM-DD format'))\n * });\n */\nexport function parseISODate(message: string = 'Must be a valid ISO date string'): Validator<unknown, Date> {\n return (value, path = []) => {\n if (typeof value !== 'string') {\n return err([{ path, message }]);\n }\n\n if (!/^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n return err([{ path, message }]);\n }\n\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n return err([{ path, message }]);\n }\n\n const originalMonth = value.slice(5, 7);\n const originalDay = value.slice(8, 10);\n const parsedMonth = String(date.getUTCMonth() + 1).padStart(2, '0');\n const parsedDay = String(date.getUTCDate()).padStart(2, '0');\n\n if (originalMonth !== parsedMonth || originalDay !== parsedDay) {\n return err([{ path, message }]);\n }\n\n return ok(date);\n };\n}\n\n/**\n * Creates a validator that parses string URLs into URL objects.\n * Validates that the URL is properly formatted and can be parsed.\n *\n * @param {string} [message='Must be a valid URL'] - Custom error message\n * @returns {Validator<unknown, URL>} A validator that parses and validates URLs\n *\n * @example\n * // Parse a URL string\n * const websiteValidator = parseURL();\n * const result = websiteValidator('https://example.com');\n * // If valid: { ok: true, value: URL { href: 'https://example.com/', ... }, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With protocol and path\n * const result = parseURL()('https://example.com/path?query=value');\n * // If valid: { ok: true, value: URL { href: 'https://example.com/path?query=value', ... }, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = parseURL()('not-a-url');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a valid URL' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const profileSchema = object({\n * website: optional(parseURL('Website must be a valid URL'))\n * });\n */\nexport function parseURL(message: string = 'Must be a valid URL'): Validator<unknown, URL> {\n return (value, path = []) => {\n if (typeof value !== 'string') {\n return err([{ path, message }]);\n }\n\n try {\n return ok(new URL(value));\n } catch {\n return err([{ path, message }]);\n }\n };\n}\n","import { err, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator that ensures a value is a Date object\n *\n * @param {string} [message='Must be a Date object'] - Custom error message\n * @returns {Validator<unknown, Date>} A validator that checks if value is a valid Date\n *\n * @example\n * // Basic Date validation\n * const validator = date();\n * const result = validator(new Date());\n * // If valid: { ok: true, value: Date, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // Chain with other date validators\n * const futureDateValidator = chain(date(), futureDate());\n */\nexport function date(message: string = 'Must be a Date object'): Validator<unknown, Date> {\n return (value, path = []) => {\n if (!(value instanceof Date)) {\n return err([{ path, message }]);\n }\n\n // Check for Invalid Date\n if (Number.isNaN(value.getTime())) {\n return err([\n {\n path,\n message: 'Invalid Date',\n },\n ]);\n }\n\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a Date is within a specified range.\n *\n * @param {Date} min - The minimum valid date (inclusive)\n * @param {Date} max - The maximum valid date (inclusive)\n * @param {string} [message] - Custom error message (defaults to a readable date range)\n * @returns {Validator<Date>} A validator that checks if a date is between min and max\n *\n * @example\n * // Validate that a date is within a specific range\n * const birthDate = new Date('1950-01-01');\n * const today = new Date();\n * const birthDateValidator = dateRange(birthDate, today);\n *\n * const result = birthDateValidator(new Date('1990-05-15'));\n * // If valid: { ok: true, value: Date(1990-05-15), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With custom error message\n * const validPeriod = dateRange(\n * new Date('2023-01-01'),\n * new Date('2023-12-31'),\n * 'The date must be within the 2023 calendar year'\n * );\n *\n * @example\n * // Used in an object schema\n * const eventSchema = object({\n * eventDate: required(chain(parseDate(), dateRange(startDate, endDate)))\n * });\n */\nexport function dateRange(\n min: Date,\n max: Date,\n message: string = `Must be between ${min.toISOString().split('T')[0]} and ${max.toISOString().split('T')[0]}`,\n): Validator<Date> {\n return (value, path = []) => {\n if (value < min || value > max) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a Date is in the past (before the current date and time).\n *\n * @param {string} [message='Must be a date in the past'] - Custom error message\n * @returns {Validator<Date>} A validator that checks if a date is in the past\n *\n * @example\n * // Validate that a date is in the past\n * const birthDateValidator = pastDate();\n * const result = birthDateValidator(new Date('1990-01-01'));\n * // If valid: { ok: true, value: Date(1990-01-01), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With future date (invalid)\n * const tomorrow = new Date();\n * tomorrow.setDate(tomorrow.getDate() + 1);\n * const result = pastDate()(tomorrow);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a date in the past' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema with custom message\n * const userSchema = object({\n * birthDate: required(chain(parseDate(), pastDate('Birth date must be in the past')))\n * });\n */\nexport function pastDate(message: string = 'Must be a date in the past'): Validator<Date> {\n return (value, path = []) => {\n if (value >= new Date()) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a Date is in the future (after the current date and time).\n *\n * @param {string} [message='Must be a date in the future'] - Custom error message\n * @returns {Validator<Date>} A validator that checks if a date is in the future\n *\n * @example\n * // Validate that a date is in the future\n * const expiryDateValidator = futureDate();\n * const nextYear = new Date();\n * nextYear.setFullYear(nextYear.getFullYear() + 1);\n * const result = expiryDateValidator(nextYear);\n * // If valid: { ok: true, value: Date(next-year), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With past date (invalid)\n * const lastYear = new Date();\n * lastYear.setFullYear(lastYear.getFullYear() - 1);\n * const result = futureDate()(lastYear);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a date in the future' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema with custom message\n * const subscriptionSchema = object({\n * expirationDate: required(chain(parseDate(), futureDate('Expiration date must be in the future')))\n * });\n */\nexport function futureDate(message: string = 'Must be a date in the future'): Validator<Date> {\n return (value, path = []) => {\n if (value <= new Date()) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a Date is either today or in the future.\n * This validator uses calendar date comparison (ignoring time portions).\n *\n * @param {string} [message='Must be today or a future date'] - Custom error message\n * @returns {Validator<Date>} A validator that checks if a date is today or in the future\n *\n * @example\n * // Validate that a date is today or later\n * const deliveryDateValidator = todayOrFuture();\n * const tomorrow = new Date();\n * tomorrow.setDate(tomorrow.getDate() + 1);\n * const result = deliveryDateValidator(tomorrow);\n * // If valid: { ok: true, value: Date(tomorrow), [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With a date from yesterday (invalid)\n * const yesterday = new Date();\n * yesterday.setDate(yesterday.getDate() - 1);\n * const result = todayOrFuture()(yesterday);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be today or a future date' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema with custom message\n * const eventSchema = object({\n * startDate: required(chain(parseDate(), todayOrFuture('Event must start today or in the future')))\n * });\n */\nexport function todayOrFuture(message: string = 'Must be today or a future date'): Validator<Date> {\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n\n return (value, path = []) => {\n if (value < today) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n","import { err, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator that ensures a value is a boolean.\n *\n * @param {string} [message='Must be a boolean'] - Custom error message\n * @returns {Validator<unknown, boolean>} A validator that checks if a value is a boolean\n *\n * @example\n * // Validate that a value is a boolean\n * const boolValidator = boolean();\n * const result = boolValidator(true);\n * // If valid: { ok: true, value: true, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input\n * const result = boolean()('not a boolean');\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a boolean' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const featureSchema = object({\n * isEnabled: required(boolean())\n * });\n */\nexport function boolean(message: string = 'Must be a boolean'): Validator<unknown, boolean> {\n return (value, path = []) => {\n if (typeof value !== 'boolean') {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n\n/**\n * Creates a validator that ensures a boolean value matches the expected value.\n *\n * @param {boolean} expected - The expected boolean value\n * @param {string} [message] - Custom error message (defaults to 'Value must be {expected}')\n * @returns {Validator<boolean>} A validator that confirms the value matches the expected boolean\n *\n * @example\n * // Validate that a feature is enabled (true)\n * const enabledValidator = matches(true);\n * const result = enabledValidator(true);\n * // If valid: { ok: true, value: true, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With custom message\n * const disabledValidator = matches(false, 'The option must be turned off');\n * const result = disabledValidator(true);\n * // If invalid: { ok: false, error: [{ path: [], message: 'The option must be turned off' }], [RESULT_BRAND]: 'error' }\n *\n * @example\n * // Used in an object schema\n * const featureSchema = object({\n * isEnabled: required(matches(true, 'This feature must be enabled'))\n * });\n */\nexport function matches(expected: boolean, message: string = `Value must be ${expected}`): Validator<boolean> {\n return (value, path = []) => {\n if (value !== expected) {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n","import { err, isErr, isOk, ok, type Result } from '../result';\n\nimport type { ValidationError, Validator } from './core';\n\n/**\n * Creates a validator that checks if a value matches any of the provided validators\n * Returns the result of the first successful validator, or all errors if all validators fail\n *\n * @template I - Common input type for all validators\n * @template O1, O2, ..., On - Output types for each validator\n * @param {Array<Validator<I, any>>} validators - Array of validators to try in order\n * @param {Object} [options] - Configuration options\n * @param {boolean} [options.collectAllErrors=true] - Whether to collect errors from all validators\n * @param {string} [options.errorPrefix] - Optional prefix for each error message\n * @returns {Validator<I, O1 | O2 | ... | On>} A validator that succeeds if any of the provided validators succeed\n *\n * @example\n * // Define multiple possible schemas for a message\n * const textMessageSchema = object({\n * type: required(stringEnum([\"text\"])),\n * content: required(string())\n * });\n *\n * const imageMessageSchema = object({\n * type: required(stringEnum([\"image\"])),\n * url: required(string()),\n * caption: optional(string())\n * });\n *\n * // Create a union validator for messages\n * const messageValidator = union([textMessageSchema, imageMessageSchema]);\n *\n * // Infer the message type from the schema\n * type Message = InferSchemaType<typeof messageValidator>;\n * // Equivalent to: type Message = { type: \"text\", content: string } | { type: \"image\", url: string, caption?: string }\n *\n * // Usage\n * const result = validate(messageData, messageValidator);\n */\nexport function union<I>(\n validators: [],\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, never>;\n\nexport function union<I, O1>(\n validators: [Validator<I, O1>],\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, O1>;\n\nexport function union<I, O1, O2>(\n validators: [Validator<I, O1>, Validator<I, O2>],\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, O1 | O2>;\n\nexport function union<I, O1, O2, O3>(\n validators: [Validator<I, O1>, Validator<I, O2>, Validator<I, O3>],\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, O1 | O2 | O3>;\n\nexport function union<I, O1, O2, O3, O4>(\n validators: [Validator<I, O1>, Validator<I, O2>, Validator<I, O3>, Validator<I, O4>],\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, O1 | O2 | O3 | O4>;\n\nexport function union<I, O1, O2, O3, O4, O5>(\n validators: [Validator<I, O1>, Validator<I, O2>, Validator<I, O3>, Validator<I, O4>, Validator<I, O5>],\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, O1 | O2 | O3 | O4 | O5>;\n\nexport function union<I, O>(\n validators: Array<Validator<I, O>>,\n options?: {\n collectAllErrors?: boolean;\n errorPrefix?: string;\n },\n): Validator<I, O> {\n const { collectAllErrors = true, errorPrefix } = options || {};\n\n return (value, parentPath = []) => {\n if (validators.length === 0) {\n return err([{ path: parentPath, message: 'No validators provided to union' }]);\n }\n\n const allErrors: ValidationError[][] = [];\n\n // Try each validator in order\n for (const validator of validators) {\n const result = validator(value, parentPath);\n\n if (isOk(result)) {\n // Return the first successful result\n return result;\n }\n\n // Collect errors for error reporting\n allErrors.push(result.error);\n\n // If we don't need to collect all errors, we can stop at the first failure\n if (!collectAllErrors) {\n break;\n }\n }\n\n // If all validators failed, combine all errors\n const combinedErrors = allErrors.flat().map((error) => ({\n path: error.path,\n message: errorPrefix ? `${errorPrefix}: ${error.message}` : error.message,\n }));\n\n return err(combinedErrors);\n };\n}\n\n/**\n * Creates a discriminated union validator that selects the validator based on\n * a discriminant field's value\n *\n * @template T - The expected output type of the validator\n * @param {string} discriminantField - The name of the field to use as discriminant\n * @param {Record<string, Validator<unknown, unknown>>} validatorMap - Map of discriminant values to validators\n * @param {string} [fallbackMessage] - Message to use when the discriminant value is not found\n * @returns {Validator<unknown, T>} A validator that selects the appropriate schema based on the discriminant\n *\n * @example\n * // Define schemas for different message types\n * const textMessageSchema = object({\n * type: required(stringEnum([\"text\"])),\n * content: required(string())\n * });\n *\n * const imageMessageSchema = object({\n * type: required(stringEnum([\"image\"])),\n * url: required(string()),\n * caption: optional(string())\n * });\n *\n * // Create a discriminated union validator using the 'type' field\n * const messageValidator = discriminatedUnion<Message>('type', {\n * text: textMessageSchema,\n * image: imageMessageSchema\n * });\n */\nexport function discriminatedUnion<T>(\n discriminantField: string,\n validatorMap: Record<string, Validator<unknown, unknown>>,\n fallbackMessage: string = `Invalid discriminant value for '${discriminantField}'`,\n): Validator<unknown, T> {\n return (value, parentPath = []) => {\n // Ensure value is an object\n if (value === null || typeof value !== 'object') {\n return err([{ path: parentPath, message: 'Expected an object' }]);\n }\n\n // Extract the discriminant value\n // eslint-disable-next-line security/detect-object-injection\n const discriminantValue = (value as Record<string, unknown>)[discriminantField];\n\n // Ensure discriminant value exists and is a string\n if (typeof discriminantValue !== 'string') {\n return err([\n {\n path: [...parentPath, discriminantField],\n message: `Missing or invalid discriminant field '${discriminantField}'`,\n },\n ]);\n }\n\n // Get the validator for this discriminant value\n // eslint-disable-next-line security/detect-object-injection\n const validator = validatorMap[discriminantValue];\n\n // If no validator is found for this discriminant value, return an error\n if (!validator) {\n return err([\n {\n path: [...parentPath, discriminantField],\n message: `${fallbackMessage}: '${discriminantValue}'`,\n },\n ]);\n }\n\n // Apply the selected validator and cast the result to the expected type\n return validator(value, parentPath) as Result<T, ValidationError[]>;\n };\n}\n\n/**\n * Combines a common fields validator with a discriminated union validator\n * This allows you to validate fields that are common across all variants\n * of a discriminated union\n *\n * @template C - Type of common fields\n * @template S - Type of the specific variant fields\n * @param {Validator<unknown, C>} commonSchema - Validator for common fields\n * @param {Validator<unknown, S>} specificSchema - Discriminated union validator\n * @returns {Validator<unknown, C & S>} A validator that validates both common and specific fields\n *\n * @example\n * // Define common fields for all maneuvers\n * const commonFieldsSchema = object({\n * startEpoch: required(parseDate()),\n * endEpoch: required(parseDate())\n * });\n *\n * // Create a discriminated union for specific maneuver types\n * const maneuverTypeSchema = discriminatedUnion('type', {\n * 'manual_burn': manualBurnSchema,\n * 'inclination_change': inclinationChangeSchema\n * });\n *\n * // Combine common fields with type-specific fields\n * const completeManeuverSchema = withCommonFields(\n * commonFieldsSchema,\n * maneuverTypeSchema\n * );\n */\n\nexport function withCommonFields<C, S>(\n commonSchema: Validator<unknown, C>,\n specificSchema: Validator<unknown, S>,\n): Validator<unknown, C & S> {\n return (value, path = []) => {\n // First validate common fields\n const commonResult = commonSchema(value, path);\n if (isErr(commonResult)) {\n return commonResult;\n }\n\n // Then validate specific fields\n const specificResult = specificSchema(value, path);\n if (isErr(specificResult)) {\n return specificResult;\n }\n\n // Combine the validated results\n const combinedValue = {\n ...commonResult.value,\n ...specificResult.value,\n } as C & S;\n\n return ok(combinedValue);\n };\n}\n","import { err, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator for TypeScript enum values\n * Works with both string and numeric enums\n *\n * @template T - The enum object type\n * @param {T} enumObject - The enum object to validate against\n * @param {string} [message] - Custom error message when the value is not a valid enum value\n * @param {T[keyof T][]} [excludedValues] - Invalid values which to be excluded from the enum\n * @returns {Validator<unknown, T[keyof T]>} A validator that ensures the value is a valid enum value\n *\n * @example\n * // Define an enum\n * enum Status {\n * Pending = \"PENDING\",\n * Approved = \"APPROVED\",\n * Rejected = \"REJECTED\"\n * }\n *\n * // Create validator for the enum\n * const statusValidator = enumValue(Status);\n *\n * @example\n * // With numeric enum\n * enum Priority {\n * Low = 0,\n * Medium = 1,\n * High = 2\n * }\n * const priorityValidator = enumValue(Priority);\n * const result = priorityValidator(1);\n * // If valid: { ok: true, value: 1, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With excluded values\n * const activeStatusValidator = enumValue(Status, \"Status not allowed\", [\"REJECTED\"]);\n * const result = activeStatusValidator(\"REJECTED\");\n * // If invalid: { ok: false, error: [{ path: [], message: 'Status not allowed' }], [RESULT_BRAND]: 'error' }\n */\nexport function enumValue<T extends Record<string, string | number>>(\n enumObject: T,\n message?: string,\n excludedValues?: T[keyof T][],\n): Validator<unknown, T[keyof T]> {\n return (value, path = []) => {\n const enumValues = Object.values(enumObject);\n\n if (!enumValues.includes(value as T[keyof T])) {\n const defaultMessage = `Value must be one of: ${enumValues.join(', ')}`;\n return err([{ path, message: message || defaultMessage }]);\n }\n\n if (excludedValues && excludedValues.includes(value as T[keyof T])) {\n const defaultMessage = `Selected value is excluded from valid enum values`;\n return err([{ path, message: `${message || defaultMessage}` }]);\n }\n\n return ok(value as T[keyof T]);\n };\n}\n","import { err, ok } from '../result';\n\nimport type { Validator } from './core';\n\n/**\n * Creates a validator that ensures a value is a bigint\n *\n * @param {string} [message] - Custom error message when validation fails\n * @returns {Validator<unknown, bigint>} A validator that checks if the value is a bigint\n *\n * @example\n * // Validate that a field is a bigint\n * const timestampField = required(bigint());\n * const schema = object({ timestampUnix: timestampField });\n *\n * @example\n * // With valid bigint input\n * const validator = bigint();\n * const result = validator(9007199254740993n);\n * // If valid: { ok: true, value: 9007199254740993n, [RESULT_BRAND]: 'ok' }\n *\n * @example\n * // With invalid input (regular number)\n * const result = bigint()(123);\n * // If invalid: { ok: false, error: [{ path: [], message: 'Must be a bigint' }], [RESULT_BRAND]: 'error' }\n */\nexport function bigint(message: string = 'Must be a bigint'): Validator<unknown, bigint> {\n return (value, path = []) => {\n if (typeof value !== 'bigint') {\n return err([{ path, message }]);\n }\n return ok(value);\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export { O as Option, R as Result, N as andThen, b as bimapOption, x as bimapResult, D as combineAllResult, h as combineOption, C as combineResult, l as err, c as filterOption, y as filterResult, f as flatMapOption, w as flatMapResult, g as fromNullableOption, K as fromPromise, L as fromPromiseWithError, I as fromTry, J as fromTryWithError, q as isErr, a as isNone, p as isOk, i as isSome, v as mapErrorResult, m as mapOption, r as mapResult, H as mapToOption, k as mapToResult, j as matchOption, E as matchResult, n as none, o as ok, s as some, G as tapErrorResult, t as tapOption, F as tapResult, M as toPromise, u as unwrapOption, d as unwrapOptionOr, e as unwrapOptionOrElse, z as unwrapResult, A as unwrapResultOr, B as unwrapResultOrElse } from './index-BdfKTZ7O.cjs';
2
+ export { curry, flow, pipe, tupled, uncurry, untupled } from './composition/index.cjs';
3
+ export { InferSchemaType, Schema, ValidationError, ValidationResult, Validator, array, between, bigint, boolean, chain, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, required, string, stringEnum, todayOrFuture, transform, union, unique, validate, validateAndFormatResult, withCommonFields } from './schema/index.cjs';
@@ -0,0 +1,3 @@
1
+ export { O as Option, R as Result, N as andThen, b as bimapOption, x as bimapResult, D as combineAllResult, h as combineOption, C as combineResult, l as err, c as filterOption, y as filterResult, f as flatMapOption, w as flatMapResult, g as fromNullableOption, K as fromPromise, L as fromPromiseWithError, I as fromTry, J as fromTryWithError, q as isErr, a as isNone, p as isOk, i as isSome, v as mapErrorResult, m as mapOption, r as mapResult, H as mapToOption, k as mapToResult, j as matchOption, E as matchResult, n as none, o as ok, s as some, G as tapErrorResult, t as tapOption, F as tapResult, M as toPromise, u as unwrapOption, d as unwrapOptionOr, e as unwrapOptionOrElse, z as unwrapResult, A as unwrapResultOr, B as unwrapResultOrElse } from './index-BdfKTZ7O.js';
2
+ export { curry, flow, pipe, tupled, uncurry, untupled } from './composition/index.js';
3
+ export { InferSchemaType, Schema, ValidationError, ValidationResult, Validator, array, between, bigint, boolean, chain, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, required, string, stringEnum, todayOrFuture, transform, union, unique, validate, validateAndFormatResult, withCommonFields } from './schema/index.js';