ts-rules-composer 0.0.1

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 (83) hide show
  1. package/.editorconfig +15 -0
  2. package/.eslintrc.json +66 -0
  3. package/.github/CONTRIBUTING.md +3 -0
  4. package/.github/ISSUE_TEMPLATE.md +9 -0
  5. package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
  6. package/.github/workflows/docs.yml +29 -0
  7. package/.github/workflows/publish.yml +25 -0
  8. package/.github/workflows/test.yml +37 -0
  9. package/.prettierignore +2 -0
  10. package/.releaserc +11 -0
  11. package/LICENSE +21 -0
  12. package/README.md +625 -0
  13. package/dist/index.cjs +2 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.cts +634 -0
  16. package/dist/index.d.ts +634 -0
  17. package/dist/index.js +2 -0
  18. package/dist/index.js.map +1 -0
  19. package/package.json +64 -0
  20. package/src/lib/combinators/index.ts +2 -0
  21. package/src/lib/combinators/logic/every.spec.ts +264 -0
  22. package/src/lib/combinators/logic/every.ts +47 -0
  23. package/src/lib/combinators/logic/if-else.spec.ts +72 -0
  24. package/src/lib/combinators/logic/if-else.ts +39 -0
  25. package/src/lib/combinators/logic/index.ts +8 -0
  26. package/src/lib/combinators/logic/match.spec.ts +186 -0
  27. package/src/lib/combinators/logic/match.ts +92 -0
  28. package/src/lib/combinators/logic/not.spec.ts +62 -0
  29. package/src/lib/combinators/logic/not.ts +25 -0
  30. package/src/lib/combinators/logic/one-of.spec.ts +68 -0
  31. package/src/lib/combinators/logic/one-of.ts +41 -0
  32. package/src/lib/combinators/logic/unless.spec.ts +61 -0
  33. package/src/lib/combinators/logic/unless.ts +27 -0
  34. package/src/lib/combinators/logic/when.spec.ts +123 -0
  35. package/src/lib/combinators/logic/when.ts +29 -0
  36. package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
  37. package/src/lib/combinators/logic/with-fallback.ts +37 -0
  38. package/src/lib/combinators/utility/index.ts +8 -0
  39. package/src/lib/combinators/utility/inject.spec.ts +55 -0
  40. package/src/lib/combinators/utility/inject.ts +25 -0
  41. package/src/lib/combinators/utility/map-error.spec.ts +63 -0
  42. package/src/lib/combinators/utility/map-error.ts +35 -0
  43. package/src/lib/combinators/utility/tap.spec.ts +102 -0
  44. package/src/lib/combinators/utility/tap.ts +38 -0
  45. package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
  46. package/src/lib/combinators/utility/validate-field.ts +59 -0
  47. package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
  48. package/src/lib/combinators/utility/with-debug.ts +55 -0
  49. package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
  50. package/src/lib/combinators/utility/with-memoize.ts +81 -0
  51. package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
  52. package/src/lib/combinators/utility/with-retry.ts +68 -0
  53. package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
  54. package/src/lib/combinators/utility/with-timeout.ts +34 -0
  55. package/src/lib/composition/compose-rules.spec.ts +211 -0
  56. package/src/lib/composition/compose-rules.ts +47 -0
  57. package/src/lib/composition/index.ts +3 -0
  58. package/src/lib/composition/pipe-rules.spec.ts +220 -0
  59. package/src/lib/composition/pipe-rules.ts +44 -0
  60. package/src/lib/composition/pipe.spec.ts +47 -0
  61. package/src/lib/composition/pipe.ts +106 -0
  62. package/src/lib/helpers/context/has-context.ts +13 -0
  63. package/src/lib/helpers/context/index.ts +3 -0
  64. package/src/lib/helpers/context/require-context.spec.ts +55 -0
  65. package/src/lib/helpers/context/require-context.ts +61 -0
  66. package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
  67. package/src/lib/helpers/context/with-lazy-context.ts +35 -0
  68. package/src/lib/helpers/index.ts +6 -0
  69. package/src/lib/helpers/result/fail.ts +15 -0
  70. package/src/lib/helpers/result/index.ts +2 -0
  71. package/src/lib/helpers/result/pass.ts +14 -0
  72. package/src/lib/helpers/retry/calculate-delay.ts +31 -0
  73. package/src/lib/index.ts +4 -0
  74. package/src/lib/types/composition-options.ts +7 -0
  75. package/src/lib/types/debug-options.ts +36 -0
  76. package/src/lib/types/index.ts +4 -0
  77. package/src/lib/types/rule-result.ts +16 -0
  78. package/src/lib/types/rule.ts +21 -0
  79. package/src/test/helpers/get-rule-error.ts +23 -0
  80. package/src/test/integration.spec.ts +285 -0
  81. package/tsconfig.json +55 -0
  82. package/tsup.config.ts +36 -0
  83. package/vitest.config.ts +16 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/helpers/context/has-context.ts","../src/lib/helpers/result/fail.ts","../src/lib/helpers/result/pass.ts","../src/lib/helpers/context/require-context.ts","../src/lib/helpers/context/with-lazy-context.ts","../src/lib/helpers/retry/calculate-delay.ts","../src/lib/combinators/logic/every.ts","../src/lib/combinators/logic/if-else.ts","../src/lib/combinators/logic/match.ts","../src/lib/combinators/logic/not.ts","../src/lib/combinators/logic/one-of.ts","../src/lib/combinators/logic/unless.ts","../src/lib/combinators/logic/when.ts","../src/lib/combinators/logic/with-fallback.ts","../src/lib/combinators/utility/inject.ts","../src/lib/combinators/utility/map-error.ts","../src/lib/combinators/utility/with-memoize.ts","../src/lib/combinators/utility/validate-field.ts","../src/lib/combinators/utility/tap.ts","../src/lib/combinators/utility/with-debug.ts","../src/lib/combinators/utility/with-retry.ts","../src/lib/combinators/utility/with-timeout.ts","../src/lib/composition/compose-rules.ts","../src/lib/composition/pipe-rules.ts","../src/lib/composition/pipe.ts"],"names":["hasContext","ctx","fail","error","pass","requireContextRule","rule","contextCheck","check","input","context","withLazyContext","loader","errorMessage","calculateDelay","strategy","attempt","initialDelayMs","strategies","strategyFn","every","rules","options","currentContext","errors","r","ifElse","predicate","ifRule","elseRule","isRule","value","match","accessor","cases","defaultCase","key","matchedRule","not","oneOf","result","unless","when","withFallback","mainRule","fallbackRule","inject","dependency","configuredRule","mapError","transform","withMemoize","keyFn","cache","now","entry","oldestKey","validateField","getter","defaultValue","finalValue","tap","effect","withDebug","config","_a","_b","_c","startTime","ruleName","duration","withRetry","attempts","delayMs","shouldRetry","lastError","delay","resolve","withTimeout","timeoutMs","timeoutError","timeout","composeRules","i","pipeRules","pipe","fns","acc","fn"],"mappings":"AAUaA,IAAAA,CAAAA,CAAiBC,CACrBA,EAAAA,CAAAA,GAAQ,OCEV,IAAMC,CAAyBC,CAAAA,CAAAA,GACnC,CAAE,MAAA,CAAQ,QAAU,CAAA,KAAA,CAAAA,CAAM,CAAA,ECFhBC,IAAAA,CAAAA,CAAO,KACjB,CAAE,MAAQ,CAAA,QAAS,CCUf,EAAA,IAAMC,CAAqB,CAAA,CAMhCF,CACAG,CAAAA,CAAAA,CAIAC,CACmC,GAAA,CAKnC,IAAMC,CAAAA,CAAQD,IAJQN,CACbA,EAAAA,CAAAA,GAAQ,MAKjB,CAAA,CAAA,OAAcQ,MAAAA,CAAAA,CAAeC,CACpBF,GAAAA,CAAAA,CAAME,CAAO,CAAA,CAAIJ,CAAKG,CAAAA,CAAAA,CAAOC,CAAO,CAAA,CAAIR,CAAKC,CAAAA,CAAK,CAE7D,ECzBaQ,IAAAA,CAAAA,CAAkB,CAC7BC,CAAAA,CACAN,CAEO,GAAA,MAAOG,CAAkB,EAAA,CAC9B,GAAI,CACF,IAAMC,CAAAA,CAAU,MAAME,CAAOH,CAAAA,CAAK,CAClC,CAAA,OAAOH,CAAKG,CAAAA,CAAAA,CAAOC,CAAO,CAC5B,CAASP,MAAAA,CAAAA,CAAO,CACd,IAAMU,CACJV,CAAAA,CAAAA,YAAiB,KAAQA,CAAAA,CAAAA,CAAM,OAAU,CAAA,wBAAA,CAC3C,OAAOD,CAAAA,CAAKW,CAAsB,CACpC,CACF,EC/BWC,IAAAA,CAAAA,CAAiB,CAC5BC,CAAAA,CACAC,CACAC,CAAAA,CAAAA,GACW,CACX,IAAMC,CAA0D,CAAA,CAC9D,KAAO,CAAA,IAAMD,CACb,CAAA,MAAA,CAASD,CAAYC,EAAAA,CAAAA,CAAiBD,CACtC,CAAA,WAA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GAAuB,CAClD,IAAMa,CAAiBD,CAAAA,CAAAA,EAAA,IAAAA,EAAAA,CAAAA,CAAS,aAC5B,eAAgBZ,CAAAA,CAAO,CACvBA,CAAAA,CAAAA,CAEJ,IAASyE,IAAAA,CAAAA,CAAI9D,CAAM,CAAA,MAAA,CAAS,CAAG8D,CAAAA,CAAAA,EAAK,CAAGA,CAAAA,CAAAA,EAAAA,CAAK,CAC1C,IAAM3C,CAAS,CAAA,MAAMnB,CAAM8D,CAAAA,CAAC,CAAE1E,CAAAA,CAAAA,CAAOc,CAAc,CAAA,CACnD,GAAIiB,CAAAA,CAAO,MAAW,GAAA,QAAA,CACpB,OAAOA,CAEX,CACA,OAAOpC,GACT,ECnBWgF,IAAAA,EAAAA,CAAY,CACvB/D,CAAAA,CACAC,CAA8B,CAAA,EAEvB,GAAA,MAAOb,CAAeC,CAAAA,CAAAA,GAAuB,CAClD,IAAMa,CAAiBD,CAAAA,CAAAA,EAAA,IAAAA,EAAAA,CAAAA,CAAS,YAC5B,CAAA,eAAA,CAAgBZ,CAAO,CAAA,CACvBA,CAEJ,CAAA,IAAA,IAAWJ,CAAQe,IAAAA,CAAAA,CAAO,CACxB,IAAMmB,CAAS,CAAA,MAAMlC,CAAKG,CAAAA,CAAAA,CAAOc,CAAc,CAAA,CAC/C,GAAIiB,CAAAA,CAAO,MAAW,GAAA,QAAA,CACpB,OAAOA,CAEX,CACA,OAAOpC,CAAK,EACd,EC6DK,SAASiF,EAAKtD,CAAAA,CAAAA,CAAAA,GAAmBuD,CAA6B,CAAA,CACnE,OAAOA,CAAAA,CAAI,MAAO,CAAA,CAACC,CAAKC,CAAAA,CAAAA,GAAOA,CAAGD,CAAAA,CAAG,CAAGxD,CAAAA,CAAK,CAC/C","file":"index.js","sourcesContent":["/**\n * Type guard to check if context exists and is of type T.\n * @template T - The expected context type\n * @param ctx - The context to check\n * @returns Boolean indicating if context exists and matches type\n * @example\n * if (hasContext<AdminContext>(context)) {\n * // context is now typed as AdminContext\n * }\n */\nexport const hasContext = <T>(ctx: T | undefined): ctx is T => {\n return ctx !== undefined;\n};\n","import { RuleResult } from \"../../types\";\n\n/**\n * Creates a failed RuleResult with the provided error.\n * @template TError - The type of the error (defaults to string)\n * @param error - The error to include in the failed result\n * @returns A RuleResult with status \"failed\" and the provided error\n * @example\n * const result = fail(\"Invalid input\"); // { status: \"failed\", error: \"Invalid input\" }\n *\n * // Used in rule implementations:\n * const alwaysFails: Rule<string> = () => fail(\"Always fails\");\n */\nexport const fail = <TError = string>(error: TError): RuleResult<TError> =>\n ({ status: \"failed\", error }) as const;\n","import { RuleResult } from \"../../types\";\n\n/**\n * Creates a successful RuleResult with \"passed\" status.\n * @template TError - The type of the error (defaults to string)\n * @returns A RuleResult with status \"passed\"\n * @example\n * const result = pass(); // { status: \"passed\" }\n *\n * // Used in rule implementations:\n * const alwaysPasses: Rule<string> = () => pass();\n */\nexport const pass = <TError = string>(): RuleResult<TError> =>\n ({ status: \"passed\" }) as const;\n","import { Rule, RuleResult } from \"../../types\";\nimport { fail } from \"../result\";\n\n/**\n * Creates a rule that requires specific context to be present.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error\n * @template TContext - The base context type\n * @template TRequiredContext - The required context type\n * @param error - Error to return if context is invalid\n * @param rule - Rule that requires the specific context\n * @param contextCheck - Optional type guard for context validation\n * @returns A rule that validates context before execution\n * @example\n * const adminRule = requireContextRule(\n * \"Admin context required\",\n * (input, context: AdminContext) => { ... },\n * (ctx): ctx is AdminContext => ctx?.role === \"admin\"\n * );\n * @caveats\n * - Fails immediately if context check fails\n * - Provides type safety for context requirements\n */\nexport const requireContextRule = <\n TInput,\n TError,\n TContext,\n TRequiredContext extends TContext,\n>(\n error: TError,\n rule: (\n input: TInput,\n context: TRequiredContext,\n ) => Promise<RuleResult<TError>> | RuleResult<TError>,\n contextCheck?: (context: TContext | undefined) => context is TRequiredContext,\n): Rule<TInput, TError, TContext> => {\n const defaultCheck = (ctx: TContext | undefined): ctx is TRequiredContext => {\n return ctx !== undefined;\n };\n\n const check = contextCheck || defaultCheck;\n\n return async (input: TInput, context?: TContext) => {\n return check(context) ? rule(input, context) : fail(error);\n };\n};\n\n/**\n * const userRule = requireContextRule(\n \"User context required\",\n (input: string, ctx: { userId: string }) => {\n return ctx.userId === \"admin\" \n ? pass() \n : fail(\"Unauthorized\");\n }\n);\n\nawait userRule(\"action\"); // fails with \"User context required\"\nawait userRule(\"action\", { userId: \"user\" }); // fails with \"Unauthorized\"\nawait userRule(\"action\", { userId: \"admin\" }); // passes\n */\n","import { Rule } from \"../../types\";\nimport { fail } from \"../result\";\n\n/**\n * Creates a rule that loads context lazily before execution.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error\n * @template TContext - The type of the context object\n * @param loader - Function to load context from input\n * @param rule - Rule that requires the context\n * @returns A rule that loads context before execution\n * @example\n * const rule = withLazyContext(\n * async (userId) => await loadUserContext(userId),\n * validateUser\n * );\n * @caveats\n * - Context loading failures are converted to validation failures\n * - The loader is called for every rule execution\n */\nexport const withLazyContext = <TInput, TError, TContext>(\n loader: (input: TInput) => Promise<TContext> | TContext,\n rule: Rule<TInput, TError, TContext>,\n): Rule<TInput, TError> => {\n return async (input: TInput) => {\n try {\n const context = await loader(input);\n return rule(input, context);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Context loading failed\";\n return fail(errorMessage as TError);\n }\n };\n};\n","import { RetryStrategy } from \"../../combinators\";\n\nexport const calculateDelay = (\n strategy: RetryStrategy | undefined,\n attempt: number,\n initialDelayMs: number,\n): number => {\n const strategies: Record<string, (attempt: number) => number> = {\n fixed: () => initialDelayMs,\n linear: (attempt) => initialDelayMs * attempt,\n exponential: (attempt) => initialDelayMs * 2 ** (attempt - 1),\n };\n\n if (!strategy) {\n return strategies[\"fixed\"](attempt);\n }\n\n // If strategy is one of the predefined strings, use the corresponding function.\n if (typeof strategy === \"string\") {\n const strategyFn = strategies[strategy];\n return strategyFn ? strategyFn(attempt) : initialDelayMs;\n }\n\n // If the strategy is a custom function, call it.\n if (typeof strategy === \"function\") {\n return strategy(attempt);\n }\n\n // If it doesn't match any cases, uses fixed strategy by default\n return strategies[\"fixed\"](attempt);\n};\n","import { fail, pass } from \"../../helpers\";\nimport { CompositionOptions, Rule } from \"../../types\";\n\n/**\n * Composes multiple rules into a single rule that runs them all and collects all errors.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param rules - Array of rules to compose\n * @param options - Configuration options\n * @param options.cloneContext - Whether to clone the context for each rule (default: false)\n * @returns A new rule that returns all errors from all failing rules\n * @example\n * const rule = every([\n * validatePresence,\n * validateEmail,\n * validateUnique\n * ]);\n *\n * const result = await rule(\"invalid-email\");\n * if (result.status === \"failed\") {\n * console.log(result.error); // Array of all errors\n * }\n * @caveats\n * - Rules are executed in parallel (using Promise.all)\n * - All rules are executed even if some fail\n */\nexport const every = <TInput, TError = string, TContext = unknown>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions = {},\n): Rule<TInput, TError[], TContext> => {\n return async (input: TInput, context?: TContext) => {\n const currentContext = options?.cloneContext\n ? structuredClone(context)\n : context;\n\n const results = await Promise.all(\n rules.map((rule) => rule(input, currentContext)),\n );\n\n const errors = results.flatMap((r) =>\n r.status === \"failed\" ? [r.error] : [],\n );\n\n return errors.length > 0 ? fail(errors) : pass();\n };\n};\n","import { pass } from \"../../helpers\";\nimport { Rule } from \"../../types\";\n\n/**\n * Conditionally executes one of two rules based on a predicate\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param predicate - Function that determines which rule to execute\n * @param ifRule - Rule to execute when predicate returns true\n * @param elseRule - Rule to execute when predicate returns false (optional)\n * @returns A new rule that conditionally executes one of two rules\n * @example\n * const rule = branch(\n * (user) => user.age >= 18,\n * validateAdultAccount,\n * validateMinorAccount\n * );\n *\n * // Without elseRule (passes when predicate is false)\n * const adultOnlyRule = branch(\n * (user) => user.age >= 18,\n * validateAdultAccount\n * );\n */\nexport const ifElse = <TInput, TError = string, TContext = unknown>(\n predicate: (input: TInput, context?: TContext) => boolean | Promise<boolean>,\n ifRule: Rule<TInput, TError, TContext>,\n elseRule?: Rule<TInput, TError, TContext>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const shouldBranch = await predicate(input, context);\n return shouldBranch\n ? ifRule(input, context)\n : elseRule\n ? elseRule(input, context)\n : pass();\n };\n};\n","import { fail } from \"../../helpers\";\nimport { Rule, RuleResult } from \"../../types\";\n\nconst isRule = <TInput, TError, TContext>(\n value: unknown,\n): value is Rule<TInput, TError, TContext> => {\n return typeof value === \"function\";\n};\n\n/**\n * Pattern-matching combinator that selects a rule based on a key extracted from input.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @template TKey - The type of the branch key (must be string | number | symbol)\n * @param accessor - Function that extracts the match key from input\n * @param cases - Object mapping keys to their corresponding rules\n * @param defaultCase - Optional default rule or error when no match is found\n * @returns A new rule that executes the matching case's rule\n * @example\n * // Basic usage with string error type\n * const validatePayment = match(\n * (order) => order.paymentMethod,\n * {\n * credit: validateCreditCard,\n * paypal: validatePayPal,\n * crypto: validateCrypto\n * },\n * \"Unsupported payment method\"\n * );\n *\n * @example\n * // With custom error type\n * interface ValidationError { code: number; message: string }\n * const validateStatus = match<Order, ValidationError>(\n * (order) => order.status,\n * {\n * pending: validatePendingOrder,\n * completed: validateCompletedOrder\n * },\n * { code: 400, message: \"Invalid status\" }\n * );\n *\n * @example\n * // With default rule instead of error\n * const validateProduct = match(\n * (product) => product.type,\n * {\n * book: validateBook,\n * digital: validateDigitalProduct\n * },\n * validateGenericProduct\n * );\n *\n * @caveats\n * - The accessor function should return a primitive value (string/number/symbol)\n * - If no matching case is found and no default is provided, returns a failed result with:\n * - A string error when TError is string (default)\n * - A type-asserted error when TError is custom (may require type casting)\n * - All case rules must have compatible input/context types\n * - For conditional branching (true/false), consider using `branch` instead\n */\nexport const match = <\n TInput,\n TError = string,\n TContext = unknown,\n TKey extends string | number | symbol = string,\n>(\n accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>,\n cases: Record<TKey, Rule<TInput, TError, TContext>>,\n defaultCase?: Rule<TInput, TError, TContext> | TError,\n): Rule<TInput, TError, TContext> => {\n return async (\n input: TInput,\n context?: TContext,\n ): Promise<RuleResult<TError>> => {\n const key = await accessor(input, context);\n const matchedRule = cases[key];\n\n if (matchedRule) {\n return matchedRule(input, context);\n }\n\n if (defaultCase !== undefined) {\n return isRule<TInput, TError, TContext>(defaultCase)\n ? defaultCase(input, context)\n : fail(defaultCase);\n }\n\n return fail(`No matching rule for key: ${String(key)}` as TError);\n };\n};\n","import { pass, fail } from \"../../helpers\";\nimport { Rule } from \"../../types/rule\";\n\n/**\n * Inverts the logic of a rule - passes when original fails and vice versa.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @param rule - The rule to invert\n * @param error - The error to return when original rule passes\n * @returns A new rule with inverted logic\n * @example\n * const isNotAdmin = not(isAdmin, \"User must not be admin\");\n * @caveats\n * - The original rule's error is discarded when it fails\n * - Always uses the provided error when original passes\n */\nexport const not = <TInput, TError = string>(\n rule: Rule<TInput, TError>,\n error: TError,\n): Rule<TInput, TError> => {\n return async (input: TInput, context?: unknown) => {\n const result = await rule(input, context);\n return result.status === \"passed\" ? fail(error) : pass();\n };\n};\n","import { fail, pass } from \"../../helpers\";\nimport { Rule } from \"../../types\";\n\n/**\n * Creates a rule that passes if any of the provided rules pass (short-circuiting).\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param rules - Rules to try (in order)\n * @returns A rule that passes if any rule passes, or fails with all errors\n * @example\n * const rule = oneOf(\n * validateEmail,\n * validatePhone,\n * validateUsername\n * );\n * @caveats\n * - Rules are executed in sequence until one passes\n * - Returns all errors if all rules fail\n */\nexport const oneOf = <TInput, TError = string, TContext = unknown>(\n ...rules: Rule<TInput, TError, TContext>[]\n): Rule<TInput, TError[], TContext> => {\n return async (input: TInput, context?: TContext) => {\n const errors: TError[] = [];\n\n if (!rules || rules.length === 0) {\n return pass();\n }\n\n for (const rule of rules) {\n const result = await rule(input, context);\n if (result.status === \"passed\") {\n return pass();\n }\n errors.push(result.error);\n }\n\n return fail(errors);\n };\n};\n","import type { Rule } from \"../../types\";\nimport { pass } from \"../../helpers\";\n\n/**\n * Executes a rule only if the predicate returns false.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param predicate - Condition to check\n * @param rule - Rule to execute when predicate is false\n * @returns A rule that conditionally executes based on the predicate\n * @example\n * const rule = unless(\n * (user) => user.isVerified,\n * requireVerification\n * );\n * @caveats\n * - Opposite behavior of `when`\n * - Automatically passes when predicate is true\n */\nexport const unless = <TInput, TError = string, TContext = unknown>(\n predicate: (input: TInput) => Promise<boolean> | boolean,\n rule: Rule<TInput, TError, TContext>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) =>\n (await predicate(input)) ? pass() : rule(input, context);\n};\n","import { pass } from \"../../helpers/result/pass\";\nimport { Rule } from \"../../types/rule\";\n\n/**\n * Conditionally executes a rule based on a predicate.\n * Similar to branch but without an else case.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @param predicate - Function that determines whether to execute the rule\n * @param rule - Rule to execute when predicate returns true\n * @returns A new rule that conditionally executes the input rule\n * @example\n * const rule = when(\n * (user) => user.role === \"admin\",\n * validateAdminPrivileges\n * );\n * @caveats\n * - The predicate can be async\n * - If predicate returns false, the rule automatically passes\n */\nexport const when = <TInput, TError = string>(\n predicate: (input: TInput) => boolean | Promise<boolean>,\n rule: Rule<TInput, TError>,\n): Rule<TInput, TError> => {\n return async (input: TInput, context?: unknown) => {\n const shouldRun = await predicate(input);\n return shouldRun ? rule(input, context) : pass();\n };\n};\n","import { Rule } from \"../../types\";\n\n/**\n * Creates a rule that falls back to an alternative rule if the main rule fails.\n * @template TInput - Input type\n * @template TError - Error type\n * @template TContext - Context type\n * @param mainRule - Primary rule to execute first\n * @param fallbackRule - Rule to execute if main rule fails\n * @param options - Configuration options\n * @param options.onlyFallbackOn - Predicate to conditionally enable fallback\n * @returns A new composite rule\n * @example\n * const rule = withFallback(\n * premiumValidation,\n * basicValidation,\n * { onlyFallbackOn: err => err.code !== 'FATAL' }\n * );\n */\nexport const withFallback = <TInput, TError, TContext>(\n mainRule: Rule<TInput, TError, TContext>,\n fallbackRule: Rule<TInput, TError, TContext>,\n options: {\n onlyFallbackOn?: (error: TError) => boolean;\n } = {},\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const result = await mainRule(input, context);\n if (\n result.status === \"failed\" &&\n (!options.onlyFallbackOn || options.onlyFallbackOn(result.error))\n ) {\n return fallbackRule(input, context);\n }\n return result;\n };\n};\n","import { Rule } from \"../../types\";\n\n/**\n * Injects a dependency into a rule creation function, returning a configured rule.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error\n * @template TDep - The type of the dependency to inject\n * @param dependency - The dependency to inject\n * @param rule - A function that creates a rule when given the dependency\n * @returns A configured rule that uses the injected dependency\n * @example\n * const createDbRule = (db: Database) => (input: string) =>\n * db.exists(input) ? pass() : fail(\"Not found\");\n *\n * const dbRule = inject(database, createDbRule);\n * @caveats\n * - The dependency is injected at rule creation time, not execution time\n */\nexport const inject = <TInput, TError, TDep>(\n dependency: TDep,\n rule: (dep: TDep) => Rule<TInput, TError>,\n): Rule<TInput, TError> => {\n const configuredRule = rule(dependency);\n return (input) => configuredRule(input);\n};\n","import { fail, pass } from \"../../helpers\";\nimport { Rule } from \"../../types\";\n\n/**\n * Transforms the error of a rule using a mapping function.\n * @template TInput - The type of the input to validate\n * @template TError - The original error type\n * @template TNewError - The new error type\n * @param rule - The rule whose errors should be transformed\n * @param transform - Function to transform the error\n * @returns A new rule that produces transformed errors\n * @example\n * const rule = mapError(\n * validateEmail,\n * (error) => `Validation failed: ${error}`\n * );\n *\n * // Can also change error types:\n * const numericErrorRule = mapError(\n * stringErrorRule,\n * (error) => error.length // Convert string error to number\n * );\n * @caveats\n * - Only transforms failed results, passes successful results through unchanged\n * - The transform function is not called for successful results\n */\nexport const mapError = <TInput, TError, TNewError>(\n rule: Rule<TInput, TError>,\n transform: (error: TError) => TNewError,\n): Rule<TInput, TNewError> => {\n return async (input: TInput, context?: unknown) => {\n const result = await rule(input, context);\n return result.status === \"failed\" ? fail(transform(result.error)) : pass();\n };\n};\n","import { Rule, RuleResult } from \"../../types\";\n\n/**\n * Creates a memoized version of a rule that caches results based on input keys.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param rule - The rule to memoize\n * @param keyFn - Function that generates a cache key from the input\n * @param options - Memoization options\n * @param options.ttl - Time-to-live for cache entries in milliseconds\n * @param options.maxSize - Maximum number of entries to keep in cache\n * @returns A memoized version of the rule\n * @example\n * const memoizedRule = withMemoize(\n * expensiveValidationRule,\n * (input) => input.id,\n * { ttl: 60000, maxSize: 100 }\n * );\n * @caveats\n * - Context changes don't invalidate cache by default\n * - Cache cleanup happens during rule execution\n * - Rejected promises are automatically evicted from cache\n */\nexport const withMemoize = <TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n keyFn: (input: TInput) => string,\n options: {\n ttl?: number; // Milliseconds\n maxSize?: number;\n } = {},\n): Rule<TInput, TError, TContext> => {\n const cache = new Map<\n string,\n {\n result: Promise<RuleResult<TError>> | RuleResult<TError>;\n timestamp: number;\n }\n >();\n\n return async (input: TInput, context?: TContext) => {\n const key = keyFn(input);\n const now = Date.now();\n\n // Cache cleanup\n if (options.ttl) {\n for (const [key, entry] of cache) {\n if (now - entry.timestamp > options.ttl) {\n cache.delete(key);\n }\n }\n }\n\n // Size management\n if (options.maxSize && cache.size >= options.maxSize) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey) {\n cache.delete(oldestKey);\n }\n }\n\n // Cache hit\n if (cache.has(key)) {\n return cache.get(key)!.result;\n }\n\n // Cache miss\n const result = rule(input, context);\n cache.set(key, {\n result,\n timestamp: now,\n });\n\n // Handle Promise cleanup if rejected\n if (result instanceof Promise) {\n result.catch(() => cache.delete(key));\n }\n\n return result;\n };\n};\n","import { fail } from \"../../helpers\";\nimport { Rule } from \"../../types\";\n\n/**\n * Creates a rule that extracts a value using a getter function and validates it.\n * @template TInput - The type of the input object\n * @template TValue - The type of the extracted value\n * @template TError - The type of the error\n * @template TContext - The type of the context object\n * @param getter - Function that extracts the value from input\n * @param rule - Rule to apply to the extracted value\n * @param defaultValue - Optional default value if getter returns undefined\n * @returns A new rule that validates the extracted value\n * @example\n * const validateName = validateField(\n * (user: User) => user.profile.name,\n * (name) => name.length > 3 ? pass() : fail('Name too short')\n * );\n *\n * const validateAge = validateField(\n * (user: User) => user.age,\n * (age) => age >= 18 ? pass() : fail('Must be adult'),\n * 18 // default value\n * );\n *\n * @caveats\n * **Null/Undefined Handling**:\n * - The getter function should handle optional properties (use optional chaining)\n * - If getter returns undefined and no default is provided, the rule will fail\n *\n * **Type Safety**:\n * - The rule's input type must match the getter's return type exactly\n * - No automatic type narrowing (e.g., string | undefined won't become string even with default)\n *\n * **Default Values**:\n * - Defaults are applied before rule execution (the rule sees the default value)\n * - Default values aren't type-checked against potentially undefined returns\n */\nexport function validateField<\n TInput,\n TValue,\n TError = string,\n TContext = unknown,\n>(\n getter: (input: TInput) => TValue | undefined,\n rule: Rule<TValue, TError, TContext>,\n defaultValue?: TValue,\n): Rule<TInput, TError, TContext> {\n return async (input: TInput, context?: TContext) => {\n const value = getter(input);\n const finalValue = value !== undefined ? value : defaultValue;\n\n if (finalValue === undefined) {\n return fail(\"Missing required value\" as unknown as TError);\n }\n\n return rule(finalValue, context);\n };\n}\n","import { Rule, RuleResult } from \"../../types\";\n\n/**\n * Creates a rule wrapper that performs side effects without modifying the result.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param effect - Side effect function receiving input, result and context\n * @returns A function that wraps a rule with the tap effect\n * @example\n * const withLogging = tap((input, result) => {\n * console.log(`Validation result for ${input}:`, result);\n * });\n *\n * const rule = withLogging(validateInput);\n * @caveats\n * - Errors in the effect are caught and logged but don't affect rule execution\n * - Doesn't modify the rule's result\n */\nexport const tap = <TInput, TError = string, TContext = unknown>(\n effect: (\n input: TInput,\n result: RuleResult<TError>,\n context?: TContext,\n ) => Promise<void> | void,\n): ((\n rule: Rule<TInput, TError, TContext>,\n) => Rule<TInput, TError, TContext>) => {\n return (rule) => async (input, context) => {\n const result = await rule(input, context);\n try {\n await effect(input, result, context);\n } catch (error) {\n console.error(\"Tap effect failed:\", error);\n }\n return result;\n };\n};\n","import { DebugOptions, Rule } from \"../../types\";\n\n/**\n * Wraps a rule with debugging capabilities.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error\n * @template TContext - The type of the context object\n * @param rule - The rule to wrap with debug capabilities\n * @param options - Debug configuration or simple name string\n * @param options.name - Name for the debug output\n * @param options.onStart - Callback when rule starts executing\n * @param options.onEnd - Callback when rule completes successfully\n * @param options.onError - Callback when rule throws an error\n * @returns A new rule with debug capabilities\n * @example\n * const rule = withDebug(expensiveValidation, {\n * name: \"Expensive Validation\",\n * onStart: (input) => console.log(`Starting with input: ${input}`),\n * onEnd: (input, result, ctx, { duration }) => {\n * console.log(`Completed in ${duration}ms`);\n * }\n * });\n * @caveats\n * - Debug callbacks are executed synchronously and may impact performance\n * - Errors in callbacks will propagate and potentially mask rule errors\n */\nexport const withDebug = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n options: DebugOptions<TInput, TError, TContext> | string,\n): Rule<TInput, TError, TContext> => {\n const config = typeof options === \"string\" ? { name: options } : options;\n\n return async (input, context) => {\n const startTime = performance.now();\n const ruleName = config.name || rule.name || \"anonymous_rule\";\n\n try {\n config.onStart?.(input, context);\n const result = await rule(input, context);\n const duration = performance.now() - startTime;\n\n config.onEnd?.(input, result, context, {\n ruleName,\n duration,\n startTime,\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n config.onError?.(error, input, context, duration);\n throw error; // Preserve original error throwing behavior\n }\n };\n};\n","import type { Rule } from \"../../types\";\nimport { calculateDelay, fail } from \"../../helpers\";\n\nexport type RetryStrategy =\n | \"fixed\"\n | \"linear\"\n | \"exponential\"\n | ((attempt: number) => number);\n\n/**\n * Wraps a rule with retry logic for handling transient failures.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param rule - The rule to wrap with retry logic\n * @param options - Retry configuration\n * @param options.attempts - Maximum number of attempts (default: 3)\n * @param options.delayMs - Delay between attempts in milliseconds (default: 100)\n * @param options.shouldRetry - Function to determine if a failure should be retried\n * @returns A new rule with retry capability\n * @example\n * const rule = withRetry(apiCheckRule, {\n * attempts: 5,\n * delayMs: 500,\n * shouldRetry: (error) => error.statusCode === 503\n * });\n * @caveats\n * - Only retries on failed RuleResults, not on thrown exceptions\n * - The final error will be \"MAX_RETRIES_EXCEEDED\" if all attempts fail\n */\nexport const withRetry = <TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options: {\n attempts?: number;\n delayMs?: number;\n retryStrategy?: RetryStrategy;\n shouldRetry?: (error: TError | unknown, attempt: number) => boolean;\n } = {},\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext> => {\n const { attempts = 3, delayMs = 100, shouldRetry = () => true } = options;\n\n return async (input, context) => {\n let lastError: TError | unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const result = await rule(input, context);\n if (result.status === \"passed\") return result;\n lastError = result.error;\n } catch (error) {\n lastError = error;\n }\n\n // Check if we should retry the last error\n if (!shouldRetry(lastError as TError, attempt)) {\n return fail(lastError as TError);\n }\n\n // Delay if not the last attempt\n if (attempt < attempts && delayMs > 0) {\n const delay = calculateDelay(options?.retryStrategy, attempt, delayMs);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n return fail(\"MAX_RETRIES_EXCEEDED\" as const);\n };\n};\n","import { fail } from \"../../helpers\";\nimport { Rule, RuleResult } from \"../../types\";\n\n/**\n * Wraps a rule with timeout functionality.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error\n * @template TContext - The type of the context object\n * @param rule - The rule to wrap with timeout\n * @param timeoutMs - Timeout duration in milliseconds\n * @param timeoutError - Error to return if timeout occurs\n * @returns A new rule that fails with timeoutError if execution takes longer than timeoutMs\n * @example\n * const rule = withTimeout(\n * slowNetworkRequestRule,\n * 5000, // 5 seconds\n * \"Request timed out\"\n * );\n * @caveats\n * - The original rule's execution isn't aborted when timeout occurs\n * - Only fails if the rule doesn't complete before timeout, not if it fails before timeout\n */\nexport const withTimeout = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n timeoutMs: number,\n timeoutError: TError,\n): Rule<TInput, TError, TContext> => {\n return async (input, context) => {\n const timeout = new Promise<RuleResult<TError>>((resolve) =>\n setTimeout(() => resolve(fail(timeoutError)), timeoutMs),\n );\n return Promise.race([rule(input, context), timeout]);\n };\n};\n","import { pass } from \"../helpers\";\nimport { CompositionOptions, Rule } from \"../types\";\n\n/**\n * Composes multiple rules into a single rule that runs them in right-to-left order (fail-fast).\n * Stops at the first failure and returns the error.\n *\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param rules - Array of rules to compose\n * @param options - Configuration options\n * @param options.cloneContext - Whether to clone the context for each rule (default: false)\n * @returns A new rule that composes all input rules\n *\n * @example\n * const rule = composeRules([\n * finalCheck,\n * normalizeInput,\n * validateBase\n * ]);\n *\n * const result = await rule(input);\n *\n * @caveats\n * - Rules are executed from **right to left**\n * - Rules are executed sequentially (not in parallel)\n * - Context clone uses structuredClone from Node.js\n */\nexport const composeRules = <TInput, TError = string, TContext = unknown>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions = {},\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const currentContext = options?.cloneContext\n ? structuredClone(context)\n : context;\n\n for (let i = rules.length - 1; i >= 0; i--) {\n const result = await rules[i](input, currentContext);\n if (result.status === \"failed\") {\n return result;\n }\n }\n return pass();\n };\n};\n","import { pass } from \"../helpers\";\nimport { CompositionOptions, Rule } from \"../types\";\n\n/**\n * Pipes multiple rules into a single rule that runs them sequentially (fail-fast).\n * Stops at the first failure and returns the error.\n * @template TInput - The type of the input to validate\n * @template TError - The type of the error (defaults to string)\n * @template TContext - The type of the context object (optional)\n * @param rules - Array of rules to compose\n * @param options - Configuration options\n * @param options.cloneContext - Whether to clone the context for each rule (default: false)\n * @returns A new rule that pipes all input rules\n * @example\n * const rule = pipeRules([\n * validateString,\n * validateLength,\n * validateFormat\n * ]);\n *\n * const result = await rule(\"test@example.com\");\n * @caveats\n * - Rules are execute from left to right\n * - Rules are executed in sequence, not in parallel\n * - Context clone uses structuredClone Nodejs implementation\n */\nexport const pipeRules = <TInput, TError = string, TContext = unknown>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions = {},\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const currentContext = options?.cloneContext\n ? structuredClone(context)\n : context;\n\n for (const rule of rules) {\n const result = await rule(input, currentContext);\n if (result.status === \"failed\") {\n return result;\n }\n }\n return pass();\n };\n};\n","type AnyFunction = (...args: any[]) => any;\n\n/**\n * Pipes a value through a series of functions (left-to-right composition).\n * @template A - The input type\n * @template B - The output type after first function\n * @param value - The initial value\n * @param fns - Functions to apply sequentially\n * @returns The result of applying all functions to the initial value\n * @example\n * const result = pipe(\n * 5,\n * (x) => x * 2,\n * (x) => x + 3,\n * (x) => `Result: ${x}`\n * ); // \"Result: 13\"\n * @caveats\n * - Currently supports up to 10 functions with proper type inference\n * - For more functions, type information will be lost\n */\nexport function pipe<A>(value: A): A;\nexport function pipe<A, B>(value: A, fn1: (arg: A) => B): B;\nexport function pipe<A, B, C>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n): C;\nexport function pipe<A, B, C, D>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n): D;\nexport function pipe<A, B, C, D, E>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n): E;\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n fn5: (arg: E) => F,\n): F;\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n fn5: (arg: E) => F,\n fn6: (arg: F) => G,\n): G;\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n fn5: (arg: E) => F,\n fn6: (arg: F) => G,\n fn7: (arg: G) => H,\n): H;\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n fn5: (arg: E) => F,\n fn6: (arg: F) => G,\n fn7: (arg: G) => H,\n fn8: (arg: H) => I,\n): I;\nexport function pipe<A, B, C, D, E, F, G, H, I, J>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n fn5: (arg: E) => F,\n fn6: (arg: F) => G,\n fn7: (arg: G) => H,\n fn8: (arg: H) => I,\n fn9: (arg: I) => J,\n): J;\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K>(\n value: A,\n fn1: (arg: A) => B,\n fn2: (arg: B) => C,\n fn3: (arg: C) => D,\n fn4: (arg: D) => E,\n fn5: (arg: E) => F,\n fn6: (arg: F) => G,\n fn7: (arg: G) => H,\n fn8: (arg: H) => I,\n fn9: (arg: I) => J,\n fn10: (arg: J) => K,\n): K;\nexport function pipe(value: unknown, ...fns: AnyFunction[]): unknown {\n return fns.reduce((acc, fn) => fn(acc), value);\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "ts-rules-composer",
