Introducing The Sweep: OX’s New Live Security Research Series
Register Now
Breaking: The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?
Read the Report
Are you exposed? Connect your apps in minutes.
Scan your apps free

ts-rules-composer

Latest version: v2.0.0

Overview

Last scanned
29 Nov 2026
Published
29 Nov 2026
npm package Publisher: brenopms
6 Stars
0 Forks
9 Versions
1.7K Downloads
TypeScript Repo language

Scan summary

ts-rules-composer was last scanned on 29 Nov 2026 at version 2.0.0. Risk score 0 of 100. No malicious behavior was detected.

  • Releases: 9 versions; the latest was published on 29 Nov 2026.
  • Findings: No rules fired in version 2.0.0.
  • Downloads: 1,692 downloads.

Versions

9 versions published
Versions and the rules that fired in each
VersionPublishedStatus
2.0.0 LATEST 29 Nov 2026 No rules fired
1.7.0 17 Nov 2026 No rules fired
1.5.0 13 Nov 2026 No rules fired
1.4.0 11 Nov 2026 Not shown
1.3.0 11 Nov 2026 Not shown

No rules fired in 2.0.0

Findings

Findings for v2.0.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.

The score describes 2.0.0; other versions have their own rules, not their own score.

README

The publisher’s own README, as collected from the registry.

TS Rules Composer

npm version bundle size license

A dependency-free, type-safe engine for composing business rules and policy checks into pipelines.

Why

Schema validators answer "is this data shaped correctly?". Business rules ask more: does this user have permission, is this order within their limit, did the fraud service say yes before the timeout? Those checks need shared context, async calls, branching, retries and timeouts.

ts-rules-composer treats each check as a small function (a rule) and gives you combinators to wire rules together, with the input, context and error types inferred end to end. It complements schema validators such as zod; it does not replace them.

Because a pipeline is plain data, you can also draw it: toMermaid turns the rules you actually ship into a flowchart, without running them. The diagram comes from the code, so it never goes stale.

Contents

  • Installation
  • Quick start
  • Features
  • Core concepts
  • Usage examples
  • Decisions
  • Diagrams
  • Error handling
  • Guardrails and policy checks
  • Context cloning
  • Best practices
  • Comparison to other libraries
  • API reference
  • Cheat sheet
  • Migrating from 1.x
  • Contributing

Installation

npm install ts-rules-composer
# or
yarn add ts-rules-composer
# or
pnpm add ts-rules-composer

Requires Node.js 22 or later, or a modern browser.

Quick start

import { fail, match, named, pass, pipeRules } from "ts-rules-composer";

type Order = { items: number; total: number; payment: "card" | "paypal" };
type Ctx = { limit: number };

// A rule is a function: (input, context?) => pass() | fail(error)
const hasItems = (order: Order) =>
  order.items > 0 ? pass() : fail("Cart is empty");

const withinLimit = (order: Order, ctx?: Ctx) =>
  order.total <= (ctx?.limit ?? 1000) ? pass() : fail("Over the spending limit");

const validateCard = (order: Order) =>
  order.total > 0 ? pass() : fail("Invalid amount");
const validatePaypal = (_order: Order) => pass();

// Combinators wire rules together; context reaches every rule
const validateCheckout = pipeRules<Order, string, Ctx>([
  hasItems,
  withinLimit,
  match(named("payment", (order: Order) => order.payment), {
    card: validateCard,
    paypal: validatePaypal,
  }),
]);

await validateCheckout({ items: 2, total: 40, payment: "card" }, { limit: 500 });
// → { outcome: "passed" }

await validateCheckout({ items: 0, total: 40, payment: "card" });
// → { outcome: "failed", error: "Cart is empty" }

await validateCheckout({ items: 1, total: 900, payment: "paypal" }, { limit: 500 });
// → { outcome: "failed", error: "Over the spending limit" }

pipeRules runs rules in order and stops at the first failure. See Core concepts for the model and the API reference for every combinator.

See it as a diagram

The same pipeline, drawn without running it:

