ts-rules-composer 0.0.1 → 1.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.
- package/README.md +310 -42
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +335 -55
- package/dist/index.d.ts +335 -55
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +27 -6
- package/.editorconfig +0 -15
- package/.eslintrc.json +0 -66
- package/.github/CONTRIBUTING.md +0 -3
- package/.github/ISSUE_TEMPLATE.md +0 -9
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
- package/.github/workflows/docs.yml +0 -29
- package/.github/workflows/publish.yml +0 -25
- package/.github/workflows/test.yml +0 -37
- package/.prettierignore +0 -2
- package/.releaserc +0 -11
- package/src/lib/combinators/index.ts +0 -2
- package/src/lib/combinators/logic/every.spec.ts +0 -264
- package/src/lib/combinators/logic/every.ts +0 -47
- package/src/lib/combinators/logic/if-else.spec.ts +0 -72
- package/src/lib/combinators/logic/if-else.ts +0 -39
- package/src/lib/combinators/logic/index.ts +0 -8
- package/src/lib/combinators/logic/match.spec.ts +0 -186
- package/src/lib/combinators/logic/match.ts +0 -92
- package/src/lib/combinators/logic/not.spec.ts +0 -62
- package/src/lib/combinators/logic/not.ts +0 -25
- package/src/lib/combinators/logic/one-of.spec.ts +0 -68
- package/src/lib/combinators/logic/one-of.ts +0 -41
- package/src/lib/combinators/logic/unless.spec.ts +0 -61
- package/src/lib/combinators/logic/unless.ts +0 -27
- package/src/lib/combinators/logic/when.spec.ts +0 -123
- package/src/lib/combinators/logic/when.ts +0 -29
- package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
- package/src/lib/combinators/logic/with-fallback.ts +0 -37
- package/src/lib/combinators/utility/index.ts +0 -8
- package/src/lib/combinators/utility/inject.spec.ts +0 -55
- package/src/lib/combinators/utility/inject.ts +0 -25
- package/src/lib/combinators/utility/map-error.spec.ts +0 -63
- package/src/lib/combinators/utility/map-error.ts +0 -35
- package/src/lib/combinators/utility/tap.spec.ts +0 -102
- package/src/lib/combinators/utility/tap.ts +0 -38
- package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
- package/src/lib/combinators/utility/validate-field.ts +0 -59
- package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
- package/src/lib/combinators/utility/with-debug.ts +0 -55
- package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
- package/src/lib/combinators/utility/with-memoize.ts +0 -81
- package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
- package/src/lib/combinators/utility/with-retry.ts +0 -68
- package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
- package/src/lib/combinators/utility/with-timeout.ts +0 -34
- package/src/lib/composition/compose-rules.spec.ts +0 -211
- package/src/lib/composition/compose-rules.ts +0 -47
- package/src/lib/composition/index.ts +0 -3
- package/src/lib/composition/pipe-rules.spec.ts +0 -220
- package/src/lib/composition/pipe-rules.ts +0 -44
- package/src/lib/composition/pipe.spec.ts +0 -47
- package/src/lib/composition/pipe.ts +0 -106
- package/src/lib/helpers/context/has-context.ts +0 -13
- package/src/lib/helpers/context/index.ts +0 -3
- package/src/lib/helpers/context/require-context.spec.ts +0 -55
- package/src/lib/helpers/context/require-context.ts +0 -61
- package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
- package/src/lib/helpers/context/with-lazy-context.ts +0 -35
- package/src/lib/helpers/index.ts +0 -6
- package/src/lib/helpers/result/fail.ts +0 -15
- package/src/lib/helpers/result/index.ts +0 -2
- package/src/lib/helpers/result/pass.ts +0 -14
- package/src/lib/helpers/retry/calculate-delay.ts +0 -31
- package/src/lib/index.ts +0 -4
- package/src/lib/types/composition-options.ts +0 -7
- package/src/lib/types/debug-options.ts +0 -36
- package/src/lib/types/index.ts +0 -4
- package/src/lib/types/rule-result.ts +0 -16
- package/src/lib/types/rule.ts +0 -21
- package/src/test/helpers/get-rule-error.ts +0 -23
- package/src/test/integration.spec.ts +0 -285
- package/tsconfig.json +0 -55
- package/tsup.config.ts +0 -36
- package/vitest.config.ts +0 -16
package/dist/index.js.map
CHANGED
|
@@ -1 +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,OCE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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"]}
|
|
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/helpers/safety/get-normalized-rule.ts","../src/lib/helpers/safety/get-normalized-rules.ts","../src/lib/helpers/clone/clone.ts","../src/lib/helpers/clone/shallowClone.ts","../src/lib/helpers/clone/getCloneFn.ts","../src/lib/combinators/logic/every.ts","../src/lib/combinators/utility/inject.ts","../src/lib/combinators/utility/map-error.ts","../src/lib/combinators/utility/tap.ts","../src/lib/combinators/utility/with-tap.ts","../src/lib/combinators/utility/validate-field.ts","../src/lib/combinators/utility/with-debug.ts","../src/lib/combinators/utility/with-memoize.ts","../src/lib/combinators/utility/with-retry.ts","../src/lib/combinators/utility/with-safe-error.ts","../src/lib/combinators/utility/with-safe-predicate.ts","../src/lib/combinators/utility/with-timeout.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/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","getNormalizedRule","opts","withSafeError","getNormalizedRules","rules","_a","clone","obj","e","shallowClone","getCloneFn","canUseStructuredClone","every","options","cloneFn","currentContext","normalizedRules","errors","r","inject","dependency","configuredRule","mapError","transform","result","tap","effect","withTap","validateField","getter","defaultValue","value","finalValue","safeRule","withDebug","config","_b","_c","startTime","ruleName","duration","withMemoize","keyFn","cache","key","now","entry","oldestKey","withRetry","attempts","delayMs","shouldRetry","lastError","delay","resolve","errorTransform","withSafePredicate","predicate","withTimeout","timeoutMs","timeoutError","timeout","ifElse","ifRule","elseRule","safePredicateResult","normalizedIfRule","normalizedElseRule","isRule","match","accessor","cases","defaultCase","matchedRule","not","oneOf","unless","normalizedRule","when","withFallback","mainRule","fallbackRule","mainSafeRule","fallbackSafeRule","composeRules","i","pipeRules","pipe","fns","acc","fn"],"mappings":"AAUO,IAAMA,EAAiBC,CACrBA,EAAAA,CAAAA,GAAQ,OCEJC,IAAAA,CAAAA,CAAyBC,IACnC,CAAE,MAAA,CAAQ,QAAU,CAAA,KAAA,CAAAA,CAAM,CCFtB,EAAA,IAAMC,EAAO,KACjB,CAAE,OAAQ,QAAS,CAAA,ECUTC,IAAAA,CAAAA,CAAqB,CAMhCF,CACAG,CAAAA,CAAAA,CAIAC,IACmC,CAKnC,IAAMC,EAAQD,CAJQN,GAAAA,CAAAA,EACbA,IAAQ,MAKjB,CAAA,CAAA,aAAcQ,CAAeC,CAAAA,CAAAA,GACpBF,EAAME,CAAO,CAAA,CAAIJ,EAAKG,CAAOC,CAAAA,CAAO,CAAIR,CAAAA,CAAAA,CAAKC,CAAK,CAE7D,MCzBaQ,CAAkB,CAAA,CAC7BC,EACAN,CAEO,GAAA,MAAOG,GAAkB,CAC9B,GAAI,CACF,IAAMC,CAAAA,CAAU,MAAME,CAAOH,CAAAA,CAAK,EAClC,OAAOH,CAAAA,CAAKG,CAAOC,CAAAA,CAAO,CAC5B,CAASP,MAAAA,CAAAA,CAAO,CACd,IAAMU,CAAAA,CACJV,aAAiB,KAAQA,CAAAA,CAAAA,CAAM,QAAU,wBAC3C,CAAA,OAAOD,EAAKW,CAAsB,CACpC,CACF,EC/BK,IAAMC,EAAiB,CAC5BC,CAAAA,CACAC,CACAC,CAAAA,CAAAA,GACW,CACX,IAAMC,CAAAA,CAA0D,CAC9D,KAAO,CAAA,IAAMD,E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AK,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 type { 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 type { 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 type { 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 type { 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 type { 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 { withSafeError } from \"../../combinators\";\nimport type { Rule, RuleSafetyOptions } from \"../../types\";\n\nexport const getNormalizedRule = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n opts?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n const normalizedRule =\n opts?.errorHandlingMode === \"unsafe\"\n ? rule\n : withSafeError(rule, opts?.errorTransform);\n\n return normalizedRule;\n};\n","import { withSafeError } from \"../../combinators\";\nimport type { Rule, RuleSafetyOptions } from \"../../types\";\n\nexport const getNormalizedRules = <TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n opts?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError, TContext>[] => {\n const normalizedRules =\n opts?.errorHandlingMode === \"unsafe\"\n ? rules\n : (rules || [])?.map((rule) => withSafeError(rule, opts?.errorTransform));\n\n return normalizedRules;\n};\n","export const clone = <T>(obj: T): T => {\n if (!obj) return {} as T;\n try {\n return JSON.parse(JSON.stringify(obj));\n } catch (e) {\n console.warn(\n `Clone failed for ${obj?.constructor?.name}, returning empty object`,\n e,\n );\n return {} as T;\n }\n};\n","export const shallowClone = <T>(obj: T): T => {\n if (!obj) return {} as T;\n try {\n return { ...obj };\n } catch (e) {\n console.warn(\n `Clone failed for ${obj?.constructor?.name}, returning empty object`,\n e,\n );\n return {} as T;\n }\n};\n","import type { CompositionOptions } from \"../../types\";\n\nimport { clone } from \"./clone\";\nimport { shallowClone } from \"./shallowClone\";\n\nexport const getCloneFn = (opts: CompositionOptions<unknown>) => {\n const canUseStructuredClone = typeof structuredClone !== \"undefined\";\n\n const cloneFn =\n opts.cloneStrategy === \"shallow\"\n ? shallowClone\n : opts.cloneStrategy === \"structured\" && canUseStructuredClone\n ? structuredClone\n : clone;\n\n return cloneFn;\n};\n","import { fail, getNormalizedRules, pass } from \"../../helpers\";\nimport { getCloneFn } from \"../../helpers/clone/getCloneFn\";\nimport type { 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 * @param options.cloneStrategy -Which strategy to use when cloning the context\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 * - Cloning behavior follows this priority:\n * 1. Uses shallowClone if options.shallowClone = true\n * 2. Uses structuredClone if available and options.structuredClone = true\n * 3. Falls back to JSON clone otherwise\n */\nexport const every = <TInput, TError = string, TContext = unknown>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError> = {},\n): Rule<TInput, TError[], TContext> => {\n return async (input: TInput, context?: TContext) => {\n const cloneFn = getCloneFn(options);\n const currentContext = options?.cloneContext ? cloneFn(context) : context;\n const normalizedRules = getNormalizedRules(rules, options);\n\n const results = await Promise.all(\n normalizedRules.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 type { 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 type { 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 { pass } from \"../../helpers\";\nimport type { Rule } from \"../../types\";\n\n/**\n * Creates a standalone tap effect for use in composition pipelines\n * @template TInput - Input type\n * @template TError - Error type\n * @template TContext - Context type\n * @param effect - Side effect function receiving (input, context)\n * @returns A rule that passes through input unchanged\n * @example\n * pipeRules([\n * tap((input) => console.log('Processing:', input)),\n * validateInput\n * ])\n */\nexport const tap = <TInput, TError = string, TContext = unknown>(\n effect: (input: TInput, context?: TContext) => Promise<void> | void,\n): Rule<TInput, TError, TContext> => {\n return async (input, context) => {\n try {\n await effect(input, context);\n } catch (error) {\n console.error(\"Tap effect failed: \", error);\n }\n return pass();\n };\n};\n","import { getNormalizedRule } from \"../../helpers\";\nimport type { Rule, RuleResult, RuleSafetyOptions } 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 * @param options - Configuration for error handling safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 withTap = <TInput, TError = string, TContext = unknown>(\n effect: (\n input: TInput,\n result: RuleResult<TError>,\n context?: TContext,\n ) => Promise<void> | void,\n options?: RuleSafetyOptions<TError>,\n): ((\n rule: Rule<TInput, TError, TContext>,\n) => Rule<TInput, TError, TContext>) => {\n return (rule) => async (input, context) => {\n const safeRule = getNormalizedRule(rule, options);\n const result = await safeRule(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 { fail, getNormalizedRule } from \"../../helpers\";\nimport type { Rule, RuleSafetyOptions } 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 * @param options - Configuration for error handling safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 options?: RuleSafetyOptions<TError>,\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 const safeRule = getNormalizedRule(rule, options);\n\n if (finalValue === undefined) {\n return fail(\"Missing required value\" as unknown as TError);\n }\n\n return safeRule(finalValue, context);\n };\n}\n","import type { 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 { getNormalizedRule } from \"../../helpers\";\nimport type { Rule, RuleResult, RuleSafetyOptions } 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 and safety 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 * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 * - Successful results obey TTL rules\n * - Cache is shared across rule instances\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 } & RuleSafetyOptions<TError> = {},\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 normalizedRule = getNormalizedRule(rule, options);\n const result = normalizedRule(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 { calculateDelay, fail } from \"../../helpers\";\nimport type { Rule } from \"../../types\";\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\") {\n return result;\n }\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 type { Rule, RuleResult } from \"../../types\";\n\n/**\n * Wraps a rule to catch errors and convert them to failed RuleResults\n * @template TInput - The input type\n * @template TError - The error type (defaults to string)\n * @template TContext - The context type\n * @param rule - The rule to protect\n * @param errorMapper - Optional error transformation logic\n * @returns A protected version of the rule\n * @example\n * // Basic usage with default error handling\n * const safeRule = withSafeError(riskyRule);\n *\n * // With custom error transformation\n * const customSafeRule = withSafeError(riskyRule, e => ({\n * code: 500,\n * message: String(e)\n * }));\n *\n * @caveats\n *\n * - Generic parameters must be explicitly set for custom error types\n * - Doesn't verify error types match TError at runtime\n */\nexport const withSafeError = <TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n errorTransform: (error: unknown) => TError = (e) => {\n // Preserve object structure if TError is object-like\n if (typeof e === \"object\" && e !== null) return e as TError;\n // Default to string for primitives/errors\n return (e instanceof Error ? e.message : String(e)) as TError;\n },\n): Rule<TInput, TError, TContext> => {\n return async (\n input: TInput,\n context?: TContext,\n ): Promise<RuleResult<TError>> => {\n try {\n const result = await rule(input, context);\n\n // Preserve existing RuleResults\n if (result && typeof result === \"object\" && \"status\" in result) {\n return result;\n }\n\n // Handle invalid rule implementations that don't return RuleResult\n return fail(\n errorTransform(new Error(`Invalid rule - did not return RuleResult`)),\n );\n } catch (error) {\n return fail(errorTransform(error));\n }\n };\n};\n","import type { Predicate, PredicateSafe, PredicateResult } from \"../../types\";\n\n/**\n * Wraps a predicate function with error handling and type safety.\n * @template TInput - The input type\n * @template TError - The error type (defaults to string)\n * @template TContext - The context type\n * @param predicate - The predicate function to wrap\n * @param errorTransform - Optional function to transform errors\n * @returns A safe predicate that never throws\n *\n * @example\n * const safePredicate = withSafePredicate(\n * (input: string) => input.length > 5,\n * (err) => `Predicate failed: ${String(err)}`\n * );\n *\n * @caveats\n * **Error Handling Behavior**:\n * - Will catch both synchronous throws and Promise rejections\n * - Errors in the errorTransform itself will propagate (not caught)\n * - The default transformer converts all errors to strings except Error objects\n *\n * **Edge Cases**:\n * - Returns failed result for non-boolean returns (including null/undefined)\n * - Returns failed result for Promise<non-boolean> resolutions\n * - Returns failed result for Promise rejections (transformed via errorTransform)\n * - Returns failed result for thrown non-Error values (like `throw \"string\"`)\n */\nexport const withSafePredicate = <TInput, TError = string, TContext = unknown>(\n predicate: Predicate<TInput, TContext>,\n errorTransform: (error: unknown) => TError = (e) => {\n // Preserve object structure if TError is object-like\n if (typeof e === \"object\" && e !== null) return e as TError;\n // Default to string for primitives/errors\n return (e instanceof Error ? e.message : String(e)) as TError;\n },\n): PredicateSafe<TInput, TError, TContext> => {\n return async (\n input: TInput,\n context?: TContext,\n ): Promise<PredicateResult<TError>> => {\n try {\n const result = await predicate(input, context);\n\n // Check if result is a boolean\n if (typeof result === \"boolean\") {\n return { status: \"passed\", value: result };\n }\n\n return {\n status: \"failed\",\n error: errorTransform(\n new Error(`Predicate must return boolean, got ${typeof result}`),\n ),\n };\n } catch (error) {\n return {\n status: \"failed\",\n error: errorTransform(error),\n };\n }\n };\n};\n","import { fail, getNormalizedRule } from \"../../helpers\";\nimport type { Rule, RuleResult, RuleSafetyOptions } 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 * @param options - Configuration for error handling safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 options?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n return async (input, context) => {\n const safeRule = getNormalizedRule(rule, options);\n const timeout = new Promise<RuleResult<TError>>((resolve) =>\n setTimeout(() => resolve(fail(timeoutError)), timeoutMs),\n );\n return Promise.race([safeRule(input, context), timeout]);\n };\n};\n","import { fail, getNormalizedRules, pass } from \"../../helpers\";\nimport type { Predicate, Rule } from \"../../types\";\nimport type { SafetyOptions } from \"../../types/safety-options\";\nimport { withSafePredicate } from \"../utility\";\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 * @param options - Configuration for error handling and predicate safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\n * @param options.predicateErrorTransform - Special error handler for predicate failures\n * @returns A new rule that conditionally executes one of two rules\n * @example\n * const rule = ifElse(\n * (user) => user.age >= 18,\n * validateAdultAccount,\n * validateMinorAccount\n * );\n *\n * // Without elseRule (passes when predicate is false)\n * const adultOnlyRule = ifElse(\n * (user) => user.age >= 18,\n * validateAdultAccount\n * );\n */\nexport const ifElse = <TInput, TError = string, TContext = unknown>(\n predicate: Predicate<TInput, TContext>,\n ifRule: Rule<TInput, TError, TContext>,\n elseRule?: Rule<TInput, TError, TContext>,\n options?: SafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const safePredicate = withSafePredicate<TInput, TError, TContext>(\n predicate,\n options?.predicateErrorTransform,\n );\n const safePredicateResult = await safePredicate(input, context);\n\n // Predicate fail to run or returned invalid result\n if (safePredicateResult.status === \"failed\") {\n return fail(safePredicateResult.error);\n }\n\n const [normalizedIfRule, normalizedElseRule] = getNormalizedRules(\n [ifRule, elseRule!],\n options,\n );\n\n const shouldBranch = safePredicateResult.value;\n return shouldBranch\n ? normalizedIfRule(input, context)\n : elseRule\n ? normalizedElseRule(input, context)\n : pass();\n };\n};\n","import { fail, getNormalizedRule } from \"../../helpers\";\nimport type { Rule, RuleResult, RuleSafetyOptions } 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 * @param options - Configuration for error handling safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 options?: RuleSafetyOptions<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 const safeMatchedRule = getNormalizedRule(matchedRule, options);\n return safeMatchedRule(input, context);\n }\n\n if (defaultCase !== undefined) {\n // if default case is not a rule, fail the error/messae directly\n if (!isRule<TInput, TError, TContext>(defaultCase)) {\n return fail(defaultCase);\n }\n\n const safeDefaultCase = getNormalizedRule(\n defaultCase as Rule<TInput, TError, TContext>,\n options,\n );\n return safeDefaultCase(input, context);\n }\n\n return fail(`No matching rule for key: ${String(key)}` as TError);\n };\n};\n","import { pass, fail, getNormalizedRule } from \"../../helpers\";\nimport type { RuleSafetyOptions } from \"../../types\";\nimport type { 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 * @param options - Configuration for error handling safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 options?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError> => {\n return async (input: TInput, context?: unknown) => {\n const normalizedRule = getNormalizedRule(rule, options);\n\n const result = await normalizedRule(input, context);\n return result.status === \"passed\" ? fail(error) : pass();\n };\n};\n","import { fail, getNormalizedRules, pass } from \"../../helpers\";\nimport type { Rule, RuleSafetyOptions } 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 * @param options - Configuration for error handling\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 options?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError[], TContext> => {\n return async (input: TInput, context?: TContext) => {\n const normalizedRules = getNormalizedRules(rules, options);\n const errors: TError[] = [];\n\n if (!rules || rules.length === 0) {\n return pass();\n }\n\n for (const rule of normalizedRules) {\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 { fail, getNormalizedRule, pass } from \"../../helpers\";\nimport type { Predicate, Rule } from \"../../types\";\nimport type { SafetyOptions } from \"../../types/safety-options\";\nimport { withSafePredicate } from \"../utility\";\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 * @param options - Configuration for error handling and predicate safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\n * @param options.predicateErrorTransform - Special error handler for predicate failures\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: Predicate<TInput, TContext>,\n rule: Rule<TInput, TError, TContext>,\n options?: SafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const normalizedRule = getNormalizedRule(rule, options);\n const safePredicate = withSafePredicate<TInput, TError, TContext>(\n predicate,\n options?.predicateErrorTransform,\n );\n\n const safePredicateResult = await safePredicate(input, context);\n\n // Predicate fail to run or returned invalid result\n if (safePredicateResult.status === \"failed\") {\n return fail(safePredicateResult.error);\n }\n\n return safePredicateResult.value ? pass() : normalizedRule(input, context);\n };\n};\n","import { fail, getNormalizedRule } from \"../../helpers\";\nimport { pass } from \"../../helpers/result/pass\";\nimport type { Predicate } from \"../../types\";\nimport type { Rule } from \"../../types/rule\";\nimport type { SafetyOptions } from \"../../types/safety-options\";\nimport { withSafePredicate } from \"../utility\";\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 * @param options - Configuration for error handling and predicate safety\n * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\n * @param options.predicateErrorTransform - Special error handler for predicate failures\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, TContext = unknown>(\n predicate: Predicate<TInput, TContext>,\n rule: Rule<TInput, TError, TContext>,\n options?: SafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const normalizedRule = getNormalizedRule(rule, options);\n const safePredicate = withSafePredicate<TInput, TError, TContext>(\n predicate,\n options?.predicateErrorTransform,\n );\n\n const safePredicateResult = await safePredicate(input, context);\n if (safePredicateResult.status === \"failed\") {\n return fail(safePredicateResult.error);\n }\n\n return safePredicateResult.value ? normalizedRule(input, context) : pass();\n };\n};\n","import { getNormalizedRules } from \"../../helpers\";\nimport type { Rule, RuleSafetyOptions } 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 * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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: RuleSafetyOptions<TError> & {\n onlyFallbackOn?: (error: TError) => boolean;\n } = {},\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\n const [mainSafeRule, fallbackSafeRule] = getNormalizedRules([\n mainRule,\n fallbackRule,\n ]);\n const result = await mainSafeRule(input, context);\n if (\n result.status === \"failed\" &&\n (!options.onlyFallbackOn || options.onlyFallbackOn(result.error))\n ) {\n return fallbackSafeRule(input, context);\n }\n return result;\n };\n};\n","import { getNormalizedRules, pass } from \"../helpers\";\nimport { getCloneFn } from \"../helpers/clone/getCloneFn\";\nimport type { 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 * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 * - Cloning behavior follows this priority:\n * 1. Uses shallowClone if options.shallowClone = true\n * 2. Uses structuredClone if available and options.structuredClone = true\n * 3. Falls back to JSON clone otherwise\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 cloneFn = getCloneFn(options);\n const currentContext = options?.cloneContext ? cloneFn(context) : context;\n const normalizedRules = getNormalizedRules(rules);\n\n for (let i = normalizedRules.length - 1; i >= 0; i--) {\n const result = await normalizedRules[i](input, currentContext);\n if (result.status === \"failed\") {\n return result;\n }\n }\n return pass();\n };\n};\n","import { getNormalizedRules, pass } from \"../helpers\";\nimport { getCloneFn } from \"../helpers/clone/getCloneFn\";\nimport type { 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 * @param options.errorHandlingMode - Determines how errors are handled:\n * - 'safe': (default) Converts thrown errors to validation failures\n * - 'unsafe': Lets errors propagate (use only in performance-critical paths)\n * @param options.errorTransform - Custom transformation for caught errors\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 * - Cloning behavior follows this priority:\n * 1. Uses shallowClone if options.shallowClone = true\n * 2. Uses structuredClone if available and options.structuredClone = true\n * 3. Falls back to JSON clone otherwise\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 cloneFn = getCloneFn(options);\n const currentContext = options?.cloneContext ? cloneFn(context) : context;\n const normalizedRules = getNormalizedRules(rules);\n\n for (const rule of normalizedRules) {\n const result = await rule(input, currentContext);\n if (result.status === \"failed\") {\n return result;\n }\n }\n return pass();\n };\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype 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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ts-rules-composer",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "Typescript rules engine by composition",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -9,6 +9,12 @@
|
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"sideEffects": false,
|
|
11
11
|
"type": "module",
|
|
12
|
+
"files": [
|
|
13
|
+
"dist/**",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"package.json"
|
|
17
|
+
],
|
|
12
18
|
"exports": {
|
|
13
19
|
"import": {
|
|
14
20
|
"types": "./dist/index.d.ts",
|
|
@@ -32,15 +38,16 @@
|
|
|
32
38
|
"test:coverage": "vitest run --coverage",
|
|
33
39
|
"watch:build": "tsc -p tsconfig.json -w",
|
|
34
40
|
"watch:test": "vitest",
|
|
35
|
-
"generate-docs": "typedoc
|
|
41
|
+
"generate-docs": "typedoc --options typedoc/typedoc.json",
|
|
36
42
|
"release": "semantic-release"
|
|
37
43
|
},
|
|
38
44
|
"engines": {
|
|
39
45
|
"node": ">=18"
|
|
40
46
|
},
|
|
41
47
|
"devDependencies": {
|
|
42
|
-
"@
|
|
43
|
-
"@
|
|
48
|
+
"@eslint/compat": "^1.2.9",
|
|
49
|
+
"@eslint/eslintrc": "^3.3.1",
|
|
50
|
+
"@eslint/js": "^9.26.0",
|
|
44
51
|
"@vitest/coverage-v8": "^3.1.2",
|
|
45
52
|
"conventional-changelog-conventionalcommits": "^8.0.0",
|
|
46
53
|
"cspell": "^8.19.2",
|
|
@@ -58,7 +65,21 @@
|
|
|
58
65
|
"ts-node": "^10.9.2",
|
|
59
66
|
"tsup": "^8.4.0",
|
|
60
67
|
"typedoc": "^0.28.3",
|
|
68
|
+
"typedoc-github-theme": "^0.3.0",
|
|
69
|
+
"typedoc-plugin-mermaid": "^1.12.0",
|
|
61
70
|
"typescript": "^5.8.3",
|
|
71
|
+
"typescript-eslint": "^8.32.1",
|
|
62
72
|
"vitest": "^3.1.2"
|
|
63
|
-
}
|
|
64
|
-
|
|
73
|
+
},
|
|
74
|
+
"keywords": [
|
|
75
|
+
"validation",
|
|
76
|
+
"rules engine",
|
|
77
|
+
"typescript",
|
|
78
|
+
"pipeline",
|
|
79
|
+
"combinator",
|
|
80
|
+
"functional",
|
|
81
|
+
"context-aware",
|
|
82
|
+
"business logic",
|
|
83
|
+
"async"
|
|
84
|
+
]
|
|
85
|
+
}
|
package/.editorconfig
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
# http://editorconfig.org
|
|
2
|
-
root = true
|
|
3
|
-
|
|
4
|
-
[*]
|
|
5
|
-
charset = utf-8
|
|
6
|
-
end_of_line = lf
|
|
7
|
-
indent_size = 2
|
|
8
|
-
indent_style = space
|
|
9
|
-
insert_final_newline = true
|
|
10
|
-
max_line_length = 80
|
|
11
|
-
trim_trailing_whitespace = true
|
|
12
|
-
|
|
13
|
-
[*.md]
|
|
14
|
-
max_line_length = 0
|
|
15
|
-
trim_trailing_whitespace = false
|
package/.eslintrc.json
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"root": true,
|
|
3
|
-
"parser": "@typescript-eslint/parser",
|
|
4
|
-
"parserOptions": {
|
|
5
|
-
"project": "./tsconfig.json"
|
|
6
|
-
},
|
|
7
|
-
"env": {
|
|
8
|
-
"es6": true
|
|
9
|
-
},
|
|
10
|
-
"ignorePatterns": [
|
|
11
|
-
"node_modules",
|
|
12
|
-
"build",
|
|
13
|
-
"coverage",
|
|
14
|
-
"vitest.config.js"
|
|
15
|
-
],
|
|
16
|
-
"plugins": [
|
|
17
|
-
"import",
|
|
18
|
-
"eslint-comments"
|
|
19
|
-
],
|
|
20
|
-
"extends": [
|
|
21
|
-
"eslint:recommended",
|
|
22
|
-
"plugin:eslint-comments/recommended",
|
|
23
|
-
"plugin:@typescript-eslint/recommended",
|
|
24
|
-
"plugin:import/typescript",
|
|
25
|
-
"prettier",
|
|
26
|
-
"prettier/@typescript-eslint"
|
|
27
|
-
],
|
|
28
|
-
"globals": {
|
|
29
|
-
"BigInt": true,
|
|
30
|
-
"console": true,
|
|
31
|
-
"WebAssembly": true
|
|
32
|
-
},
|
|
33
|
-
"rules": {
|
|
34
|
-
"@typescript-eslint/explicit-module-boundary-types": "off",
|
|
35
|
-
"@typescript-eslint/no-unused-vars": [
|
|
36
|
-
1,
|
|
37
|
-
{
|
|
38
|
-
"argsIgnorePattern": "^_",
|
|
39
|
-
"varsIgnorePattern": "^_"
|
|
40
|
-
}
|
|
41
|
-
],
|
|
42
|
-
"eslint-comments/disable-enable-pair": [
|
|
43
|
-
"error",
|
|
44
|
-
{
|
|
45
|
-
"allowWholeFile": true
|
|
46
|
-
}
|
|
47
|
-
],
|
|
48
|
-
"eslint-comments/no-unused-disable": "error",
|
|
49
|
-
"import/order": [
|
|
50
|
-
"error",
|
|
51
|
-
{
|
|
52
|
-
"newlines-between": "always",
|
|
53
|
-
"alphabetize": {
|
|
54
|
-
"order": "asc"
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
],
|
|
58
|
-
"quotes": [
|
|
59
|
-
"error",
|
|
60
|
-
"single",
|
|
61
|
-
{
|
|
62
|
-
"allowTemplateLiterals": true
|
|
63
|
-
}
|
|
64
|
-
]
|
|
65
|
-
}
|
|
66
|
-
}
|
package/.github/CONTRIBUTING.md
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
- **I'm submitting a ...**
|
|
2
|
-
[ ] bug report
|
|
3
|
-
[ ] feature request
|
|
4
|
-
[ ] question about the decisions made in the repository
|
|
5
|
-
[ ] question about how to use this project
|
|
6
|
-
|
|
7
|
-
- **Summary**
|
|
8
|
-
|
|
9
|
-
- **Other information** (e.g. detailed explanation, stack traces, related issues, suggestions how to fix, links for us to have context, eg. StackOverflow, personal fork, etc.)
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
name: docs
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
push:
|
|
5
|
-
branches:
|
|
6
|
-
- main
|
|
7
|
-
|
|
8
|
-
jobs:
|
|
9
|
-
test:
|
|
10
|
-
runs-on: ubuntu-latest
|
|
11
|
-
strategy:
|
|
12
|
-
matrix:
|
|
13
|
-
node-version: [22.x]
|
|
14
|
-
steps:
|
|
15
|
-
- uses: actions/checkout@v2
|
|
16
|
-
- name: Build on Node.js ${{ matrix.node-version }}
|
|
17
|
-
uses: actions/setup-node@v3
|
|
18
|
-
with:
|
|
19
|
-
node-version: ${{ matrix.node-version }}
|
|
20
|
-
- run: npm ci --ignore-scripts
|
|
21
|
-
|
|
22
|
-
- name: Run typedoc to generate html documentation
|
|
23
|
-
run: npm run generate-docs
|
|
24
|
-
|
|
25
|
-
- name: Deploy 🚀
|
|
26
|
-
uses: JamesIves/github-pages-deploy-action@4.1.4
|
|
27
|
-
with:
|
|
28
|
-
branch: gh-pages
|
|
29
|
-
folder: genDocs
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
name: publish
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
workflow_run:
|
|
5
|
-
workflows: ["test"]
|
|
6
|
-
branches: [main]
|
|
7
|
-
types:
|
|
8
|
-
- completed
|
|
9
|
-
|
|
10
|
-
jobs:
|
|
11
|
-
publish:
|
|
12
|
-
if: ${{ github.event.workflow_run.conclusion == 'success' }} && github.ref == 'refs/heads/main'
|
|
13
|
-
runs-on: ubuntu-latest
|
|
14
|
-
steps:
|
|
15
|
-
- uses: actions/checkout@v4
|
|
16
|
-
- uses: actions/setup-node@v4
|
|
17
|
-
with:
|
|
18
|
-
node-version: 22
|
|
19
|
-
registry-url: 'https://registry.npmjs.org'
|
|
20
|
-
- run: npm ci --ignore-scripts
|
|
21
|
-
- run: npm run build --if-present
|
|
22
|
-
- name: Publish
|
|
23
|
-
run: npm run release
|
|
24
|
-
env:
|
|
25
|
-
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
name: test
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
push:
|
|
5
|
-
branches:
|
|
6
|
-
- main
|
|
7
|
-
- dev
|
|
8
|
-
|
|
9
|
-
pull_request:
|
|
10
|
-
types:
|
|
11
|
-
- opened
|
|
12
|
-
- synchronize
|
|
13
|
-
|
|
14
|
-
jobs:
|
|
15
|
-
test:
|
|
16
|
-
runs-on: ubuntu-latest
|
|
17
|
-
strategy:
|
|
18
|
-
matrix:
|
|
19
|
-
node-version: [22.x]
|
|
20
|
-
steps:
|
|
21
|
-
- uses: actions/checkout@v2
|
|
22
|
-
- name: Build on Node.js ${{ matrix.node-version }}
|
|
23
|
-
uses: actions/setup-node@v1
|
|
24
|
-
with:
|
|
25
|
-
node-version: ${{ matrix.node-version }}
|
|
26
|
-
- run: npm ci --ignore-scripts
|
|
27
|
-
- run: npm run build --if-present
|
|
28
|
-
name: Build
|
|
29
|
-
- run: npm test
|
|
30
|
-
env:
|
|
31
|
-
CI: true
|
|
32
|
-
- run: npm run lint
|
|
33
|
-
env:
|
|
34
|
-
CI: true
|
|
35
|
-
- run: npm run format
|
|
36
|
-
env:
|
|
37
|
-
CI: true
|
package/.prettierignore
DELETED
package/.releaserc
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
branches:
|
|
2
|
-
- main
|
|
3
|
-
- name: alpha
|
|
4
|
-
prerelease: true
|
|
5
|
-
debug: true
|
|
6
|
-
ci: true
|
|
7
|
-
dryRun: false
|
|
8
|
-
plugins:
|
|
9
|
-
- ["@semantic-release/commit-analyzer", { "preset": "conventionalcommits" }]
|
|
10
|
-
- "@semantic-release/release-notes-generator"
|
|
11
|
-
- "@semantic-release/npm"
|