npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sincpro/criteria

v2.6.0

Published

The read grammar of the Sincpro engine in TypeScript: criteria, model definition, the in-memory engine that answers one, and readings that hold the cursor for you. No transport, no framework, no dependencies.

Readme

@sincpro/criteria

The read grammar of the Sincpro engine, in TypeScript, and the machinery that drives it. One object says what to bring — the filter, the ordering, the page, what to expand, how to group — and the answer says what the model is, so a client never carries a schema of its own.

No transport, no framework, no dependencies. Where the rows come from is one function you write; everything else is here.

npm install @sincpro/criteria

Quick start

import { criteria, pack, pageFrom, resource } from "@sincpro/criteria";

// The only thing that touches the outside world: one function.
const datasets = resource<Dataset>(async (q) =>
  pageFrom(await fetch(`/datasets?criteria=${pack(q)}`).then((r) => r.json())),
);

const reading = datasets.read(
  criteria<Dataset>()
    .selection(["encoding", "=", "utf-8"], ["row_count", ">", 1000])
    .order("-registered_at")
    .limit(100),
);

await reading.load();
await reading.more(); // infinite scroll — the cursor never appears in your code

reading.rows;
reading.count; // {value: 197, exact: true}
reading.meta; // what may be filtered, ordered and grouped
reading.dropped; // what the model could not answer, and why
reading.hasMore;

Rows already in hand are a source too, with nothing to write:

import { fromRows, resource } from "@sincpro/criteria";

const datasets = resource(fromRows(rows)); // filter, sort, page, group and pivot, in memory

What this knows

A filter that reads left to right

A condition is written as a triple — field, operator, value — and nothing is imported to write one. The editor offers the fields at the first position and the operators at the second, and a typo is a compile error naming the field you meant.

import { selection } from "@sincpro/criteria";

.selection(
  ["encoding", "=", "utf-8"],
  ["row_count", ">", 1000],
  selection.any(["tags", "contains", "raw"], ["producer_id", "is null", true]),
  selection.negate(["name", "like", "draft"]),
)

Arguments are ANDed. Structure is three functions under one name — selection.all, selection.any, selection.negate — and they are functions because they hold the rule about what is empty: an any with no parts matches nothing and an all with no parts matches everything, so a row of chips that are all switched off has to disappear rather than turn into its opposite.

The operators are the symbols the model definition publishes in ops, so what a filter widget reads and what you write are the same vocabulary — there is no table translating gt to > anywhere.

Text is searched two ways, both ignoring case and accents: like contains the value anywhere, and starts with is a prefix — ["code", "starts with", "1.2.3"] finds 1.2.30, not 1.2.1.2.3, and ["name", "like", "impresion"] finds Impresión. In either, % and _ are the text itself, never wildcards: 50% finds Descuento 50% off and nothing that merely starts with 50. fold (from @sincpro/criteria/engine) is that reading of a text, for a platform that stores a key to search by.

A filter crosses a relation with {through, selection}: it holds when some record the relation holds — several, one or none — answers the selection, written over that record's own fields. A sale with a line of more than ten units:

criteria<Sale>().selection({
  through: "lines",
  selection: { field: "qty", operator: ">", value: 10 },
});

The server crosses it with a correlated EXISTS; matches and filtered answer it over the records in hand. A relation the definition does not mark navigable is dropped (not_navigable), as the server does.

The triple never travels. It is read into {field, operator, value} before it leaves, so the wire and a saved reading keep saying the same thing. q.value is that plain object; it goes in a URL, a POST body or a queue message unchanged.

A value that is read when the filter runs

Some questions are not about a fixed value: «due before today», «mine», «the last 30 days». A condition's value can be a dynamic value, stored as itself and read by the server when the filter runs — so a saved reading that says today means the day it is opened, and a client can never say it is another user.

import { criteria, dynamic } from "@sincpro/criteria";

criteria<Invoice>().selection(
  ["due", "<", dynamic.today()],
  ["owner_id", "=", dynamic.context("user_id")],
  ["posted_at", ">=", dynamic.today({ minus: { days: 30 }, startOf: "month" })],
  ["closed_at", "between", dynamic.period("this_month")],
  ["closed_at", "between", dynamic.period({ unit: "day", last: 30 })],
  ["total", ">", dynamic.field<Invoice>("credit_limit")],
);

dynamic.* computes nothing: each returns the object that travels — {"$": "today", "plus": {"days": -30}} — and the server resolves it with its own clock, its own timezone and its own context. minus and startOf are only a way of writing: the wire has the one signed plus and start_of. A name the engine does not have ("this_mont", a unit day where a span counts in days) is a compile error.