import { toMermaid } from "ts-rules-composer/mermaid";

console.log(toMermaid(validateCheckout));
flowchart TD
  input([input])
  root_steps_0["hasItems"]
  root_steps_1["withinLimit"]
  root_steps_2{"payment"}
  root_steps_2_cases_0["validateCard"]
  root_steps_2_cases_1["validatePaypal"]
  passed([passed])
  input --> root_steps_0
  root_steps_2 -->|"card"| root_steps_2_cases_0
  root_steps_2 -->|"paypal"| root_steps_2_cases_1
  root_steps_0 --> root_steps_1
  root_steps_1 --> root_steps_2
  root_steps_2_cases_0 --> passed
  root_steps_2_cases_1 --> passed

Diagrams show the names the engine can find, which is why the match accessor above uses named("payment", ...). Unnamed functions print as rule #1. See Diagrams for options and naming tips.

Features

  • Composable: build pipelines from combinators such as when, unless, match, every and mapError
  • Decisions: pick one of several outcomes (approve, review, decline) with defineOutcomes, merged by precedence
  • Self-documenting: toMermaid turns any pipeline into a flowchart that always matches the code, without running it
  • Zero dependencies: small and tree-shakeable (sideEffects: false)
  • TypeScript first: inference for inputs, contexts and errors
  • Async ready: mix sync and async rules
  • Context-aware: share state, services and configuration across rules
  • Resilient: retries, timeouts, memoization and fallbacks built in
  • Extensible: write your own combinators with the same Rule type
  • Instrumented: withDebug and withTap for logging and metrics
  • Portable: Node.js 22+ and modern browsers

Core Concepts

The Rule

At the heart of ts-rules-composer lies the Rule — a function that performs a single validation step.

Rules are:

  • Minimal: they validate one thing only.
  • Composable: they can be combined using higher-order combinators.
  • Pure (ideally): they take an input and return a result, without mutating external state.
  • Async-compatible: all rules can be sync or async, and combinators handle both transparently.
  • Context-aware: optional context can be passed to any rule for dependency injection, configuration, or shared state.