3
+ "version": "0.0.1",
4
+ "description": "Typescript rules engine by composition",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "author": "Breno Magalhaes",
9
+ "license": "MIT",
10
+ "sideEffects": false,
11
+ "type": "module",
12
+ "exports": {
13
+ "import": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.cts",
19
+ "require": "./dist/index.cjs"
20
+ }
21
+ },
22
+ "scripts": {
23
+ "prepublish": "npm run build",
24
+ "build": "tsup",
25
+ "format": "prettier \"src/**/*.ts\" --check",
26
+ "format:fix": "prettier \"src/**/*.ts\" --write",
27
+ "lint": "eslint ./src/",
28
+ "lint:fix": "eslint --fix ./src",
29
+ "test": "run-s build test:*",
30
+ "test:prettier": "prettier \"src/**/*.ts\" --list-different",
31
+ "test:unit": "vitest run",
32
+ "test:coverage": "vitest run --coverage",
33
+ "watch:build": "tsc -p tsconfig.json -w",
34
+ "watch:test": "vitest",
35
+ "generate-docs": "typedoc ./src --githubPages --includeVersion --out ./genDocs",
36
+ "release": "semantic-release"
37
+ },
38
+ "engines": {
39
+ "node": ">=18"
40
+ },
41
+ "devDependencies": {
42
+ "@typescript-eslint/eslint-plugin": "^8.31.0",
43
+ "@typescript-eslint/parser": "^8.31.0",
44
+ "@vitest/coverage-v8": "^3.1.2",
45
+ "conventional-changelog-conventionalcommits": "^8.0.0",
46
+ "cspell": "^8.19.2",
47
+ "cz-conventional-changelog": "^3.3.0",
48
+ "eslint": "^9.25.1",
49
+ "eslint-config-prettier": "^10.1.2",
50
+ "eslint-plugin-eslint-comments": "^3.2.0",
51
+ "eslint-plugin-import": "^2.31.0",
52
+ "gh-pages": "^6.3.0",
53
+ "npm-run-all": "^4.1.5",
54
+ "open-cli": "^8.0.0",
55
+ "prettier": "^3.5.3",
56
+ "semantic-release": "^24.2.3",
57
+ "standard-version": "^9.5.0",
58
+ "ts-node": "^10.9.2",
59
+ "tsup": "^8.4.0",
60
+ "typedoc": "^0.28.3",
61
+ "typescript": "^5.8.3",
62
+ "vitest": "^3.1.2"
63
+ }
64
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./logic";
2
+ export * from "./utility";
@@ -0,0 +1,264 @@
1
+ import { pass, fail } from "../../helpers";
2
+
3
+ import { beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { Rule } from "../../types";
5
+ import { every } from "./every";
6
+
7
+ describe("every", () => {
8
+ const delay = (ms: number) =>
9
+ new Promise((resolve) => setTimeout(resolve, ms));
10
+
11
+ it("should return pass if no rules are provided", async () => {
12
+ const result = await every([])({});
13
+ expect(result).toEqual(pass());
14
+ });
15
+
16
+ it("should return pass if all rules pass", async () => {
17
+ const rule1 = vi.fn(() => pass());
18
+ const rule2 = vi.fn(() => pass());
19
+ const validator = every([rule1, rule2]);
20
+ const input = { foo: "bar" };
21
+
22
+ const result = await validator(input);
23
+
24
+ expect(result).toEqual(pass());
25
+ expect(rule1).toHaveBeenCalledWith(input, undefined);
26
+ expect(rule2).toHaveBeenCalledWith(input, undefined);
27
+ });
28
+
29
+ it("should collect all errors in parallel", async () => {
30
+ const error1 = "Error 1";
31
+ const error2 = "Error 2";
32
+ const rule1 = vi.fn(() => fail(error1));
33
+ const rule2 = vi.fn(async () => {
34
+ await delay(10); // Ensure parallel execution
35
+ return fail(error2);
36
+ });
37
+ const validator = every([rule1, rule2]);
38
+ const input = { foo: "bar" };
39
+
40
+ const result = await validator(input);
41
+
42
+ expect(result).toEqual(fail([error1, error2]));
43
+ expect(rule1).toHaveBeenCalledWith(input, undefined);
44
+ expect(rule2).toHaveBeenCalledWith(input, undefined);
45
+ });
46
+
47
+ it("should maintain error order when rules fail", async () => {
48
+ const error1 = "Error 1";
49
+ const error2 = "Error 2";
50
+ const rule1 = vi.fn(async () => {
51
+ await delay(20);
52
+ return fail(error1);
53
+ });
54
+ const rule2 = vi.fn(async () => {
55
+ await delay(10);
56
+ return fail(error2);
57
+ });
58
+ const validator = every([rule1, rule2]);
59
+
60
+ const result = await validator({});
61
+
62
+ // Order should match input rule order, not completion order
63
+ expect(result).toEqual(fail([error1, error2]));
64
+ });
65
+
66
+ it("should pass context to all rules", async () => {
67
+ const rule1 = vi.fn(() => pass());
68
+ const rule2 = vi.fn(() => pass());
69
+ const validator = every([rule1, rule2]);
70
+ const input = { foo: "bar" };
71
+ const context = { userId: 123 };
72
+
73
+ await validator(input, context);
74
+
75
+ expect(rule1).toHaveBeenCalledWith(input, context);
76
+ expect(rule2).toHaveBeenCalledWith(input, context);
77
+ });
78
+ });
79
+
80
+ describe("Niche errors", () => {
81
+ it("should preserve custom error types", async () => {
82
+ type CustomError = { code: number; message: string };
83
+ const rule: Rule<unknown, CustomError> = () =>
84
+ fail({ code: 400, message: "Bad" });
85
+
86
+ const validator = every([rule]);
87
+ const result = await validator({});
88
+
89
+ expect(result).toEqual(fail([{ code: 400, message: "Bad" }]));
90
+ });
91
+
92
+ // Mixed sync/async rules
93
+ it("should handle mixed sync/async rules", async () => {
94
+ const syncRule = () => fail("Sync error");
95
+ const asyncRule = async () => fail("Async error");
96
+
97
+ const validator = every([syncRule, asyncRule]);
98
+ const result = await validator({});
99
+
100
+ expect(result).toEqual(fail(["Sync error", "Async error"]));
101
+ });
102
+
103
+ it("should handle 1000+ parallel rules", async () => {
104
+ const manyRules = Array(1000).fill(() => pass());
105
+ const validator = every(manyRules);
106
+ await expect(validator({})).resolves.toEqual(pass());
107
+ });
108
+
109
+ it('should handle falsy error values (false, 0, "")', async () => {
110
+ const rules = [() => fail(false), () => fail(0), () => fail("")];
111
+ const validator = every(rules as any);
112
+ const result = await validator({});
113
+ expect(result).toEqual(fail([false, 0, ""]));
114
+ });
115
+ });
116
+ // Error type propagation
117
+
118
+ describe("Context behavior tests", () => {
119
+ const countingRule = vi.fn((_: unknown, ctx: any) => {
120
+ ctx.count = (ctx.count || 0) + 1;
121
+ return pass();
122
+ });
123
+
124
+ // Context checker rule
125
+ const expectCountRule = (expected: number) =>
126
+ vi.fn((_: unknown, ctx: any) =>
127
+ ctx.count === expected
128
+ ? pass()
129
+ : fail(`Expected count ${expected}, got ${ctx.count}`),
130
+ );
131
+
132
+ beforeEach(() => {
133
+ vi.clearAllMocks();
134
+ });
135
+
136
+ it("should allow context mutation by default (shared reference)", async () => {
137
+ const context = { count: 0 };
138
+ const validator = every(
139
+ [countingRule, countingRule, expectCountRule(2)], // Expect both mutations to apply
140
+ );
141
+
142
+ const result = await validator({}, context);
143
+
144
+ expect(result).toEqual(pass());
145
+ expect(context.count).toBe(2); // Original context modified
146
+ });
147
+
148
+ it("should prevent context mutations when cloneContext=true", async () => {
149
+ const context = { count: 0 };
150
+ const validator = every([countingRule, expectCountRule(1)], {
151
+ cloneContext: true,
152
+ });
153
+
154
+ const result = await validator({}, context);
155
+
156
+ expect(result).toEqual(pass());
157
+ expect(context.count).toBe(0); // Original context untouched
158
+ expect(countingRule.mock.calls[0][1].count).toBe(1); // First clone
159
+ });
160
+
161
+ it("should deep clone complex context objects", async () => {
162
+ const context = { nested: { value: 0 } };
163
+ const mutateNested = vi.fn((_, ctx) => {
164
+ ctx.nested.value++;
165
+ return pass();
166
+ });
167
+
168
+ const validator = every([mutateNested, mutateNested], {
169
+ cloneContext: true,
170
+ });
171
+
172
+ await validator({}, context);
173
+
174
+ expect(context.nested.value).toBe(0); // Original unchanged
175
+ expect(mutateNested.mock.calls[0][1].nested.value).toBe(2); // First clone
176
+ expect(mutateNested.mock.calls[1][1].nested.value).toBe(2); // Fresh clone
177
+ });
178
+
179
+ it("should handle null/undefined context", async () => {
180
+ const nullValidator = every([], { cloneContext: true });
181
+ await expect(nullValidator({}, null)).resolves.not.toThrow();
182
+ await expect(nullValidator({}, undefined)).resolves.not.toThrow();
183
+ });
184
+
185
+ it("should shallow clone when possible for performance", async () => {
186
+ const context = { simple: "value" };
187
+ const validator = every(
188
+ [
189
+ (_, ctx) => {
190
+ (ctx as any).simple = "changed";
191
+ return pass();
192
+ },
193
+ ],
194
+ { cloneContext: true },
195
+ );
196
+
197
+ await validator({}, context);
198
+ expect(context.simple).toBe("value"); // Original unchanged
199
+ });
200
+ });
201
+
202
+ it("should prevent accidental context mutation", async () => {
203
+ const context = { count: 0 };
204
+
205
+ const rule1 = (_: any, ctx: any) => {
206
+ (ctx as any).count++; // Bad practice but test should handle
207
+ return pass();
208
+ };
209
+
210
+ const rule2 = (_: any, ctx: any) => {
211
+ if ((ctx as any).count !== 0) {
212
+ return fail("Context mutated");
213
+ }
214
+ return pass();
215
+ };
216
+
217
+ const validator = every([rule1, rule2]);
218
+ await expect(validator({}, context)).resolves.toEqual(
219
+ fail(["Context mutated"]),
220
+ );
221
+ });
222
+
223
+ it("should preserve custom generic types through composition", async () => {
224
+ type CustomInput = { id: string };
225
+ type CustomError = { severity: number };
226
+
227
+ const rule: Rule<CustomInput, CustomError> = (input) =>
228
+ input.id ? pass() : fail({ severity: 5 });
229
+
230
+ const validator = every([rule]);
231
+ const result1 = await validator({ id: "test" });
232
+ const result2 = await validator({} as CustomInput);
233
+
234
+ expect(result1).toEqual(pass());
235
+ expect(result2).toEqual(fail([{ severity: 5 }]));
236
+ });
237
+
238
+ it("should not retain rule references after execution", async () => {
239
+ let heavyObject = new Array(1e6).fill(0); // 1MB object
240
+ const rule = () => {
241
+ heavyObject = null!; // Simulate cleanup
242
+ return pass();
243
+ };
244
+
245
+ const validator = every([rule]);
246
+ await validator({});
247
+
248
+ // This would fail if composition held references
249
+ expect(() => heavyObject.length).toThrow();
250
+ });
251
+
252
+ it("should handle circular reference errors", async () => {
253
+ const obj: any = { self: null };
254
+ obj.self = obj;
255
+
256
+ const validator = every([() => fail(obj), () => pass()]);
257
+ const result = await validator({});
258
+
259
+ expect(result.status).toBe("failed");
260
+ // Check circular reference is preserved
261
+ const errors = (result as any).error;
262
+ expect(errors[0].self).toBe(errors[0]); // Verify circularity
263
+ expect(errors).toEqual([obj]); // Verify error content
264
+ });
@@ -0,0 +1,47 @@
1
+ import { fail, pass } from "../../helpers";
2
+ import { CompositionOptions, Rule } from "../../types";
3
+
4
+ /**
5
+ * Composes multiple rules into a single rule that runs them all and collects all errors.
6
+ * @template TInput - The type of the input to validate
7
+ * @template TError - The type of the error (defaults to string)
8
+ * @template TContext - The type of the context object (optional)
9
+ * @param rules - Array of rules to compose
10
+ * @param options - Configuration options
11
+ * @param options.cloneContext - Whether to clone the context for each rule (default: false)
12
+ * @returns A new rule that returns all errors from all failing rules
13
+ * @example
14
+ * const rule = every([
15
+ * validatePresence,
16
+ * validateEmail,
17
+ * validateUnique
18
+ * ]);
19
+ *
20
+ * const result = await rule("invalid-email");
21
+ * if (result.status === "failed") {
22
+ * console.log(result.error); // Array of all errors
23
+ * }
24
+ * @caveats
25
+ * - Rules are executed in parallel (using Promise.all)
26
+ * - All rules are executed even if some fail
27
+ */
28
+ export const every = <TInput, TError = string, TContext = unknown>(
29
+ rules: Rule<TInput, TError, TContext>[],
30
+ options: CompositionOptions = {},
31
+ ): Rule<TInput, TError[], TContext> => {
32
+ return async (input: TInput, context?: TContext) => {
33
+ const currentContext = options?.cloneContext
34
+ ? structuredClone(context)
35
+ : context;
36
+
37
+ const results = await Promise.all(
38
+ rules.map((rule) => rule(input, currentContext)),
39
+ );
40
+
41
+ const errors = results.flatMap((r) =>
42
+ r.status === "failed" ? [r.error] : [],
43
+ );
44
+
45
+ return errors.length > 0 ? fail(errors) : pass();
46
+ };
47
+ };
@@ -0,0 +1,72 @@
1
+ import { describe, vi, beforeEach, it, expect } from "vitest";
2
+ import { pass, fail } from "../../helpers";
3
+ import { Rule } from "../../types";
4
+ import { ifElse } from "./if-else";
5
+
6
+ describe("branch", () => {
7
+ const mockTruePredicate = vi.fn(() => true);
8
+ const mockFalsePredicate = vi.fn(() => false);
9
+ const asyncTruePredicate = vi.fn(async () => true);
10
+
11
+ const passingRule: Rule<string> = vi.fn(() => pass());
12
+ const failingRule: Rule<string> = vi.fn(() => fail("Failed rule"));
13
+ const contextAwareRule: Rule<string, string, { mode: string }> = vi.fn(
14
+ (_, ctx) => (ctx?.mode === "test" ? pass() : fail("Invalid context")),
15
+ );
16
+
17
+ beforeEach(() => {
18
+ vi.clearAllMocks();
19
+ });
20
+
21
+ it("should execute ifRule when predicate returns true", async () => {
22
+ const rule = ifElse(mockTruePredicate, passingRule);
23
+ const result = await rule("input");
24
+ expect(result.status).toBe("passed");
25
+ expect(mockTruePredicate).toHaveBeenCalledWith("input", undefined);
26
+ expect(passingRule).toHaveBeenCalled();
27
+ });
28
+
29
+ it("should execute elseRule when provided and predicate returns false", async () => {
30
+ const rule = ifElse(mockFalsePredicate, failingRule, passingRule);
31
+ const result = await rule("input");
32
+ expect(result.status).toBe("passed");
33
+ expect(passingRule).toHaveBeenCalled();
34
+ });
35
+
36
+ it("should return pass() when no elseRule provided and predicate returns false", async () => {
37
+ const rule = ifElse(mockFalsePredicate, failingRule);
38
+ const result = await rule("input");
39
+ expect(result.status).toBe("passed");
40
+ expect(failingRule).not.toHaveBeenCalled();
41
+ });
42
+
43
+ it("should work with async predicates", async () => {
44
+ const rule = ifElse(asyncTruePredicate, passingRule);
45
+ const result = await rule("input");
46
+ expect(result.status).toBe("passed");
47
+ expect(asyncTruePredicate).toHaveBeenCalled();
48
+ expect(passingRule).toHaveBeenCalled();
49
+ });
50
+
51
+ it("should pass context to both predicate and rules", async () => {
52
+ const context = { mode: "test" };
53
+ const rule = ifElse((_, ctx) => ctx?.mode === "test", contextAwareRule);
54
+ const result = await rule("input", context);
55
+ expect(result.status).toBe("passed");
56
+ expect(contextAwareRule).toHaveBeenCalledWith("input", context);
57
+ });
58
+
59
+ it("should handle failing ifRule", async () => {
60
+ const rule = ifElse(mockTruePredicate, failingRule);
61
+ const result = await rule("input");
62
+ expect(result.status).toBe("failed");
63
+ expect(result).toEqual(fail("Failed rule"));
64
+ });
65
+
66
+ it("should handle failing elseRule", async () => {
67
+ const rule = ifElse(mockFalsePredicate, passingRule, failingRule);
68
+ const result = await rule("input");
69
+ expect(result.status).toBe("failed");
70
+ expect(result).toEqual(fail("Failed rule"));
71
+ });
72
+ });
@@ -0,0 +1,39 @@
1
+ import { pass } from "../../helpers";
2
+ import { Rule } from "../../types";
3
+
4
+ /**
5
+ * Conditionally executes one of two rules based on a predicate
6
+ * @template TInput - The type of the input to validate
7
+ * @template TError - The type of the error (defaults to string)
8
+ * @template TContext - The type of the context object (optional)
9
+ * @param predicate - Function that determines which rule to execute
10
+ * @param ifRule - Rule to execute when predicate returns true
11
+ * @param elseRule - Rule to execute when predicate returns false (optional)
12
+ * @returns A new rule that conditionally executes one of two rules
13
+ * @example
14
+ * const rule = branch(
15
+ * (user) => user.age >= 18,
16
+ * validateAdultAccount,
17
+ * validateMinorAccount
18
+ * );
19
+ *
20
+ * // Without elseRule (passes when predicate is false)
21
+ * const adultOnlyRule = branch(
22
+ * (user) => user.age >= 18,
23
+ * validateAdultAccount
24
+ * );
25
+ */
26
+ export const ifElse = <TInput, TError = string, TContext = unknown>(
27
+ predicate: (input: TInput, context?: TContext) => boolean | Promise<boolean>,
28
+ ifRule: Rule<TInput, TError, TContext>,
29
+ elseRule?: Rule<TInput, TError, TContext>,
30
+ ): Rule<TInput, TError, TContext> => {
31
+ return async (input: TInput, context?: TContext) => {
32
+ const shouldBranch = await predicate(input, context);
33
+ return shouldBranch
34
+ ? ifRule(input, context)
35
+ : elseRule
36
+ ? elseRule(input, context)
37
+ : pass();
38
+ };
39
+ };
@@ -0,0 +1,8 @@
1
+ export * from "./every";
2
+ export * from "./if-else";
3
+ export * from "./match";
4
+ export * from "./not";
5
+ export * from "./one-of";
6
+ export * from "./unless";
7
+ export * from "./when";
8
+ export * from "./with-fallback";