| dynamic. | Reads | | -------------- | ---------------------------------------------------------------------------------- | | today() | the current date, in the timezone of the server's context (UTC without one) | | now() | the current instant, in UTC | | context(key) | a key of the SERVER's own context — the user, the tenant, a date it holds | | param(name) | a value the caller supplied for this call (name may be a path with dots) | | period(…) | a range [start, end): a name (this_month) or {unit, last \| next}; between | | field(name) | another field of the same row: a column against a column |

Dates move with plus and then snap with start_of (day, week, month, quarter, year): a month end clamps (31 January plus a month is 28 February), a day across a clock change is still a day, and everything is UTC except where a calendar boundary falls. A period is closed at its start and open at its end, and last/next leave the current unit out unless includeCurrent.

Rows in hand are narrowed the same way: filtered(rows, filter, meta, { now }) reads each dynamic value once, with the instant it is given — and resolve(filter, { now, timeZone, context }) is the step on its own, for what a form hint or a test needs. What a client resolves stays on the client. meta.resolvers lists what the server reads, so a filter builder offers «Today» and «This month» from what the backend says. What every value reads to is held to tests/criteria-resolution.json, written by hand in the framework, so both engines agree.

The law for merging two of them

A saved reading, what the user typed and what a permission imposes are three criteria over the same rows. merge is total, so they never disagree quietly:

| Part | Law | | --------------------------------- | ------------------------------------------------------------------------------------- | | selection | AND — both restrictions hold | | specification | intersection — a mask can only take away, which is what makes it safe as a permission | | order, pagination, grouping | the more specific one replaces | | count | the more specific one replaces, and silence never overrules one that was asked for | | the cursor | never carried over — it belongs to one ordering over one filter |

A permission the server hands out, and a filter the user typed, in the shape they actually take — selection.any/selection.negate included — merged into the one criteria that goes out:

// The server's rule — the user never sees or edits this.
const permission = criteria<Account>().selection(
  selection.any(["region", "=", "north"], ["owner", "=", currentUser]),
);

// What the user typed into a search box.
const typed = criteria<Account>().selection(
  ["kind", "=", "asset"],
  selection.negate(["region", "=", "south"]),
);

const asked = merge(plain(permission), plain(typed));
// { selection: { all: [
//   { any: [{ field: "region", operator: "=", value: "north" }, { field: "owner", operator: "=", value: "ana" }] },
//   { field: "kind", operator: "=", value: "asset" },
//   { negate: { field: "region", operator: "=", value: "south" } },
// ] } }

asked is what actually goes to read() — the user's filter narrows the permission, it can never widen past it, because merge's law for selection is always AND.

What the model says about itself

The model is described once: the bounded context publishes it as a contract — JSON Schema with the framework's vocabulary under x-sincpro — in the discovery document its wire serves (OpenAPI's components.schemas, OpenRPC's, MCP's, or the file export_metamodel writes). metaFromContract reads it into the definition everything here takes; hand it to the source and every page carries it, while each answer says only which version of the model it is (model_version, compared with versionOf(contract) — another one means: load the document again). A filter form, a column menu and a search box are built from it, so a client can never ask for a field it was not shown:

const document = await (await fetch("/openapi.json")).json();
const meta = metaFromContract(document.components.schemas.Dataset);
const datasets = resource<Dataset>(restSource("/datasets", { meta }));
fieldsThatFilter(meta); // what a filter may name
fieldsThatSort(meta); // never a list; a nullable column orders NULL first, then last descending
operatorsFor(meta, "row_count"); // ["=", "!=", "<", "<=", ">", ">=", "between", "in", "not in"]
labelOf(meta, "row_count", "es"); // "Filas"
choicesOf(meta, "priority", "es"); // [{value: "high", label: "Alta"}, …] — a select over an enum
choiceLabelOf(meta, "priority", "high", "es"); // "Alta"; the value itself when the enum named it nothing
searchOver(meta, typed); // the entity's own search template, else `like` over every text field
matching(meta, typed); // what a many2one select sends: the template, 8 references

meta.search is the entity's DEFAULT_LITERAL_SEARCH: a criteria whose selection holds dynamic.param("text") where the typed text goes. searchOver and matching fill it exactly as the engine's own matching does, so a select finds what the backend's select would: word by word, each word in some field the template searches — factura 2026 finds the record holding factura in one field and 2026 in another, and a code such as T-1 stays one word.