Rule signature
type Rule<TInput, TError = string, TContext = unknown> =
  (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
  • TInput – the type of input the rule receives
  • TError – the type of error returned on failure (defaults to string)
  • TContext – optional shared context object passed to the rule
  • Result – your rule can return synchronously or asynchronously
Rule result

Rules must return one of two outcomes:

type RuleResult<TError = string> =
  | { outcome: "passed" }
  | { outcome: "failed"; error: TError };

Aggregating combinators change the error type: every and oneOf return a rule whose error is TError[] (one entry per failed rule), while pipeRules, composeRules and the rest keep a single TError.

Use the utility functions pass() and fail(error) to return results:

import { pass, fail } from 'ts-rules-composer';

const isEven = (n: number) =>
  n % 2 === 0 ? pass() : fail("Must be even");
Context example

Context is optional but powerful. It lets rules access external services, user configuration, or metadata.

type Ctx = { threshold: number };

const isAboveThreshold = (n: number, ctx?: Ctx) =>
  n > (ctx?.threshold ?? 0) ? pass() : fail("Below threshold");

When composing rules, context will be passed automatically to all child rules.

Composing rules

Rules are designed to be combined using combinators like pipeRules, every, oneOf, when, and match.

import { pipeRules } from 'ts-rules-composer';

const validate = pipeRules([
  isEven,
  isAboveThreshold
]);

const result = await validate(4, { threshold: 2 });
// → { outcome: "passed" }

const result2 = await validate(3, { threshold: 2 });
// → { outcome: "failed", error: "Must be even" }

Each rule is a unit of validation that plugs into powerful composition pipelines. You write simple rules and then combine them into expressive, testable flows using composable logic.

Usage Examples

Complete, type-checked examples (they are compiled by npm run typecheck):

  • User Registration
  • Financial Transaction Validation
  • Model Deployment Validator
Sketch: financial transaction pipeline

A sketch of how the combinators compose. Helper rules and services (fraudService, validateCardNumber, bankAuthCheck and so on) are assumed; see the linked file above for the runnable version.

import {
  pipeRules,
  match,
  withRetry,
  withMemoize,
  withTimeout,
  when
} from 'ts-rules-composer';

// 1. Basic validators
const validateAmount = (tx: Transaction) =>
  tx.amount > 0 ? pass() : fail("Amount must be positive");

const validateCurrency = (tx: Transaction) =>
  SUPPORTED_CURRENCIES.includes(tx.currency)
    ? pass()
    : fail(`Unsupported currency: ${tx.currency}`);

// 2. Memoized fraud check (cached for 5 minutes)
const checkFraudRisk = withMemoize(
  async (tx: Transaction) => {
    const risk = await fraudService.assess(tx);
    return risk.score < 5 ? pass() : fail("High fraud risk");
  },
  tx => JSON.stringify([tx.userId, tx.amount, tx.recipient]),
  { ttl: 300000 }
);

// 3. Payment method handling
const validatePaymentMethod = match(
  tx => tx.paymentType,
  {
    "credit_card": pipeRules([
      validateCardNumber,
      validateExpiry,
      withTimeout(bankAuthCheck, 3000, "Bank auth timeout")
    ]),
    "crypto": validateWalletAddress,
    "bank_transfer": validateIBAN
  }
);

// 4. Complete pipeline
const validateTransaction = pipeRules([
  validateAmount,
  validateCurrency,

  // Only run fraud check for transactions > $1000
  when(
    tx => tx.amount > 1000,
    withRetry(checkFraudRisk, { attempts: 2 })
  ),

  validatePaymentMethod,

  // Compliance check (different for business/personal)
  match(
    tx => tx.accountType,
    {
      "business": validateBusinessTransfer,
      "personal": validatePersonalTransfer
    }
  )
]);

// Usage
const result = await validateTransaction(paymentRequest);

Decisions

A rule answers yes or no: passed or failed. A decision picks one outcome from a set you declare, such as declined, review or approved. It is still a plain function, (input, context?) => { outcome }, sync or async.

Declare the outcomes
import { defineOutcomes, type OutcomeOf } from "ts-rules-composer";

const credit = defineOutcomes(["declined", "review", "approved"], {
  onError: "review",
});
type CreditOutcome = OutcomeOf<typeof credit>; // "declined" | "review" | "approved"

Declaration order is precedence: an earlier outcome outranks every later one. onError is the outcome any failure while deciding resolves to (see When something goes wrong). defineOutcomes returns a frozen toolkit bound to this set:

Member What it does
outcome(label) Builds a typed result for a decision you write yourself, like pass() / fail() for rules.
ifElse(predicate, whenTrue, whenFalse) Picks a branch from a yes/no question.
match(accessor, cases, defaultCase) Picks a branch by key. The default is required.
combine(decisions, { resolver? }) Runs decisions one at a time, in order, and merges their outcomes. Stops early (see Precedence).
combineAll(decisions, { resolver? }) Runs every decision at once and merges their outcomes.
mapOutcome(rule, { failed, passed? }) Turns a rule into a decision of this toolkit.
resolvers strongestWins (the default) and runEveryCheck, for the resolver option.
outcomes, onError The declared set, in order, and its onError.

A branch or case is either a declared outcome as a bare string ("review"), which ends the path there, or another decision. Labels are typo-checked against CreditOutcome. Each builder checks its arguments when you call it and throws a TypeError for bad configuration, never later while running.

Build a policy

A credit policy built from rules, branches and three external services: a sanctions lookup, then a credit bureau and a fraud service checked in parallel (sanctionsService, creditBureau and fraudService are assumed; the policy is tested as written in src/test/helpers/credit-policy.ts):

const SUPPORTED_COUNTRIES = ["US", "GB", "DE"];

const isAdult: Rule<CreditApplication> = named(
  "applicant is an adult",
  (app) => (app.age >= 18 ? pass() : fail("Applicant must be an adult")),
);

const isSupportedCountry: Rule<CreditApplication> = named(
  "country is supported",
  (app) =>
    SUPPORTED_COUNTRIES.includes(app.country)
      ? pass()
      : fail(`Unsupported country: ${app.country}`),
);

const isNotSanctioned: Rule<CreditApplication> = named(
  "applicant is not sanctioned",
  async (app) =>
    (await sanctionsService.isListed(app.applicantId))
      ? fail("Applicant is on a sanctions list")
      : pass(),
);

// A failed eligibility check declines. A check that throws is an outage,
// not a "no": it gives onError ("review").
const eligibility = credit.mapOutcome(
  pipeRules([isAdult, isSupportedCountry]),
  { failed: "declined" },
);

// This check declines a listed applicant and gives "review" for a
// sanctions-service outage.
const sanctions = credit.mapOutcome(isNotSanctioned, { failed: "declined" });

const debtToIncome = (app: CreditApplication) =>
  app.monthlyDebt / app.monthlyIncome;

const debtToIncomeAbove = (percent: number) =>
  named(
    `debt to income above ${percent}%`,
    (app: CreditApplication) => debtToIncome(app) > percent / 100,
  );

const affordability = credit.ifElse(
  debtToIncomeAbove(50),
  "declined",
  credit.ifElse(debtToIncomeAbove(35), "review", "approved"),
);

const employment = credit.match(
  named("employment", (app: CreditApplication) => app.employment),
  { employed: "approved", self_employed: "review", unemployed: "declined" },
  "review",
);

const bureauScore: Decision<CreditApplication, CreditOutcome> = named(
  "credit bureau score",
  async (app) => {
    const score = await creditBureau.score(app.applicantId);
    if (score >= 700) {
      return credit.outcome("approved");
    }
    if (score >= 600) {
      return credit.outcome("review");
    }
    return credit.outcome("declined");
  },
);

const fraudRisk: Decision<CreditApplication, CreditOutcome> = named(
  "fraud risk",
  async (app) => {
    const risk = await fraudService.riskScore(app);
    if (risk > 0.7) {
      return credit.outcome("declined");
    }
    if (risk > 0.3) {
      return credit.outcome("review");
    }
    return credit.outcome("approved");
  },
);

// A new account asking for a lot gets at least a review.
const newAccountLargeLoan = credit.ifElse(
  named(
    "new account asking over 20k",
    (app: CreditApplication) =>
      app.accountAgeDays < 90 && app.requestedAmount > 20_000,
  ),
  "review",
  "approved",
);

// Independent paid checks run in parallel.
const externalChecks = credit.combineAll([bureauScore, fraudRisk]);

// Sequential: the strongest outcome wins and the run stops at "declined", so
// an ineligible applicant never reaches the paid checks.
const creditPolicy = credit.combine([
  eligibility,
  sanctions,
  affordability,
  employment,
  newAccountLargeLoan,
  externalChecks,
]);
await creditPolicy(applicant); // { outcome: "approved" }
await creditPolicy({ ...applicant, employment: "self_employed" }); // { outcome: "review" }
await creditPolicy({ ...applicant, age: 16 }); // { outcome: "declined" }, no service called
Precedence and early stop

OX Radar and Response Center

Find threats in your stack.

OX Radar can check high-priority threats, like critical package CVEs, against your context.

Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.

Where it’s listed

The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).

  • npm ts-rules-composer

References

The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.

Powered by Read the latest findings

Scan your whole stack

Group 1261154050 1
Group 1261154050
 

From OX Research Newsroom

The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?
Vulnerability Insights

The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?

Copy of Template Design OX Blog (3)
Research

Ruby2Shell: Ruby Memory Corruption Flaws Expose Applications to Remote Code Execution, But is it an Actual Risk?

Cry2Wolf: How to Tell a Real Bug from a Nothingburger
AI & VibeSec

Cry2Wolf: Not Every Branded Bug Deserves a Fire Drill

Frame 2085668439 (1)
Group 1261154229