Filters
A typed, end-to-end filtering system: one model spans frontend ↔ API ↔ any
query builder. Built like pagination — a portable core
lowers a request into a driver-agnostic AST, and thin per-driver adapters
render it (Drizzle, Kysely, Knex, Bun.sql / postgres.js, Mongo, Prisma,
PostgREST/Supabase, Elasticsearch/OpenSearch, in memory, or your own).
- The core (
@xtandard/lib/filters) is validation-library-free and driver-free: plain TS types +compileFilters. - Validation is optional and pluggable: ready-made schemas for valibot,
Zod, ArkType, and Effect (
@xtandard/lib/filters/{valibot,zod,arktype,effect}), or bring any Standard-Schema validator and target the same shape. - The
datekind is injected (no date library is bundled).
npm install @xtandard/lib# + whichever adapter peer you use: drizzle-orm | kysely | (knex/sql-tag/mongo/prisma/postgrest/elasticsearch need no peer)# + valibot for the optional ready-made schemasHow a request travels from the client to the database:
flowchart LR
REQ["Untrusted JSON<br/>(body or URL)"] -->|"schema parse"| MODEL["ColumnFilter[] or FilterNode"]
MODEL --> COMPILE["compileFilters / compileFilterNode<br/>(each adapter calls it for you)"]
SPEC["spec: field → kind allow-list"] --> COMPILE
RD["resolveDate (injected)"] -.-> COMPILE
COMPILE --> AST["CompiledWhere AST"]
AST --> DRZ["drizzle: SQL"]
AST --> RQB["drizzle-rqb: where object"]
AST --> KYS["kysely: RawBuilder"]
AST --> KNX["knex: { sql, bindings }"]
AST --> TAG["sql-tag: Bun.sql / postgres.js fragment"]
AST --> MGO["mongo: filter object"]
AST --> PRS["prisma: where object"]
AST --> PGR["postgrest: query params"]
AST --> ES["elasticsearch: Query DSL"]
Quick start
Section titled “Quick start”import * as v from "valibot";import { FiltersRequestSchema } from "@xtandard/lib/filters/valibot";import { buildWhere, textField, numberField, dateField } from "@xtandard/lib/filters/drizzle";
// 1. validate the untrusted request (any validator works — here, the ready-made schema)const filters = v.parse(FiltersRequestSchema, [ { field: "name", filter: { kind: "text", operator: "contains", value: "ada" } }, { field: "amount", filter: { kind: "number", operator: "between", from: 10, to: 100 } },]);
// 2. declare a per-resource allow-list (public field → column + kind)const spec = { name: textField({ column: users.name }), amount: numberField({ column: users.amount }), createdAt: dateField({ column: users.createdAt }),};
// 3. build the WHERE and queryconst { where } = buildWhere({ spec, filters, resolveDate });const rows = await db.select().from(users).where(where);To target another store, change only the adapter import (/drizzle →
/kysely /knex /mongo /prisma) and the column reference in the spec.
The model
Section titled “The model”A filter request is built from ColumnFilters — a public field name + a
FieldFilter. FieldFilter is a two-level discriminated union:
- outer
kind— the column data kind:text·number·enum·boolean·date·array. - inner
operator— the argument shape within that kind.
type ColumnFilter = { field: string; filter: FieldFilter };type FiltersRequest = ColumnFilter[]; // flat AND list (the common case)Operators by kind
Section titled “Operators by kind”Operators are Drizzle-aligned and grouped by argument shape:
| Group | Operators | Argument |
|---|---|---|
| scalar | eq ne lt gt lte gte |
value |
| text-match | contains startsWith endsWith like ilike notIlike |
value (string) |
| range | between notBetween |
from + to |
| set | inArray notInArray |
values[] |
| array (PG) | arrayContains arrayContained arrayOverlaps |
values[] |
| unary | isNull isNotNull |
— |
| date preset | is before after between |
unit + timeZone + anchor (+ end) |
Which operators each kind accepts:
| kind | operators |
|---|---|
text |
scalar (eq/ne) + text-match + set + unary |
number |
scalar + range + set + unary |
enum |
eq/ne + set + unary |
boolean |
eq/ne + unary |
date |
date preset + unary |
array |
array (PG) + unary |
OPERATORS_BY_KIND and the *_OPERATORS constants (e.g. TEXT_OPERATORS,
NUMBER_OPERATORS) expose these lists for building UI operator pickers. All are
as const tuples exported from @xtandard/lib/filters:
| Constant | Contents |
|---|---|
TEXT_SCALAR_OPERATORS |
eq ne + text-match (single value) |
NUMBER_SCALAR_OPERATORS |
eq ne lt gt lte gte |
EQUALITY_OPERATORS |
eq ne |
RANGE_OPERATORS |
between notBetween |
SET_OPERATORS |
inArray notInArray |
ARRAY_COL_OPERATORS |
arrayContains arrayContained arrayOverlaps |
UNARY_OPERATORS |
isNull isNotNull |
DATE_PRESET_OPERATORS |
is before after between |
TEXT_OPERATORS … ARRAY_OPERATORS |
everything one kind accepts (= OPERATORS_BY_KIND[kind]) |
import { OPERATORS_BY_KIND, UNARY_OPERATORS } from "@xtandard/lib/filters";
const pickerOptions = OPERATORS_BY_KIND.number.map((op) => ({ value: op, label: op }));const needsValue = (op: string) => !(UNARY_OPERATORS as readonly string[]).includes(op);needsValue("isNull"); // false: hide the value inputExamples of each kind
Section titled “Examples of each kind”// text{ field: "name", filter: { kind: "text", operator: "contains", value: "ada" } }{ field: "name", filter: { kind: "text", operator: "inArray", values: ["a", "b"] } }{ field: "name", filter: { kind: "text", operator: "isNull" } }// number{ field: "amount", filter: { kind: "number", operator: "gte", value: 10 } }{ field: "amount", filter: { kind: "number", operator: "between", from: 10, to: 100 } }// enum / boolean{ field: "status", filter: { kind: "enum", operator: "inArray", values: ["open", "done"] } }{ field: "active", filter: { kind: "boolean", operator: "eq", value: true } }// array (Postgres array column){ field: "tags", filter: { kind: "array", operator: "arrayContains", values: ["x", "y"] } }// date — a DST-aware period preset (resolved to a half-open instant window){ field: "createdAt", filter: { kind: "date", operator: "is", unit: "month", timeZone: "America/Los_Angeles", anchor: "2026-02-01T00:00:00" } }Composition: and / or / not
Section titled “Composition: and / or / not”The flat list ANDs its entries. For arbitrary boolean trees use FilterNode:
import type { FilterNode } from "@xtandard/lib/filters";
const node: FilterNode = { type: "and", nodes: [ { type: "column", field: "status", filter: { kind: "enum", operator: "eq", value: "open" } }, { type: "not", node: { type: "or", nodes: [ { type: "column", field: "name", filter: { kind: "text", operator: "startsWith", value: "tmp" }, }, { type: "column", field: "amount", filter: { kind: "number", operator: "lt", value: 0 } }, ], }, }, ],};// every adapter has a `buildFilterNode` (or `buildFilterNodeSql`) counterpart.Validation — ready-made schemas (or bring your own)
Section titled “Validation — ready-made schemas (or bring your own)”Any request crossing a trust boundary (an HTTP body, a URL) must be validated
before it reaches an adapter — buildWhere consumes already-typed objects and
never validates. The library ships ready-made schemas for four validators as
optional subpaths; import the one you already use:
| Validator | Subpath | Peers |
|---|---|---|
| valibot | @xtandard/lib/filters/valibot |
valibot + @js-temporal/polyfill |
| Zod | @xtandard/lib/filters/zod |
zod + @js-temporal/polyfill |
| ArkType | @xtandard/lib/filters/arktype |
arktype + @js-temporal/polyfill |
| Effect Schema | @xtandard/lib/filters/effect |
effect 3 + @js-temporal/polyfill |
| Effect Schema | @xtandard/lib/filters/effect/v4 |
effect 4 + @js-temporal/polyfill |
Each subpath exports the same names — FieldFilterSchema,
ColumnFilterSchema, FiltersRequestSchema (the flat AND list),
FilterNodeSchema (the recursive and/or/not tree), SortSchema / SortItemSchema,
DatePresetSchema, and the per-kind variant schemas (TextFilterSchema, …).
Every one validates timeZone as a real IANA id and anchor/end as
Temporal.PlainDateTime strings, and a *.test-d.ts asserts each schema’s
inferred output equals the model type — so they can’t drift. A runtime test
runs the same valid and invalid inputs through all four libraries.
Effect has two subpaths with the same exports: @xtandard/lib/filters/effect is
built on effect 3 and @xtandard/lib/filters/effect/v4 on effect 4 (whose Schema
API changed shape). Import the one that matches the effect major you have
installed; the peer range covers both.
anchor/end are wall-clock times, read in the preset’s timeZone, not
instants: Z-suffixed strings such as "2026-02-01T00:00:00Z" are rejected,
while a numeric offset (+02:00) is accepted and ignored, as
Temporal.PlainDateTime.from reads it. A date-only "2026-02-01" is a valid
PlainDateTime (midnight) and passes every library; valibot also normalizes it
to "2026-02-01T00:00:00", while Zod, ArkType and Effect return it unchanged.
// pick one — the parsed result is the same `ColumnFilter[]` either way
// valibotimport * as v from "valibot";import { FiltersRequestSchema } from "@xtandard/lib/filters/valibot";const filters = v.parse(FiltersRequestSchema, await req.json());
// Zodimport { FiltersRequestSchema } from "@xtandard/lib/filters/zod";const filters = FiltersRequestSchema.parse(await req.json());
// ArkType (throws on invalid)import { FiltersRequestSchema } from "@xtandard/lib/filters/arktype";const filters = FiltersRequestSchema.assert(await req.json());
// Effect Schema (on effect 4: "@xtandard/lib/filters/effect/v4", same call)import { Schema } from "effect";import { FiltersRequestSchema } from "@xtandard/lib/filters/effect";const filters = Schema.decodeUnknownSync(FiltersRequestSchema)(await req.json());Then hand the result to any adapter’s buildWhere({ spec, filters, resolveDate }).
Bring your own validator
Section titled “Bring your own validator”The core is validation-library-free — the model is just plain TS types, so
any Standard-Schema validator works if your stack uses something else. Write a
schema whose output is the ColumnFilter[] / FilterNode shape and reuse
the exported operator vocab so it can’t drift from the model:
TEXT_SCALAR_OPERATORS, NUMBER_SCALAR_OPERATORS, EQUALITY_OPERATORS,
RANGE_OPERATORS, SET_OPERATORS, ARRAY_COL_OPERATORS, UNARY_OPERATORS,
DATE_PRESET_OPERATORS (all exported from @xtandard/lib/filters; the date
units are the DateUnit type). The four shipped schemas
(src/filters/schemas*.ts) are worked examples to copy from — each is a
two-level union (outer kind, inner operator shape). For IANA /
Temporal.PlainDateTime parity, @xtandard/lib/valibot exports isValidTimeZone
and the temporal-kind schemas.
The date kind is injected
Section titled “The date kind is injected”A date preset (e.g. “this month in America/Los_Angeles”) resolves to a
half-open [gte, lt) instant window. That DST-aware resolution — and the
human chip label — are app-specific, so they are injected rather than
bundling a date library:
type DateFilterResolver = (input: { value: DatePreset }) => { start: Date | null; // inclusive lower bound (→ gte) end: Date | null; // exclusive upper bound (→ lt)};Pass resolveDate to any adapter’s buildWhere/buildFilterNode — a date
preset filter without it throws (a bare date isNull/isNotNull needs
nothing). For chip labels, pass describeDate to describeFieldFilter. (In
demi.casa, both come from @demi.casa/time: resolveDateFilter /
describeDateSelectorValue.)
The
datepreset is the only place we use timezone-aware date math, and it is always rendered as half-open>= start AND < end— never SQLBETWEEN, whose inclusive upper bound double-counts the boundary (PG: Don’t Do This).