When the rows came from somewhere that says nothing about them, describeRows(rows) reads a definition off the rows themselves.

What the engine would answer, checked before sending

const { criteria: checked, dropped, refused } = validate(q, meta);
  • dropped — the condition disappears and the read still runs. An unknown field, an operator a type does not take, a value that will not read. A dropped filter always widens the result, so saying it out loud is enough — and a shared link outlives the schema it was written against.
  • refused — the whole request would fail: ordering by a field that has no order to page by (a list, a translation, a relation). A menu can grey the entry out instead of finding out later. A nullable column is not refused: NULL comes first ascending and last descending, where the server's ORDER BY puts it, so a cursor minted on either side reads on the other.

The read itself, over rows in hand

matches(row, filter) and filtered(rows, filter) answer the same filter over rows already in hand, and agree with SQL including where SQL is odd: NULL compares to nothing, two lists are compared by their members. The rest of the machine — sorting, keyset cursors, folds, pivots — is @sincpro/criteria/engine, and a token minted there can be read by the server.

Where rows come from

The whole seam between this package and the outside world is one function:

interface Source<T> {
  read(criteria: Criteria<T>, signal?: AbortSignal): Awaitable<Page<T>>;
  group?(criteria: Criteria<T>, signal?: AbortSignal): Awaitable<Page<Bucket<T>>>;
  pivot?(criteria: Criteria<T>, axes: Axes<T>, signal?: AbortSignal): Awaitable<Pivot>;
}

A source that only reads is written as the bare function: resource(async (q) => …).

pageFrom(answer) turns whatever the server sent into the Page everything else reads, so a REST adapter is one line and a JSON-RPC one is another; groupsFrom(answer) reads a grouped answer's groups, by their name. group and pivot are optional: a source without them says so, and resource(source, { groupLocally: true }) will read the matching rows and group them here instead — opt-in, because a screen that quietly downloads a table is worse than one that says the source cannot group.

@sincpro/criteria/rest writes that one line for the common case — GET {baseUrl}?criteria=…. group() reuses that same URL by default: the criteria's own grouping is what asks for it, not a path this package would otherwise have to guess. Pass groupUrl only when a backend genuinely answers grouping at a different endpoint (some do — that is the backend's routing choice to declare, never this package's to assume):

import { restSource } from "@sincpro/criteria/rest";

const datasets = resource<Dataset>(
  restSource("/datasets", {
    headers: () => ({ Authorization: `Bearer ${token()}` }),
    // groupUrl: "/datasets/groups",  // only if that backend actually routes it separately
  }),
);

A non-2xx answer throws RestError with the status, the body and problem — the engine's failure read into one shape (kind, reason, next_step, retryable, retry_after, and errors as JSON pointers), the same one RpcError.problem carries, so a screen handles a refusal once whichever wire it came over. readProblem(body) reads one from any body. There is no pivot: no endpoint anywhere follows a convention for one yet.

A page may come in another format than JSON — a search of millions answers Parquet to a client that reads it. decode is the seam: it decides by the response's headers, answers the envelope JSON would have sent, or undefined to leave the body to JSON. This package knows no format but JSON; @sincpro/client-framework plugs its Parquet decoder here.

restSource("/entries", { decode: (response, signal) => myDecoder(response, signal) });

@sincpro/criteria/rpc does the same over the framework's own JSON-RPC 2.0 entrypoint — every read Query there carries one field, criteria, so a method call is {criteria: plain(...)} in params, no packing needed (there is no URL length to save):

import { rpcSource } from "@sincpro/criteria/rpc";

const datasets = resource<Dataset>(
  rpcSource("/rpc", {
    read: "catalog.query.ListDatasets",
    group: "catalog.query.GroupDatasets",
  }),
);

A transport failure or a JSON-RPC error in the envelope both throw RpcError, carrying the JSON-RPC error object (code, message, data). The method names are application-specific — {instance}.{layer}.{dto_name} — so this asks for them rather than guessing.

selection.any/selection.negate, a saved reading, a permission merged with what the user typed — none of it is transport-specific. Both restSource and rpcSource send whatever Criteria<T> they are handed through pack/plain; the criteria from "The law for merging two of them" above travels identically whether read() ends up calling restSource or rpcSource — the addon does not know or care how the selection tree is shaped.

A reading

