ts-rules-composer 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- const e=e=>e!==void 0,t=e=>({status:`failed`,error:e}),n=()=>({status:`passed`}),r=(e,n,r)=>{let i=r||(e=>e!==void 0);return async(r,a)=>i(a)?n(r,a):t(e)},i=(e,n)=>async r=>{try{return n(r,await e(r))}catch(e){let n=e instanceof Error?e.message:`Context loading failed`;return t(n)}},a=(e,t,n)=>{let r={fixed:()=>n,linear:e=>n*e,exponential:e=>n*2**(e-1)};if(!e)return r.fixed(t);if(typeof e==`string`){let i=r[e];return i?i(t):n}return typeof e==`function`?e(t):r.fixed(t)},o=(e,t)=>t?.errorHandlingMode===`unsafe`?e:b(e,t?.errorTransform),s=(e,t)=>t?.errorHandlingMode===`unsafe`?e:(e||[])?.map(e=>b(e,t?.errorTransform)),c=e=>{if(!e)return{};try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},l=e=>{if(!e)return{};try{return{...e}}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},u=e=>{let t=typeof structuredClone<`u`;return e.cloneStrategy===`shallow`?l:e.cloneStrategy===`structured`&&t?structuredClone:c};function d(e,r,i){let a=s([...e],r),o=u(r),c=r.cloneContext;return async(e,r)=>{let s=c?o(r):r;if(i===`parallelCollect`){let r=(await Promise.all(a.map(t=>t(e,s)))).flatMap(e=>e.status===`failed`?[e.error]:[]);return r.length>0?t(r):n()}let l=i===`forwardFailFast`?a:[...a].reverse();for(let t of l){let n=await t(e,s);if(n.status===`failed`)return n}return n()}}const f=(e,t={})=>d(e,t,`parallelCollect`),p=(e,t)=>{let n=t(e);return(e,t)=>n(e,t)},m=(e,r)=>async(i,a)=>{let o=await e(i,a);return o.status===`failed`?t(r(o.error)):n()},h=e=>async(t,r)=>{try{await e(t,r)}catch(e){console.error(`Tap effect failed: `,e)}return n()};function g(e,n,r,i){return async(a,s)=>{let c=e(a),l=c===void 0?r:c,u=o(n,i);return l===void 0?t(`Missing required value`):u(l,s)}}const _=(e,t)=>{let n=typeof t==`string`?{name:t}:t;return async(t,r)=>{let i=performance.now(),a=n.name||e.name||`anonymous_rule`;try{n.onStart?.(t,r);let o=await e(t,r),s=performance.now()-i;return n.onEnd?.(t,o,r,{ruleName:a,duration:s,startTime:i}),o}catch(e){let a=performance.now()-i;throw n.onError?.(e,t,r,a),e}}},v=(e,t,n={})=>{let r=/* @__PURE__ */ new Map;return async(i,a)=>{let s=t(i,a),c=Date.now();if(n.ttl)for(let[e,t]of r)c-t.timestamp>n.ttl&&r.delete(e);let l=r.get(s);if(l)return l.result;if(n.maxSize&&r.size>=n.maxSize){let e=r.keys().next().value;e!==void 0&&r.delete(e)}let u=o(e,n)(i,a);return r.set(s,{result:u,timestamp:c}),u instanceof Promise&&u.catch(()=>r.delete(s)),u}};function y(e,n={}){let{attempts:r=3,delayMs:i=100,shouldRetry:o=()=>!0,retryOn:s=`both`,onExhausted:c=`max-retries`}=n;return async(l,u)=>{let d,f;for(let c=1;c<=r;c++){try{let t=await e(l,u);if(t.status===`passed`)return t;d=t.error,f=!1}catch(e){d=e,f=!0}if(s!==`both`&&s!==(f?`thrown`:`failed`)||!o(d,c))return t(d);if(c<r&&i>0){let e=a(n?.retryStrategy,c,i);await new Promise(t=>setTimeout(t,e))}}return t(c===`last-error`?d:`MAX_RETRIES_EXCEEDED`)}}const b=(e,n=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(r,i)=>{try{let a=await e(r,i);return a&&typeof a==`object`&&`status`in a?a:t(n(/* @__PURE__ */ Error(`Invalid rule - did not return RuleResult`)))}catch(e){return t(n(e))}},x=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(n,r)=>{try{let i=await e(n,r);return typeof i==`boolean`?{status:`passed`,value:i}:{status:`failed`,error:t(/* @__PURE__ */ Error(`Predicate must return boolean, got ${typeof i}`))}}catch(e){return{status:`failed`,error:t(e)}}},S=(e,t)=>n=>async(r,i)=>{let a=await o(n,t)(r,i);try{await e(r,a,i)}catch(e){console.error(`Tap effect failed:`,e)}return a},C=(e,n,r,i)=>async(a,s)=>{let c=o(e,i),l=new Promise(e=>setTimeout(()=>e(t(r)),n));return Promise.race([c(a,s),l])},w=(e,r,i,a)=>async(o,c)=>{let l=await x(e,a?.predicateErrorTransform)(o,c);if(l.status===`failed`)return t(l.error);let[u,d]=s([r,i],a);return l.value?u(o,c):i?d(o,c):n()},T=e=>typeof e==`function`,E=(e,n,r,i)=>async(a,s)=>{let c=await e(a,s),l=n[c];return l?o(l,i)(a,s):r===void 0?t(`No matching rule for key: ${String(c)}`):T(r)?o(r,i)(a,s):t(r)},D=(e,r,i)=>async(a,s)=>(await o(e,i)(a,s)).status===`passed`?t(r):n(),O=(e,r)=>async(i,a)=>{let o=s(e,r),c=[];if(!e||e.length===0)return n();for(let e of o){let t=await e(i,a);if(t.status===`passed`)return n();c.push(t.error)}return t(c)},k=(e,r,i)=>async(a,s)=>{let c=o(r,i),l=await x(e,i?.predicateErrorTransform)(a,s);return l.status===`failed`?t(l.error):l.value?n():c(a,s)},A=(e,r,i)=>async(a,s)=>{let c=o(r,i),l=await x(e,i?.predicateErrorTransform)(a,s);return l.status===`failed`?t(l.error):l.value?c(a,s):n()},j=(e,t,n={})=>async(r,i)=>{let[a,o]=s([e,t],n),c=await a(r,i);return c.status===`failed`&&(!n.onlyFallbackOn||n.onlyFallbackOn(c.error))?o(r,i):c},M=(e,t={})=>d(e,t,`reverseFailFast`);function N(e,...t){return t.reduce((e,t)=>t(e),e)}const P=(e,t={})=>d(e,t,`forwardFailFast`);export{a as calculateDelay,M as composeRules,f as every,t as fail,o as getNormalizedRule,s as getNormalizedRules,e as hasContext,w as ifElse,p as inject,m as mapError,E as match,D as not,O as oneOf,n as pass,N as pipe,P as pipeRules,r as requireContextRule,h as tap,k as unless,g as validateField,A as when,_ as withDebug,j as withFallback,i as withLazyContext,v as withMemoize,y as withRetry,b as withSafeError,x as withSafePredicate,S as withTap,C as withTimeout};
1
+ import{n as e,t}from"./to-graph-Dd9xksGt.js";const n=e=>e!==void 0,r=e=>({status:`failed`,error:e}),i=()=>({status:`passed`}),a=(e,t,n)=>{let i=n||(e=>e!==void 0);return async(n,a)=>i(a)?t(n,a):r(e)},o=(e,t)=>async n=>{try{return t(n,await e(n))}catch(e){let t=e instanceof Error?e.message:`Context loading failed`;return r(t)}},s=(e,t,n)=>{let r={fixed:()=>n,linear:e=>n*e,exponential:e=>n*2**(e-1)};if(!e)return r.fixed(t);if(typeof e==`string`){let i=r[e];return i?i(t):n}return typeof e==`function`?e(t):r.fixed(t)},c=(e,t)=>t?.errorHandlingMode===`unsafe`?e:S(e,t?.errorTransform),l=(e,t)=>t?.errorHandlingMode===`unsafe`?e:(e||[])?.map(e=>S(e,t?.errorTransform)),u=e=>{if(!e)return{};try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},d=e=>{if(!e)return{};try{return{...e}}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},f=e=>{let t=typeof structuredClone<`u`;return e.cloneStrategy===`shallow`?d:e.cloneStrategy===`structured`&&t?structuredClone:u};function p(e,t,n){let a=l([...e],t),o=f(t),s=t.cloneContext;return async(e,t)=>{let c=s?o(t):t;if(n===`parallelCollect`){let t=(await Promise.all(a.map(t=>t(e,c)))).flatMap(e=>e.status===`failed`?[e.error]:[]);return t.length>0?r(t):i()}let l=n===`forwardFailFast`?a:[...a].reverse();for(let t of l){let n=await t(e,c);if(n.status===`failed`)return n}return i()}}const m=(e,t={})=>p(e,t,`parallelCollect`),h=(e,t)=>{let n=t(e);return(e,t)=>n(e,t)},g=(e,t)=>async(n,a)=>{let o=await e(n,a);return o.status===`failed`?r(t(o.error)):i()},_=e=>async(t,n)=>{try{await e(t,n)}catch(e){console.error(`Tap effect failed: `,e)}return i()};function v(e,t,n,i){return async(a,o)=>{let s=e(a),l=s===void 0?n:s,u=c(t,i);return l===void 0?r(`Missing required value`):u(l,o)}}const y=(e,t)=>{let n=typeof t==`string`?{name:t}:t;return async(t,r)=>{let i=performance.now(),a=n.name||e.name||`anonymous_rule`;try{n.onStart?.(t,r);let o=await e(t,r),s=performance.now()-i;return n.onEnd?.(t,o,r,{ruleName:a,duration:s,startTime:i}),o}catch(e){let a=performance.now()-i;throw n.onError?.(e,t,r,a),e}}},b=(e,t,n={})=>{let r=/* @__PURE__ */ new Map;return async(i,a)=>{let o=t(i,a),s=Date.now();if(n.ttl)for(let[e,t]of r)s-t.timestamp>n.ttl&&r.delete(e);let l=r.get(o);if(l)return l.result;if(n.maxSize&&r.size>=n.maxSize){let e=r.keys().next().value;e!==void 0&&r.delete(e)}let u=c(e,n)(i,a);return r.set(o,{result:u,timestamp:s}),u instanceof Promise&&u.catch(()=>r.delete(o)),u}};function x(e,t={}){let{attempts:n=3,delayMs:i=100,shouldRetry:a=()=>!0,retryOn:o=`both`,onExhausted:c=`max-retries`}=t;return async(l,u)=>{let d,f;for(let c=1;c<=n;c++){try{let t=await e(l,u);if(t.status===`passed`)return t;d=t.error,f=!1}catch(e){d=e,f=!0}if(o!==`both`&&o!==(f?`thrown`:`failed`)||!a(d,c))return r(d);if(c<n&&i>0){let e=s(t?.retryStrategy,c,i);await new Promise(t=>setTimeout(t,e))}}return r(c===`last-error`?d:`MAX_RETRIES_EXCEEDED`)}}const S=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(n,i)=>{try{let a=await e(n,i);return a&&typeof a==`object`&&`status`in a?a:r(t(/* @__PURE__ */ Error(`Invalid rule - did not return RuleResult`)))}catch(e){return r(t(e))}},C=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(n,r)=>{try{let i=await e(n,r);return typeof i==`boolean`?{status:`passed`,value:i}:{status:`failed`,error:t(/* @__PURE__ */ Error(`Predicate must return boolean, got ${typeof i}`))}}catch(e){return{status:`failed`,error:t(e)}}},w=(e,t)=>n=>async(r,i)=>{let a=await c(n,t)(r,i);try{await e(r,a,i)}catch(e){console.error(`Tap effect failed:`,e)}return a},T=(e,t,n,i)=>async(a,o)=>{let s=c(e,i),l=new Promise(e=>setTimeout(()=>e(r(n)),t));return Promise.race([s(a,o),l])},E=(e,t,n,a)=>async(o,s)=>{let c=await C(e,a?.predicateErrorTransform)(o,s);if(c.status===`failed`)return r(c.error);let[u,d]=l([t,n],a);return c.value?u(o,s):n?d(o,s):i()},D=e=>typeof e==`function`,O=(e,t,n,i)=>async(a,o)=>{let s=await e(a,o),l=t[s];return l?c(l,i)(a,o):n===void 0?r(`No matching rule for key: ${String(s)}`):D(n)?c(n,i)(a,o):r(n)},k=(e,t,n)=>async(a,o)=>(await c(e,n)(a,o)).status===`passed`?r(t):i(),A=(e,t)=>async(n,a)=>{let o=l(e,t),s=[];if(!e||e.length===0)return i();for(let e of o){let t=await e(n,a);if(t.status===`passed`)return i();s.push(t.error)}return r(s)},j=(e,t,n)=>async(a,o)=>{let s=c(t,n),l=await C(e,n?.predicateErrorTransform)(a,o);return l.status===`failed`?r(l.error):l.value?i():s(a,o)},M=(t,n,a)=>e(async(e,o)=>{let s=c(n,a),l=await C(t,a?.predicateErrorTransform)(e,o);return l.status===`failed`?r(l.error):l.value?s(e,o):i()},{kind:`branch`,test:t,ifTrue:n}),N=(e,t,n={})=>async(r,i)=>{let[a,o]=l([e,t],n),s=await a(r,i);return s.status===`failed`&&(!n.onlyFallbackOn||n.onlyFallbackOn(s.error))?o(r,i):s},P=(e,t={})=>p(e,t,`reverseFailFast`);function F(e,...t){return t.reduce((e,t)=>t(e),e)}const I=(t,n={})=>e(p(t,n,`forwardFailFast`),{kind:`sequence`,via:`pipeRules`,steps:[...t]}),L=(t,n,r)=>e(((...e)=>n(...e)),{kind:`rule`,label:t,...r?.params?{params:r.params}:{}});export{s as calculateDelay,P as composeRules,m as every,r as fail,c as getNormalizedRule,l as getNormalizedRules,n as hasContext,E as ifElse,h as inject,g as mapError,O as match,L as named,k as not,A as oneOf,i as pass,F as pipe,I as pipeRules,a as requireContextRule,_ as tap,t as toGraph,j as unless,v as validateField,M as when,y as withDebug,N as withFallback,o as withLazyContext,b as withMemoize,x as withRetry,S as withSafeError,C as withSafePredicate,w as withTap,T as withTimeout};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["hasContext","ctx","fail","pass","requireContextRule","check","contextCheck","context","rule","input","error","withLazyContext","loader","errorMessage","calculateDelay","strategies","initialDelayMs","attempt","strategy","\"fixed\"","strategyFn","getNormalizedRule","opts","withSafeError","getNormalizedRules","rules","clone","obj","e","shallowClone","getCloneFn","canUseStructuredClone","prepareRuleExecution","normalizedRules","options","cloneFn","shouldCloneContext","currentContext","policy","errors","result","rulesInOrder","every","inject","configuredRule","dependency","mapError","transform","tap","effect","validateField","value","getter","finalValue","defaultValue","safeRule","withDebug","config","startTime","ruleName","duration","withMemoize","cache","key","keyFn","now","entry","cached","oldestKey","withRetry","lastError","wasThrown","attempts","retryOn","shouldRetry","delayMs","delay","resolve","onExhausted","errorTransform","withSafePredicate","predicate","withTap","withTimeout","timeout","timeoutError","timeoutMs","ifElse","safePredicateResult","normalizedIfRule","normalizedElseRule","ifRule","elseRule","isRule","match","accessor","matchedRule","cases","defaultCase","not","oneOf","unless","normalizedRule","when","withFallback","mainSafeRule","fallbackSafeRule","mainRule","fallbackRule","composeRules","pipe","fns","fn","acc","pipeRules"],"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/composition/rule-execution.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/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-tap.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.ts","../src/lib/composition/pipe-rules.ts"],"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\ntype ExecutionPolicy =\n | \"forwardFailFast\"\n | \"reverseFailFast\"\n | \"parallelCollect\";\n\nexport function prepareRuleExecution<TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError>,\n policy: \"forwardFailFast\" | \"reverseFailFast\",\n): Rule<TInput, TError, TContext>;\nexport function prepareRuleExecution<TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError>,\n policy: \"parallelCollect\",\n): Rule<TInput, TError[], TContext>;\nexport function prepareRuleExecution<TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError>,\n policy: ExecutionPolicy,\n): Rule<TInput, TError | TError[], TContext> {\n const normalizedRules = getNormalizedRules([...rules], options);\n const cloneFn = getCloneFn(options);\n const shouldCloneContext = options.cloneContext;\n\n return async (input: TInput, context?: TContext) => {\n const currentContext = shouldCloneContext ? cloneFn(context) : context;\n\n if (policy === \"parallelCollect\") {\n const results = await Promise.all(\n normalizedRules.map((rule) => rule(input, currentContext)),\n );\n const errors = results.flatMap((result) =>\n result.status === \"failed\" ? [result.error] : [],\n );\n return errors.length > 0 ? fail(errors) : pass();\n }\n\n const rulesInOrder =\n policy === \"forwardFailFast\"\n ? normalizedRules\n : [...normalizedRules].reverse();\n\n for (const rule of rulesInOrder) {\n const result = await rule(input, currentContext);\n if (result.status === \"failed\") {\n return result;\n }\n }\n\n return pass();\n };\n}\n","import { prepareRuleExecution } from \"../../composition/rule-execution\";\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 once per composed invocation (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 prepareRuleExecution(rules, options, \"parallelCollect\");\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 * @template TContext - The type of the context object (optional, defaults to unknown)\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 * - The execution context is forwarded to the configured rule\n */\nexport const inject = <TInput, TError, TDep, TContext = unknown>(\n dependency: TDep,\n rule: (dep: TDep) => Rule<TInput, TError, TContext>,\n): Rule<TInput, TError, TContext> => {\n const configuredRule = rule(dependency);\n return (input, context) => configuredRule(input, context);\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 * @template TContext - The type of the context object (optional, defaults to unknown)\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 * - The context type of the wrapped rule is preserved and forwarded to it\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, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n transform: (error: TError) => TNewError,\n): Rule<TInput, TNewError, TContext> => {\n return async (input: TInput, context?: TContext) => {\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 { 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 and, optionally,\n * the context. Include every piece of context the verdict depends on (user,\n * tenant, permissions); otherwise one caller can be served another caller's result\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 *\n * // verdict depends on who is asking: key by context too\n * const perUser = withMemoize(\n * permissionRule,\n * (input, context) => JSON.stringify([context?.userId, input.id])\n * );\n * @caveats\n * - The cache key is exactly what `keyFn` returns: a key that ignores context\n * shares entries across contexts, so a result cached for one user can be served\n * to another. Key by context whenever the result depends on it\n * - Build keys unambiguously: joining values with a separator (`${a}:${b}`) can make\n * different callers produce the same key; serialize them (`JSON.stringify([a, b])`)\n * - Cache cleanup happens during rule execution\n * - Rejected promises are automatically evicted from cache\n * - Successful results obey TTL rules\n * - Each call to withMemoize creates its own cache; it is not shared across memoized rules\n * - Entries are evicted oldest-inserted first (FIFO) once maxSize is reached; hits do not refresh recency\n */\nexport const withMemoize = <TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n keyFn: (input: TInput, context?: TContext) => 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, context);\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 // Cache hit\n const cached = cache.get(key);\n if (cached) {\n return cached.result;\n }\n\n // Size management (FIFO): only a miss adds an entry, so only a miss evicts\n if (options.maxSize && cache.size >= options.maxSize) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey !== undefined) {\n cache.delete(oldestKey);\n }\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 RetryOn = \"failed\" | \"thrown\" | \"both\";\n\nexport type RetryStrategy =\n | \"fixed\"\n | \"linear\"\n | \"exponential\"\n | ((attempt: number) => number);\n\ntype WithRetryOptions<TError> = {\n attempts?: number;\n delayMs?: number;\n retryStrategy?: RetryStrategy;\n shouldRetry?: (error: TError | unknown, attempt: number) => boolean;\n retryOn?: RetryOn;\n};\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 * @param options.retryOn - What to retry: \"failed\" results, \"thrown\" exceptions, or \"both\" (default)\n * @param options.onExhausted - What to return when every attempt fails:\n * \"max-retries\" (default) returns \"MAX_RETRIES_EXCEEDED\"; \"last-error\"\n * returns the final error unchanged and keeps the error type as `TError`\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 * onExhausted: \"last-error\"\n * });\n * @caveats\n * - Retries both failed RuleResults and thrown exceptions by default\n * - A failed result is a deliberate decision, not a transient fault: do not retry\n * policy decisions. Use `retryOn: \"thrown\"` for guardrails and other rules\n * where a \"no\" must stay a \"no\"\n * - A failure excluded by `retryOn` is returned immediately (a thrown exception\n * becomes a failed result carrying the thrown value)\n * - `retryOn` and `shouldRetry` compose: an attempt is retried only if both allow it\n * - By default the final error is \"MAX_RETRIES_EXCEEDED\" if all attempts fail,\n * which hides why the rule failed; use `onExhausted: \"last-error\"` to keep it\n * - With \"last-error\" the final error may be a thrown value, as with `shouldRetry`\n */\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options: WithRetryOptions<TError> & { onExhausted: \"last-error\" },\n): Rule<TInput, TError, TContext>;\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options?: WithRetryOptions<TError> & { onExhausted?: \"max-retries\" },\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext>;\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options?: WithRetryOptions<TError> & {\n onExhausted?: \"max-retries\" | \"last-error\";\n },\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext>;\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options: WithRetryOptions<TError> & {\n onExhausted?: \"max-retries\" | \"last-error\";\n } = {},\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext> {\n const {\n attempts = 3,\n delayMs = 100,\n shouldRetry = () => true,\n retryOn = \"both\",\n onExhausted = \"max-retries\",\n } = options;\n\n return async (input, context) => {\n let lastError: TError | unknown;\n let wasThrown: boolean;\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 wasThrown = false;\n } catch (error) {\n lastError = error;\n wasThrown = true;\n }\n\n const kindAllowed =\n retryOn === \"both\" || retryOn === (wasThrown ? \"thrown\" : \"failed\");\n\n // Check if we should retry the last error\n if (!kindAllowed || !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 onExhausted === \"last-error\"\n ? fail(lastError as TError)\n : 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, PredicateResult, PredicateSafe } 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 { 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, 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 { fail, getNormalizedRule, pass } 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 * @template TContext - The type of the context object (optional, defaults to unknown)\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, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n error: TError,\n options?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\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, fallbackRule],\n options,\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 type { CompositionOptions, Rule } from \"../types\";\n\nimport { prepareRuleExecution } from \"./rule-execution\";\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 once per composed invocation (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<TError> = {},\n): Rule<TInput, TError, TContext> => {\n return prepareRuleExecution(rules, options, \"reverseFailFast\");\n};\n","// biome-ignore lint/suspicious/noExplicitAny: generic function arity\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","import type { CompositionOptions, Rule } from \"../types\";\n\nimport { prepareRuleExecution } from \"./rule-execution\";\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 once per composed invocation (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<TError> = {},\n): Rule<TInput, TError, TContext> => {\n return prepareRuleExecution(rules, options, \"forwardFailFast\");\n};\n"],"mappings":"AAUA,MAAaA,EAAiB,GACrBC,IAAQ,IAAA,GCEJC,EAAyB,IACnC,CAAE,OAAQ,SAAU,OAAM,GCFhBC,OACV,CAAE,OAAQ,QAAS,GCUTC,GAMX,EACA,EAIA,IACmC,CAKnC,IAAMC,EAAQC,IAJQ,GACbL,IAAQ,IAAA,IAKjB,OAAO,MAAO,EAAe,IACpBI,EAAME,CAAO,EAAIC,EAAKC,EAAOF,CAAO,EAAIL,EAAKQ,CAAK,CAE7D,ECzBaC,GACX,EACA,IAEO,KAAO,IAAkB,CAC9B,GAAI,CAEF,OAAOH,EAAKC,EAAO,MADGG,EAAOH,CAAK,CACR,CAC5B,OAASC,EAAO,CACd,IAAMG,EACJH,aAAiB,MAAQA,EAAM,QAAU,yBAC3C,OAAOR,EAAKW,CAAsB,CACpC,CACF,EC/BWC,GACX,EACA,EACA,IACW,CACX,IAAMC,EAA0D,CAC9D,UAAaC,EACb,OAAS,GAAYA,EAAiBC,EACtC,YAAc,GAAYD,EAAiB,IAAMC,EAAU,EAC7D,EAEA,GAAI,CAACC,EACH,OAAOH,EAAWI,MAASF,CAAO,EAIpC,GAAI,OAAOC,GAAa,SAAU,CAChC,IAAME,EAAaL,EAAWG,GAC9B,OAAOE,EAAaA,EAAWH,CAAO,EAAID,CAC5C,CAQA,OALI,OAAOE,GAAa,WACfA,EAASD,CAAO,EAIlBF,EAAWI,MAASF,CAAO,CACpC,EC3BaI,GACX,EACA,IAGEC,GAAM,oBAAsB,SACxBd,EACAe,EAAcf,EAAMc,GAAM,cAAc,ECPnCE,GACX,EACA,IAGEF,GAAM,oBAAsB,SACxBG,GACCA,GAAS,CAAC,EAAA,EAAI,IAAK,GAASF,EAAcf,EAAMc,GAAM,cAAc,CAAC,EC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EAAoB,KAAK,EAGhCA,EAAoB,MAAQc,EAAe7F,EAAOF,CAAO,EAAIJ,EAAK,CAC3E,ECxBWqG,GACX,EACA,EACA,EAEI,CAAC,IAEE,MAAO,EAAe,IAAuB,CAClD,GAAM,CAACC,EAAcC,GAAoBlF,EACvC,CAACmF,EAAUC,CAAY,EACvB1E,CACF,EACMM,EAAS,MAAMiE,EAAahG,EAAOF,CAAO,EAOhD,OALEiC,EAAO,SAAW,WACjB,CAACN,EAAQ,gBAAkBA,EAAQ,eAAeM,EAAO,KAAK,GAExDkE,EAAiBjG,EAAOF,CAAO,EAEjCiC,CACT,ECPWqE,GACX,EACA,EAAsC,CAAC,IAEhC7E,EAAqBP,EAAOS,EAAS,iBAAiB,EC+D/D,SAAgB4E,EAAK,EAAgB,GAAGC,EAA6B,CACnE,OAAOA,EAAI,QAAQ,EAAK,IAAOC,EAAGC,CAAG,EAAG9D,CAAK,CAC/C,CCxEA,MAAa+D,GACX,EACA,EAAsC,CAAC,IAEhClF,EAAqBP,EAAOS,EAAS,iBAAiB,E"}
1
+ {"version":3,"file":"index.js","names":["attachNode","hasContext","ctx","fail","pass","requireContextRule","check","contextCheck","context","rule","input","error","withLazyContext","loader","errorMessage","calculateDelay","strategies","initialDelayMs","attempt","strategy","\"fixed\"","strategyFn","getNormalizedRule","opts","withSafeError","getNormalizedRules","rules","clone","obj","e","shallowClone","getCloneFn","canUseStructuredClone","prepareRuleExecution","normalizedRules","options","cloneFn","shouldCloneContext","currentContext","policy","errors","result","rulesInOrder","every","inject","configuredRule","dependency","mapError","transform","tap","effect","validateField","value","getter","finalValue","defaultValue","safeRule","withDebug","config","startTime","ruleName","duration","withMemoize","cache","key","keyFn","now","entry","cached","oldestKey","withRetry","lastError","wasThrown","attempts","retryOn","shouldRetry","delayMs","delay","resolve","onExhausted","errorTransform","withSafePredicate","predicate","withTap","withTimeout","timeout","timeoutError","timeoutMs","ifElse","safePredicateResult","normalizedIfRule","normalizedElseRule","ifRule","elseRule","isRule","match","accessor","matchedRule","cases","defaultCase","not","oneOf","unless","normalizedRule","when","withFallback","mainSafeRule","fallbackSafeRule","mainRule","fallbackRule","composeRules","pipe","fns","fn","acc","pipeRules","named","args","name","toGraph"],"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/composition/rule-execution.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/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-tap.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.ts","../src/lib/composition/pipe-rules.ts","../src/lib/graph/named.ts"],"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\ntype ExecutionPolicy =\n | \"forwardFailFast\"\n | \"reverseFailFast\"\n | \"parallelCollect\";\n\nexport function prepareRuleExecution<TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError>,\n policy: \"forwardFailFast\" | \"reverseFailFast\",\n): Rule<TInput, TError, TContext>;\nexport function prepareRuleExecution<TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError>,\n policy: \"parallelCollect\",\n): Rule<TInput, TError[], TContext>;\nexport function prepareRuleExecution<TInput, TError, TContext>(\n rules: Rule<TInput, TError, TContext>[],\n options: CompositionOptions<TError>,\n policy: ExecutionPolicy,\n): Rule<TInput, TError | TError[], TContext> {\n const normalizedRules = getNormalizedRules([...rules], options);\n const cloneFn = getCloneFn(options);\n const shouldCloneContext = options.cloneContext;\n\n return async (input: TInput, context?: TContext) => {\n const currentContext = shouldCloneContext ? cloneFn(context) : context;\n\n if (policy === \"parallelCollect\") {\n const results = await Promise.all(\n normalizedRules.map((rule) => rule(input, currentContext)),\n );\n const errors = results.flatMap((result) =>\n result.status === \"failed\" ? [result.error] : [],\n );\n return errors.length > 0 ? fail(errors) : pass();\n }\n\n const rulesInOrder =\n policy === \"forwardFailFast\"\n ? normalizedRules\n : [...normalizedRules].reverse();\n\n for (const rule of rulesInOrder) {\n const result = await rule(input, currentContext);\n if (result.status === \"failed\") {\n return result;\n }\n }\n\n return pass();\n };\n}\n","import { prepareRuleExecution } from \"../../composition/rule-execution\";\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 once per composed invocation (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 prepareRuleExecution(rules, options, \"parallelCollect\");\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 * @template TContext - The type of the context object (optional, defaults to unknown)\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 * - The execution context is forwarded to the configured rule\n */\nexport const inject = <TInput, TError, TDep, TContext = unknown>(\n dependency: TDep,\n rule: (dep: TDep) => Rule<TInput, TError, TContext>,\n): Rule<TInput, TError, TContext> => {\n const configuredRule = rule(dependency);\n return (input, context) => configuredRule(input, context);\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 * @template TContext - The type of the context object (optional, defaults to unknown)\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 * - The context type of the wrapped rule is preserved and forwarded to it\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, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n transform: (error: TError) => TNewError,\n): Rule<TInput, TNewError, TContext> => {\n return async (input: TInput, context?: TContext) => {\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 { 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 and, optionally,\n * the context. Include every piece of context the verdict depends on (user,\n * tenant, permissions); otherwise one caller can be served another caller's result\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 *\n * // verdict depends on who is asking: key by context too\n * const perUser = withMemoize(\n * permissionRule,\n * (input, context) => JSON.stringify([context?.userId, input.id])\n * );\n * @caveats\n * - The cache key is exactly what `keyFn` returns: a key that ignores context\n * shares entries across contexts, so a result cached for one user can be served\n * to another. Key by context whenever the result depends on it\n * - Build keys unambiguously: joining values with a separator (`${a}:${b}`) can make\n * different callers produce the same key; serialize them (`JSON.stringify([a, b])`)\n * - Cache cleanup happens during rule execution\n * - Rejected promises are automatically evicted from cache\n * - Successful results obey TTL rules\n * - Each call to withMemoize creates its own cache; it is not shared across memoized rules\n * - Entries are evicted oldest-inserted first (FIFO) once maxSize is reached; hits do not refresh recency\n */\nexport const withMemoize = <TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n keyFn: (input: TInput, context?: TContext) => 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, context);\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 // Cache hit\n const cached = cache.get(key);\n if (cached) {\n return cached.result;\n }\n\n // Size management (FIFO): only a miss adds an entry, so only a miss evicts\n if (options.maxSize && cache.size >= options.maxSize) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey !== undefined) {\n cache.delete(oldestKey);\n }\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 RetryOn = \"failed\" | \"thrown\" | \"both\";\n\nexport type RetryStrategy =\n | \"fixed\"\n | \"linear\"\n | \"exponential\"\n | ((attempt: number) => number);\n\ntype WithRetryOptions<TError> = {\n attempts?: number;\n delayMs?: number;\n retryStrategy?: RetryStrategy;\n shouldRetry?: (error: TError | unknown, attempt: number) => boolean;\n retryOn?: RetryOn;\n};\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 * @param options.retryOn - What to retry: \"failed\" results, \"thrown\" exceptions, or \"both\" (default)\n * @param options.onExhausted - What to return when every attempt fails:\n * \"max-retries\" (default) returns \"MAX_RETRIES_EXCEEDED\"; \"last-error\"\n * returns the final error unchanged and keeps the error type as `TError`\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 * onExhausted: \"last-error\"\n * });\n * @caveats\n * - Retries both failed RuleResults and thrown exceptions by default\n * - A failed result is a deliberate decision, not a transient fault: do not retry\n * policy decisions. Use `retryOn: \"thrown\"` for guardrails and other rules\n * where a \"no\" must stay a \"no\"\n * - A failure excluded by `retryOn` is returned immediately (a thrown exception\n * becomes a failed result carrying the thrown value)\n * - `retryOn` and `shouldRetry` compose: an attempt is retried only if both allow it\n * - By default the final error is \"MAX_RETRIES_EXCEEDED\" if all attempts fail,\n * which hides why the rule failed; use `onExhausted: \"last-error\"` to keep it\n * - With \"last-error\" the final error may be a thrown value, as with `shouldRetry`\n */\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options: WithRetryOptions<TError> & { onExhausted: \"last-error\" },\n): Rule<TInput, TError, TContext>;\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options?: WithRetryOptions<TError> & { onExhausted?: \"max-retries\" },\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext>;\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options?: WithRetryOptions<TError> & {\n onExhausted?: \"max-retries\" | \"last-error\";\n },\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext>;\nexport function withRetry<TInput, TError = string, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n options: WithRetryOptions<TError> & {\n onExhausted?: \"max-retries\" | \"last-error\";\n } = {},\n): Rule<TInput, TError | \"MAX_RETRIES_EXCEEDED\", TContext> {\n const {\n attempts = 3,\n delayMs = 100,\n shouldRetry = () => true,\n retryOn = \"both\",\n onExhausted = \"max-retries\",\n } = options;\n\n return async (input, context) => {\n let lastError: TError | unknown;\n let wasThrown: boolean;\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 wasThrown = false;\n } catch (error) {\n lastError = error;\n wasThrown = true;\n }\n\n const kindAllowed =\n retryOn === \"both\" || retryOn === (wasThrown ? \"thrown\" : \"failed\");\n\n // Check if we should retry the last error\n if (!kindAllowed || !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 onExhausted === \"last-error\"\n ? fail(lastError as TError)\n : 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, PredicateResult, PredicateSafe } 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 { 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, 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 { fail, getNormalizedRule, pass } 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 * @template TContext - The type of the context object (optional, defaults to unknown)\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, TContext = unknown>(\n rule: Rule<TInput, TError, TContext>,\n error: TError,\n options?: RuleSafetyOptions<TError>,\n): Rule<TInput, TError, TContext> => {\n return async (input: TInput, context?: TContext) => {\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 { attachNode } from \"../../graph/node\";\nimport { 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 attachNode(\n 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\n ? normalizedRule(input, context)\n : pass();\n },\n { kind: \"branch\", test: predicate, ifTrue: rule },\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, fallbackRule],\n options,\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 type { CompositionOptions, Rule } from \"../types\";\n\nimport { prepareRuleExecution } from \"./rule-execution\";\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 once per composed invocation (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<TError> = {},\n): Rule<TInput, TError, TContext> => {\n return prepareRuleExecution(rules, options, \"reverseFailFast\");\n};\n","// biome-ignore lint/suspicious/noExplicitAny: generic function arity\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","import { attachNode } from \"../graph/node\";\nimport type { CompositionOptions, Rule } from \"../types\";\n\nimport { prepareRuleExecution } from \"./rule-execution\";\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 once per composed invocation (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<TError> = {},\n): Rule<TInput, TError, TContext> => {\n return attachNode(prepareRuleExecution(rules, options, \"forwardFailFast\"), {\n kind: \"sequence\",\n via: \"pipeRules\",\n steps: [...rules],\n });\n};\n","import { attachNode, type Fn } from \"./node\";\n\n/**\n * Gives a rule (or predicate, accessor or getter) a readable name for\n * `toGraph` and `toMermaid`. Behavior is unchanged: the returned function\n * forwards its arguments and result as-is, and the function you pass in is\n * not modified.\n *\n * @example\n * const adult = named(\"Is adult\", (user: User) => user.age >= 18);\n * const minAge = (years: number) =>\n * named(`Min age ${years}`, ageRule(years), { params: { years } });\n * @caveats\n * - A named rule is described as a single box, even if it was built from\n * combinators. Use that to collapse a sub-pipeline in a diagram.\n * - The wrapper adds one function call per invocation.\n */\nexport const named = <F extends Fn>(\n name: string,\n fn: F,\n options?: { params?: Record<string, unknown> },\n): F =>\n attachNode(((...args: never[]) => fn(...args)) as F, {\n kind: \"rule\",\n label: name,\n ...(options?.params ? { params: options.params } : {}),\n });\n"],"mappings":"A,6CAUA,MAAaC,EAAiB,GACrBC,IAAQ,IAAA,GCEJC,EAAyB,IACnC,CAAE,OAAQ,SAAU,OAAM,GCFhB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AACmF,EAAUC,CAAY,EACvB1E,CACF,EACMM,EAAS,MAAMiE,EAAahG,EAAOF,CAAO,EAOhD,OALEiC,EAAO,SAAW,WACjB,CAACN,EAAQ,gBAAkBA,EAAQ,eAAeM,EAAO,KAAK,GAExDkE,EAAiBjG,EAAOF,CAAO,EAEjCiC,CACT,ECPWqE,GACX,EACA,EAAsC,CAAC,IAEhC7E,EAAqBP,EAAOS,EAAS,iBAAiB,EC+D/D,SAAgB4E,EAAK,EAAgB,GAAGC,EAA6B,CACnE,OAAOA,EAAI,QAAQ,EAAK,IAAOC,EAAGC,CAAG,EAAG9D,CAAK,CAC/C,CCvEA,MAAa+D,GACX,EACA,EAAsC,CAAC,IAEhCnH,EAAWiC,EAAqBP,EAAOS,EAAS,iBAAiB,EAAG,CACzE,KAAM,WACN,IAAK,YACL,MAAO,CAAC,GAAGT,CAAK,CAClB,CAAC,EC1BU0F,GACX,EACA,EACA,IAEApH,IAAa,GAAGqH,IAAkBJ,EAAG,GAAGI,CAAI,GAAS,CACnD,KAAM,OACN,MAAOC,EACP,GAAInF,GAAS,OAAS,CAAE,OAAQA,EAAQ,MAAO,EAAI,CAAC,CACtD,CAAC,E"}
@@ -0,0 +1,3 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./to-graph-Dilv6lBr.cjs"),t=e=>e.replace(/[^A-Za-z0-9_]/g,`_`),n=e=>e.replace(/[^\p{L}\p{N} _.,:/-]/gu,e=>`#${e.codePointAt(0)};`),r=(e,t)=>` ${e}["${n(t)}"]`,i=e=>{let n=t(e.id);if(e.kind===`sequence`&&e.steps.length>0){let t=e.steps.map(i);return{nodes:t.flatMap(e=>e.nodes),edges:[...t.flatMap(e=>e.edges),...t.slice(1).map((e,n)=>` ${t[n].exit} --> ${e.entry}`)],entry:t[0].entry,exit:t[t.length-1].exit}}let a=e.kind===`rule`?e.label:e.kind;return{nodes:[r(n,a)],edges:[],entry:n,exit:n}},a=t=>{let n=i(e.t(t).root);return[`flowchart TD`,` input([input])`,...n.nodes,` passed([passed])`,` input --> ${n.entry}`,...n.edges,` ${n.exit} --> passed`].join(`
2
+ `)};exports.toMermaid=a;
3
+ //# sourceMappingURL=mermaid.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mermaid.cjs","names":["toGraph","require_to_graph","mermaidId","id","escapeLabel","label","char","box","render","node","parts","part","i","toMermaid","body","rule"],"sources":["../src/lib/mermaid/to-mermaid.ts"],"sourcesContent":["import type { GraphNode } from \"../graph/node\";\nimport { toGraph } from \"../graph/to-graph\";\nimport type { Rule } from \"../types\";\n\ntype Fragment = {\n nodes: string[];\n edges: string[];\n entry: string;\n exit: string;\n};\n\nconst mermaidId = (id: string) => id.replace(/[^A-Za-z0-9_]/g, \"_\");\n\n/**\n * Labels come from function names and `named()` strings, so they are\n * untrusted. Everything except letters, digits, spaces and a few plain\n * punctuation marks becomes a numeric entity (`#40;`). That covers quotes,\n * brackets, `%` (directives), `#`, `;` and every kind of line break, so a label\n * can never leave its quoted string or start a statement of its own.\n */\nconst escapeLabel = (label: string) =>\n label.replace(/[^\\p{L}\\p{N} _.,:/-]/gu, (char) => `#${char.codePointAt(0)};`);\n\nconst box = (id: string, label: string) => ` ${id}[\"${escapeLabel(label)}\"]`;\n\nconst render = (node: GraphNode): Fragment => {\n const id = mermaidId(node.id);\n\n if (node.kind === \"sequence\" && node.steps.length > 0) {\n const parts = node.steps.map(render);\n return {\n nodes: parts.flatMap((part) => part.nodes),\n edges: [\n ...parts.flatMap((part) => part.edges),\n ...parts\n .slice(1)\n .map((part, i) => ` ${parts[i].exit} --> ${part.entry}`),\n ],\n entry: parts[0].entry,\n exit: parts[parts.length - 1].exit,\n };\n }\n\n // Leaves and kinds the skeleton cannot draw yet render as a single box.\n const label = node.kind === \"rule\" ? node.label : node.kind;\n return { nodes: [box(id, label)], edges: [], entry: id, exit: id };\n};\n\n/**\n * Renders a rule as Mermaid flowchart source, without running it.\n *\n * Skeleton: draws leaf rules and `pipeRules` sequences only.\n *\n * @example\n * const text = toMermaid(pipeRules([hasItems, withinLimit]));\n */\nexport const toMermaid = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): string => {\n const body = render(toGraph(rule).root);\n return [\n \"flowchart TD\",\n \" input([input])\",\n ...body.nodes,\n \" passed([passed])\",\n ` input --> ${body.entry}`,\n ...body.edges,\n ` ${body.exit} --> passed`,\n ].join(\"\\n\");\n};\n"],"mappings":"A,8GAWME,EAAa,GAAeC,EAAG,QAAQ,iBAAkB,GAAG,EAS5DC,EAAe,GACnBC,EAAM,QAAQ,yBAA2B,GAAS,IAAIC,EAAK,YAAY,CAAC,EAAE,EAAE,EAExEC,GAAO,EAAY,IAAkB,KAAKJ,EAAG,IAAIC,EAAYC,CAAK,EAAE,IAEpEG,EAAU,GAA8B,CAC5C,IAAML,EAAKD,EAAUO,EAAK,EAAE,EAE5B,GAAIA,EAAK,OAAS,YAAcA,EAAK,MAAM,OAAS,EAAG,CACrD,IAAMC,EAAQD,EAAK,MAAM,IAAID,CAAM,EACnC,MAAO,CACL,MAAOE,EAAM,QAAS,GAASC,EAAK,KAAK,EACzC,MAAO,CACL,GAAGD,EAAM,QAAS,GAASC,EAAK,KAAK,EACrC,GAAGD,EACA,MAAM,CAAC,CAAC,CACR,KAAK,EAAM,IAAM,KAAKA,EAAME,EAAE,CAAC,KAAK,OAAOD,EAAK,OAAO,CAC5D,EACA,MAAOD,EAAM,EAAE,CAAC,MAChB,KAAMA,EAAMA,EAAM,OAAS,EAAE,CAAC,IAChC,CACF,CAGA,IAAML,EAAQI,EAAK,OAAS,OAASA,EAAK,MAAQA,EAAK,KACvD,MAAO,CAAE,MAAO,CAACF,EAAIJ,EAAIE,CAAK,CAAC,EAAG,MAAO,CAAC,EAAG,MAAOF,EAAI,KAAMA,CAAG,CACnE,EAUaU,EACX,GACW,CACX,IAAMC,EAAON,EAAOR,EAAAA,EAAQe,CAAI,CAAC,CAAC,IAAI,EACtC,MAAO,CACL,eACA,mBACA,GAAGD,EAAK,MACR,qBACA,eAAeA,EAAK,QACpB,GAAGA,EAAK,MACR,KAAKA,EAAK,KAAK,YACjB,CAAC,CAAC,KAAK;CAAI,CACb,E"}
@@ -0,0 +1,11 @@
1
+ import { t as Rule } from "./rule-C3RlYflY.cjs";
2
+ /**
3
+ * Renders a rule as Mermaid flowchart source, without running it.
4
+ *
5
+ * Skeleton: draws leaf rules and `pipeRules` sequences only.
6
+ *
7
+ * @example
8
+ * const text = toMermaid(pipeRules([hasItems, withinLimit]));
9
+ */
10
+ export declare const toMermaid: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>) => string;
11
+ //# sourceMappingURL=mermaid.d.cts.map
@@ -0,0 +1,11 @@
1
+ import { t as Rule } from "./rule-C3RlYflY.js";
2
+ /**
3
+ * Renders a rule as Mermaid flowchart source, without running it.
4
+ *
5
+ * Skeleton: draws leaf rules and `pipeRules` sequences only.
6
+ *
7
+ * @example
8
+ * const text = toMermaid(pipeRules([hasItems, withinLimit]));
9
+ */
10
+ export declare const toMermaid: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>) => string;
11
+ //# sourceMappingURL=mermaid.d.ts.map
@@ -0,0 +1,3 @@
1
+ import{t as e}from"./to-graph-Dd9xksGt.js";const t=e=>e.replace(/[^A-Za-z0-9_]/g,`_`),n=e=>e.replace(/[^\p{L}\p{N} _.,:/-]/gu,e=>`#${e.codePointAt(0)};`),r=(e,t)=>` ${e}["${n(t)}"]`,i=e=>{let n=t(e.id);if(e.kind===`sequence`&&e.steps.length>0){let t=e.steps.map(i);return{nodes:t.flatMap(e=>e.nodes),edges:[...t.flatMap(e=>e.edges),...t.slice(1).map((e,n)=>` ${t[n].exit} --> ${e.entry}`)],entry:t[0].entry,exit:t[t.length-1].exit}}let a=e.kind===`rule`?e.label:e.kind;return{nodes:[r(n,a)],edges:[],entry:n,exit:n}},a=t=>{let n=i(e(t).root);return[`flowchart TD`,` input([input])`,...n.nodes,` passed([passed])`,` input --> ${n.entry}`,...n.edges,` ${n.exit} --> passed`].join(`
2
+ `)};export{a as toMermaid};
3
+ //# sourceMappingURL=mermaid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mermaid.js","names":["toGraph","mermaidId","id","escapeLabel","label","char","box","render","node","parts","part","i","toMermaid","body","rule"],"sources":["../src/lib/mermaid/to-mermaid.ts"],"sourcesContent":["import type { GraphNode } from \"../graph/node\";\nimport { toGraph } from \"../graph/to-graph\";\nimport type { Rule } from \"../types\";\n\ntype Fragment = {\n nodes: string[];\n edges: string[];\n entry: string;\n exit: string;\n};\n\nconst mermaidId = (id: string) => id.replace(/[^A-Za-z0-9_]/g, \"_\");\n\n/**\n * Labels come from function names and `named()` strings, so they are\n * untrusted. Everything except letters, digits, spaces and a few plain\n * punctuation marks becomes a numeric entity (`#40;`). That covers quotes,\n * brackets, `%` (directives), `#`, `;` and every kind of line break, so a label\n * can never leave its quoted string or start a statement of its own.\n */\nconst escapeLabel = (label: string) =>\n label.replace(/[^\\p{L}\\p{N} _.,:/-]/gu, (char) => `#${char.codePointAt(0)};`);\n\nconst box = (id: string, label: string) => ` ${id}[\"${escapeLabel(label)}\"]`;\n\nconst render = (node: GraphNode): Fragment => {\n const id = mermaidId(node.id);\n\n if (node.kind === \"sequence\" && node.steps.length > 0) {\n const parts = node.steps.map(render);\n return {\n nodes: parts.flatMap((part) => part.nodes),\n edges: [\n ...parts.flatMap((part) => part.edges),\n ...parts\n .slice(1)\n .map((part, i) => ` ${parts[i].exit} --> ${part.entry}`),\n ],\n entry: parts[0].entry,\n exit: parts[parts.length - 1].exit,\n };\n }\n\n // Leaves and kinds the skeleton cannot draw yet render as a single box.\n const label = node.kind === \"rule\" ? node.label : node.kind;\n return { nodes: [box(id, label)], edges: [], entry: id, exit: id };\n};\n\n/**\n * Renders a rule as Mermaid flowchart source, without running it.\n *\n * Skeleton: draws leaf rules and `pipeRules` sequences only.\n *\n * @example\n * const text = toMermaid(pipeRules([hasItems, withinLimit]));\n */\nexport const toMermaid = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): string => {\n const body = render(toGraph(rule).root);\n return [\n \"flowchart TD\",\n \" input([input])\",\n ...body.nodes,\n \" passed([passed])\",\n ` input --> ${body.entry}`,\n ...body.edges,\n ` ${body.exit} --> passed`,\n ].join(\"\\n\");\n};\n"],"mappings":"A,2CAWA,MAAMC,EAAa,GAAeC,EAAG,QAAQ,iBAAkB,GAAG,EAS5DC,EAAe,GACnBC,EAAM,QAAQ,yBAA2B,GAAS,IAAIC,EAAK,YAAY,CAAC,EAAE,EAAE,EAExEC,GAAO,EAAY,IAAkB,KAAKJ,EAAG,IAAIC,EAAYC,CAAK,EAAE,IAEpEG,EAAU,GAA8B,CAC5C,IAAML,EAAKD,EAAUO,EAAK,EAAE,EAE5B,GAAIA,EAAK,OAAS,YAAcA,EAAK,MAAM,OAAS,EAAG,CACrD,IAAMC,EAAQD,EAAK,MAAM,IAAID,CAAM,EACnC,MAAO,CACL,MAAOE,EAAM,QAAS,GAASC,EAAK,KAAK,EACzC,MAAO,CACL,GAAGD,EAAM,QAAS,GAASC,EAAK,KAAK,EACrC,GAAGD,EACA,MAAM,CAAC,CAAC,CACR,KAAK,EAAM,IAAM,KAAKA,EAAME,EAAE,CAAC,KAAK,OAAOD,EAAK,OAAO,CAC5D,EACA,MAAOD,EAAM,EAAE,CAAC,MAChB,KAAMA,EAAMA,EAAM,OAAS,EAAE,CAAC,IAChC,CACF,CAGA,IAAML,EAAQI,EAAK,OAAS,OAASA,EAAK,MAAQA,EAAK,KACvD,MAAO,CAAE,MAAO,CAACF,EAAIJ,EAAIE,CAAK,CAAC,EAAG,MAAO,CAAC,EAAG,MAAOF,EAAI,KAAMA,CAAG,CACnE,EAUaU,EACX,GACW,CACX,IAAMC,EAAON,EAAOP,EAAQc,CAAI,CAAC,CAAC,IAAI,EACtC,MAAO,CACL,eACA,mBACA,GAAGD,EAAK,MACR,qBACA,eAAeA,EAAK,QACpB,GAAGA,EAAK,MACR,KAAKA,EAAK,KAAK,YACjB,CAAC,CAAC,KAAK;CAAI,CACb,E"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Represents the result of a rule evaluation.
3
+ * @template TError - The type of the error (defaults to string)
4
+ * @example
5
+ * // Passed result
6
+ * const passed: RuleResult = { status: "passed" };
7
+ *
8
+ * // Failed result
9
+ * const failed: RuleResult = {
10
+ * status: "failed",
11
+ * error: "Validation failed"
12
+ * };
13
+ */
14
+ type RuleResult<TError = string> = {
15
+ readonly status: "passed";
16
+ } | {
17
+ readonly status: "failed";
18
+ readonly error: TError;
19
+ };
20
+ /**
21
+ * A function that validates an input and returns a RuleResult.
22
+ * @template TInput - The type of the input to validate
23
+ * @template TError - The type of the error (defaults to string)
24
+ * @template TContext - The type of the context object (optional)
25
+ * @param input - The input value to validate
26
+ * @param context - Optional context object that can be used during validation
27
+ * @returns Either a Promise of RuleResult or RuleResult directly
28
+ * @example
29
+ * const isEven: Rule<number> = (input) => {
30
+ * return input % 2 === 0
31
+ * ? { status: "passed" }
32
+ * : { status: "failed", error: "Number must be even" };
33
+ * };
34
+ */
35
+ type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
36
+ export { RuleResult as n, Rule as t };
37
+ //# sourceMappingURL=rule-C3RlYflY.d.cts.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Represents the result of a rule evaluation.
3
+ * @template TError - The type of the error (defaults to string)
4
+ * @example
5
+ * // Passed result
6
+ * const passed: RuleResult = { status: "passed" };
7
+ *
8
+ * // Failed result
9
+ * const failed: RuleResult = {
10
+ * status: "failed",
11
+ * error: "Validation failed"
12
+ * };
13
+ */
14
+ type RuleResult<TError = string> = {
15
+ readonly status: "passed";
16
+ } | {
17
+ readonly status: "failed";
18
+ readonly error: TError;
19
+ };
20
+ /**
21
+ * A function that validates an input and returns a RuleResult.
22
+ * @template TInput - The type of the input to validate
23
+ * @template TError - The type of the error (defaults to string)
24
+ * @template TContext - The type of the context object (optional)
25
+ * @param input - The input value to validate
26
+ * @param context - Optional context object that can be used during validation
27
+ * @returns Either a Promise of RuleResult or RuleResult directly
28
+ * @example
29
+ * const isEven: Rule<number> = (input) => {
30
+ * return input % 2 === 0
31
+ * ? { status: "passed" }
32
+ * : { status: "failed", error: "Number must be even" };
33
+ * };
34
+ */
35
+ type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
36
+ export { RuleResult as n, Rule as t };
37
+ //# sourceMappingURL=rule-C3RlYflY.d.ts.map
@@ -0,0 +1,2 @@
1
+ const e=Symbol.for(`ts-rules-composer.node`),t=(t,n)=>(Object.defineProperty(t,e,{value:n,enumerable:!1,writable:!1,configurable:!0}),t),n=t=>typeof t==`function`&&Object.hasOwn(t,e)?t[e]:void 0,r=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},i=()=>{let e=0,t=(t,n)=>n??r(t)??`rule #${++e}`,i=(e,r)=>{let o=n(e);if(!o||o.kind===`rule`)return{id:r,kind:`rule`,label:t(e,o?.label),...o?.params?{params:o.params}:{}};switch(o.kind){case`sequence`:return{id:r,kind:`sequence`,via:o.via,steps:o.steps.map((e,t)=>i(e,`${r}.steps.${t}`))};case`branch`:return{id:r,kind:`branch`,test:t(o.test,a(o.test)),...o.ifTrue?{ifTrue:i(o.ifTrue,`${r}.ifTrue`)}:{},...o.ifFalse?{ifFalse:i(o.ifFalse,`${r}.ifFalse`)}:{}}}};return i},a=e=>{let t=n(e);return t?.kind===`rule`?t.label:void 0},o=e=>({version:1,root:i()(e,`root`)});export{t as n,o as t};
2
+ //# sourceMappingURL=to-graph-Dd9xksGt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"to-graph-Dd9xksGt.js","names":["NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","step","id","index","readLabel","toGraph","rule"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n const build = (fn: Fn, id: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label),\n ...(raw?.params ? { params: raw.params } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n }\n };\n\n return build;\n};\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAoEA,MAAaA,EAA0B,OAAO,IAC5C,wBACF,EASaC,GAA4B,EAAO,KAC9C,OAAO,eAAeC,EAAIF,EAAU,CAClC,MAAOG,EACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACMD,GAIIE,EAAY,GACvB,OAAOF,GAAO,YAAc,OAAO,OAAOA,EAAIF,CAAQ,EACjDE,EAAgBF,GACjB,IAAA,GCzFOK,EAAc,GAA6C,CACtE,GAAM,CAAE,QAASH,EACjB,OAAOI,IAAS,IAAMA,IAAS,aAAeA,EAAK,WAAW,QAAQ,EAClE,IAAA,GACAA,CACN,ECAMC,MAAsB,CAC1B,IAAIC,EAAa,EACXC,GAAW,EAAQ,IACvBC,GAAYL,EAAWH,CAAE,GAAK,SAAS,EAAEM,IAErCG,GAAS,EAAQ,IAA0B,CAC/C,IAAMC,EAAMR,EAASF,CAAE,EAGvB,GAAI,CAACU,GAAOA,EAAI,OAAS,OACvB,MAAO,CACL,KACA,KAAM,OACN,MAAOH,EAAQP,EAAIU,GAAK,KAAK,EAC7B,GAAIA,GAAK,OAAS,CAAE,OAAQA,EAAI,MAAO,EAAI,CAAC,CAC9C,EAGF,OAAQA,EAAI,KAAZ,CACE,IAAK,WACH,MAAO,CACL,KACA,KAAM,WACN,IAAKA,EAAI,IACT,MAAOA,EAAI,MAAM,KAAK,EAAM,IAC1BD,EAAME,EAAM,GAAGC,EAAG,SAASC,GAAO,CACpC,CACF,EACF,IAAK,SAEH,MAAO,CACL,KACA,KAAM,SACN,KAJWN,EAAQG,EAAI,KAAMI,EAAUJ,EAAI,IAAI,CAI5C,EACH,GAAIA,EAAI,OAAS,CAAE,OAAQD,EAAMC,EAAI,OAAQ,GAAGE,EAAG,QAAQ,CAAE,EAAI,CAAC,EAClE,GAAIF,EAAI,QACJ,CAAE,QAASD,EAAMC,EAAI,QAAS,GAAGE,EAAG,SAAS,CAAE,EAC/C,CAAC,CACP,CAEJ,CACF,EAEA,OAAOH,CACT,EAEMK,EAAa,GAAW,CAC5B,IAAMJ,EAAMR,EAASF,CAAE,EACvB,OAAOU,GAAK,OAAS,OAASA,EAAI,MAAQ,IAAA,EAC5C,EAeaK,EACX,IACe,CAAE,QAAS,EAAG,KAAMV,EAAc,CAAC,CAACW,EAAM,MAAM,CAAE,G"}
@@ -0,0 +1,2 @@
1
+ const e=Symbol.for(`ts-rules-composer.node`),t=(t,n)=>(Object.defineProperty(t,e,{value:n,enumerable:!1,writable:!1,configurable:!0}),t),n=t=>typeof t==`function`&&Object.hasOwn(t,e)?t[e]:void 0,r=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},i=()=>{let e=0,t=(t,n)=>n??r(t)??`rule #${++e}`,i=(e,r)=>{let o=n(e);if(!o||o.kind===`rule`)return{id:r,kind:`rule`,label:t(e,o?.label),...o?.params?{params:o.params}:{}};switch(o.kind){case`sequence`:return{id:r,kind:`sequence`,via:o.via,steps:o.steps.map((e,t)=>i(e,`${r}.steps.${t}`))};case`branch`:return{id:r,kind:`branch`,test:t(o.test,a(o.test)),...o.ifTrue?{ifTrue:i(o.ifTrue,`${r}.ifTrue`)}:{},...o.ifFalse?{ifFalse:i(o.ifFalse,`${r}.ifFalse`)}:{}}}};return i},a=e=>{let t=n(e);return t?.kind===`rule`?t.label:void 0},o=e=>({version:1,root:i()(e,`root`)});Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
+ //# sourceMappingURL=to-graph-Dilv6lBr.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"to-graph-Dilv6lBr.cjs","names":["NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","step","id","index","readLabel","toGraph","rule"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n const build = (fn: Fn, id: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label),\n ...(raw?.params ? { params: raw.params } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n }\n };\n\n return build;\n};\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAoEA,MAAaA,EAA0B,OAAO,IAC5C,wBACF,EASaC,GAA4B,EAAO,KAC9C,OAAO,eAAeC,EAAIF,EAAU,CAClC,MAAOG,EACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACMD,GAIIE,EAAY,GACvB,OAAOF,GAAO,YAAc,OAAO,OAAOA,EAAIF,CAAQ,EACjDE,EAAgBF,GACjB,IAAA,GCzFOK,EAAc,GAA6C,CACtE,GAAM,CAAE,QAASH,EACjB,OAAOI,IAAS,IAAMA,IAAS,aAAeA,EAAK,WAAW,QAAQ,EAClE,IAAA,GACAA,CACN,ECAMC,MAAsB,CAC1B,IAAIC,EAAa,EACXC,GAAW,EAAQ,IACvBC,GAAYL,EAAWH,CAAE,GAAK,SAAS,EAAEM,IAErCG,GAAS,EAAQ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