The rules that are easy to get wrong live in one place:

  • the definition is asked for on the first page and not on the rest;
  • an answer that arrives after a newer one was asked for is dropped — the race every search box loses — and the request in flight is aborted;
  • refining drops the cursor, because it belongs to one ordering over one filter;
  • a first page resumed from a cursor the server refuses is read again from the beginning, since a criteria that came back from a URL outlives the ordering it was written under;
  • dropped is a warning, never a failure.
const reading = datasets.read(base);
await reading.load();
await reading.more();
await reading.refine(base.selection(searchOver(reading.meta!, typed)));
await reading.reload();

reading.subscribe(() => render()); // headless: React, Vue, Svelte, or nothing
reading.snapshot(); // the same object until something changes

When a source answers live — a channel that says "this may be stale", never rows, see docs/DESIGN.md at the repo root for why — a reading can keep itself current:

const stop = reading.follow(); // reloads on invalidation, debounced
// later
stop(); // closes the channel

follow() throws when the source has no live: there is nothing to invalidate the reading.

To walk everything, no cursor appears at all:

for await (const dataset of datasets.all(
  criteria<Dataset>().selection(["encoding", "=", "utf-8"]),
)) {
  // one page at a time, under the hood
}

Grouping

Five verbs, and each one says which of the two things it is about — the rows, or the groups the rows made:

| Verb | What it is about | | ------------------------------------------- | ------------------------------------------------------------------ | | .order(…), .limit(n) | the ROWS; grouping, they decide which rows each bucket shows first | | .groupBy(…) | how the set is split, one level at a time | | .measures({ name: measure.sum("field") }) | the numbers every bucket answers, each under a name of yours | | .whereMeasures(…) | filters the GROUPS by those numbers, plus count | | .orderGroups(…), .limitGroups(n) | the order and the page of the GROUPS |

The measures are a closed list, because the name reaches SQL: anything outside it is refused before a statement exists.

| | | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | measure.sum avg min max | over the values that are there; an empty one is left out, not counted as zero | | measure.count(field) | how many rows hold a value in it — every bucket answers count for its rows without being asked | | measure.countDistinct(field) | how many DIFFERENT values — "how many customers", not how many rows | | measure.percentile(field, 0.95) · measure.median(field) | the value at a fraction of the sorted ones, interpolating; a median is the 0.5 one and takes no argument. Not every engine computes it: SQLite has none, and the repository refuses it by name instead of letting it reach the database | | measure.boolAnd(field) · measure.boolOr(field) | whether every / any row of the group holds true; a boolean field only |

What is open is where the rows come from, what each model publishes it can be asked, and everything worked out from the answer — see below.

One statement per level, and every bucket carries the criteria that opens it — no client rebuilds a filter it did not write:

const tree = datasets.group(
  criteria<Dataset>()
    .groupBy("encoding")
    .measures({ rows: measure.sum("row_count") })
    .whereMeasures(["count", ">", 10]),
);
await tree.load();

const rows = tree.open(tree.buckets[0]); // the bucket's rows, as a reading
const months = tree.drill(tree.buckets[0], ["registered_at", "month"]);

A grained level is labelled the way the engine labels it — "2026-01" — and opens on a range, because the rows hold instants and the label holds a month. With an explicit page on the criteria, every bucket also carries the ids and cursor of its own first page.

pivot crosses two axes and folds the cells, with margins folded from the rows rather than added up from the cells: an average of averages is not an average.

The part of a date, and the groups with no rows

A grain CUTS a date into ranges (["registered_at", "month"] is 2026-03); a part extracts a number from it, so every March groups together whatever the year:

criteria<Dataset>().groupBy({ field: "registered_at", part: "month" }); // 1 … 12

part is year, quarter, month, iso_week, day_of_week (Monday is 1), day_of_month or hour, always in UTC. A level takes a grain or a part, not both. A group of a part cannot be opened: «every March» is not a condition on the date, so its bucket says openable: false and carries its parent's criteria, and asking for a page of ids per group over one is refused.

A group that happens to be empty is absent from a grouping, and a chart with a hole in its axis lies. fill: true lists every value the level can take, with a count of 0:

criteria<Bill>().groupBy({ field: "state", fill: true }); // every choice of the enum
criteria<Bill>().groupBy({ field: "registered_at", part: "month", fill: true }); // 1 … 12

It fills the choices of an enum, both values of a boolean, every number of a part, and the grains of a date range that the filter bounds at both ends — an axis with no ends has no «every». An empty group's count is 0, its counts are 0 and every other fold is null. It cannot be combined with whereMeasures or a page of groups. meta.fields[x].groupable and .aggregates say what a field takes, and computed marks a field the server computes — read-only, and grouped and filtered like a column.

The two orders and the two pages

A criteria carries two of each, and the nesting says which is which:

| | the rows | the groups | | ------------- | ------------------------------- | ----------------------- | | how many | .limit(n) | .limitGroups(n) | | from where | .cursor(token) · .offset(n) | .offsetGroups(n) | | in what order | .order("-registered_at") | .orderGroups("-rows") |

Grouping, the rows' order and page decide which rows each bucket of the deepest level shows first — its ids and its own cursor; a bucket above another shows the groups below it, not rows. The groups have no cursor on purpose: a cursor names a row, and a group is a number over many rows, so ordering by a measure leaves nothing to resume past.

The page of groups cuts the first level only: the levels below come whole for the groups on it, and a level below is paged by opening a group — bucket.criteria grouped by that level, where it is the first. The answer says how many groups the first level makes in all (groupsCount, groups_count on the wire), which is what «more groups» is offered by. .orderGroups takes a level, a measure or count — anything else is refused — and a level's field orders that level only; whatever is left tied falls by the groups' own value, so a page of groups is the same page every time.

A saved reading

A criteria is a value, so saving what somebody filtered and grouped is saving one thing:

localStorage.setItem("my-reading", pack(forSaving(reading.criteria)));

const saved = unpack(localStorage.getItem("my-reading")!);

await datasets.page(saved); // run it
criteria<Dataset>(saved).selection(["row_count", ">", 1000]); // go on building over it
merge(saved, whatTheScreenAlwaysAdds); // cross it, under the law
conditionsOf(saved.selection).map((one) => explainFilter(one, { meta })); // draw its chips

forSaving drops the cursor: it names a row under one ordering over one filter and does not outlive either, so it has no business in something that is kept.

What is worked out from the answer

A measure is computed by whoever answered the reading. A derived number is not a measure: it is arithmetic over the groups already in hand, and it needs no engine, no round trip and no permission. That is @sincpro/criteria/analysis, and unlike the measures it is open:

import {
  asSeries,
  cumulative,
  derive,
  fillGaps,
  percentOfTotal,
} from "@sincpro/criteria/analysis";

const shown = derive(tree.buckets, {
  share: percentOfTotal("total"),
  running: cumulative("total"),
  margin: (bucket) => Number(bucket.measures?.income) - Number(bucket.measures?.cost),
});

For a chart, the groups already are its shape — the bucket values are the categories and the measures are the series:

asSeries(byMonth, { measures: ["total"] });
// {categories: ["2026-01", "2026-02"], series: [{name: "total", values: [65000, 30000]}]}

asStackedSeries(byRegionThenRep, { measure: "total" }); // one series per inner group
asTable(pivot); // the pivot as a rectangle: every crossing present, margins and grand total

And a month that answered nothing is not a group, it is an absence — only the caller knows the range it asked about, so only the caller can put it back:

fillGaps(byMonth, { grain: "month", from, to }); // the empty months, with count 0

Nothing here imports a chart library: what comes out is plain data that ECharts, Recharts, Vega or a <table> all take.

Reading it out loud

explain(q, { meta, locale: "es" });
// 'Conjuntos, where Codificación = "utf-8" and Filas > 1000, by Registrado ↓, 100 per page'

A read that can be printed is a read that can be logged, diffed in a test, shown in a "what am I looking at" bar, and understood by an agent that did not build it.

Typing is opt-in

criteria() asks nothing of a caller that has no generated type yet: field names are plain strings. criteria<Dataset>() checks every field name in the filter, the ordering, the grouping levels and the mask — and having offers the numbers this very criteria folds, because the builder remembers what measures declared:

criteria<Dataset>()
  .groupBy("encoding")
  .measures({ rows: measure.sum("row_count") })
  .whereMeasures(["rows", ">", 1000]) // "rows" and "count" are offered; anything else is an error
  .orderGroups("-rows");

The two mix freely — a resource over Dataset takes a typed criteria and an untyped one alike, which is what makes a saved reading easy to pick back up.

Development

make init           # install
make test           # node --test over the TypeScript sources
make typecheck      # tsc --noEmit, which also checks the @ts-expect-error contract in tests
make verify-format  # eslint --fix + prettier + doctor, and fails if anything changed
make doctor         # the traps tsc does not catch — see docs/GOTCHAS.md
make build          # dist/ (JS + .d.ts)

License

MIT © Sincpro SRL