UNPKG

@mastra/core

Version:
1 lines • 17 kB
{"version":3,"file":"index.cjs","names":["z"],"sources":["../../src/predicate/index.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n/**\n * Declarative predicate DSL shared across the framework.\n *\n * Predicates are a JSON-safe, storable alternative to closure conditions.\n * The base module owns the grammar and evaluation semantics; each domain\n * (workflows, scoring, ...) composes its own typed evaluator via\n * `createPredicateEvaluator`, supplying only path resolution over its own\n * context shape.\n *\n * The DSL is deliberately minimal: comparisons, membership, existence,\n * truthiness, and boolean composition. Missing paths never throw — path-based\n * ops return `false` when the path can't be resolved. Callers who want to\n * distinguish \"missing\" from \"falsy\" should use `exists` / `notExists`.\n */\n\nconst LITERAL_SCALAR = z.union([z.string(), z.number(), z.boolean(), z.null()]);\n\nconst pathRef: z.ZodType<{ path: string }> = z.object({ path: z.string().min(1) }).strict();\nconst literalRef: z.ZodType<{ literal: string | number | boolean | null }> = z\n .object({ literal: LITERAL_SCALAR })\n .strict();\nconst pathOrLiteral: z.ZodType<PathOrLiteral> = z.union([pathRef, literalRef]);\n\nconst COMPARISON_OPS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte'] as const;\nconst MEMBERSHIP_OPS = ['in', 'notIn'] as const;\n\n/**\n * The predicate Zod schema. We define it via `z.lazy` so the recursive\n * `and` / `or` / `not` branches can reference the top-level type.\n */\nexport const predicateSchema: z.ZodType<Predicate> = z.lazy(() =>\n z.union([\n z.object({ op: z.enum(COMPARISON_OPS), left: pathOrLiteral, right: pathOrLiteral }).strict(),\n z\n .object({\n op: z.enum(MEMBERSHIP_OPS),\n value: pathOrLiteral,\n set: z.array(LITERAL_SCALAR).min(1),\n })\n .strict(),\n z.object({ op: z.enum(['exists', 'notExists']), path: z.string().min(1) }).strict(),\n z.object({ op: z.enum(['truthy', 'falsy']), value: pathOrLiteral }).strict(),\n z.object({ op: z.enum(['and', 'or']), args: z.array(predicateSchema).min(1) }).strict(),\n z.object({ op: z.literal('not'), arg: predicateSchema }).strict(),\n ]),\n);\n\nexport type PathOrLiteral = { path: string } | { literal: string | number | boolean | null };\n\nexport type Predicate =\n | { op: 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte'; left: PathOrLiteral; right: PathOrLiteral }\n | { op: 'in' | 'notIn'; value: PathOrLiteral; set: Array<string | number | boolean | null> }\n | { op: 'exists' | 'notExists'; path: string }\n | { op: 'truthy' | 'falsy'; value: PathOrLiteral }\n | { op: 'and' | 'or'; args: Predicate[] }\n | { op: 'not'; arg: Predicate };\n\nconst PATH_PLACEHOLDER = /^\\$\\{([^}]+)\\}$/;\n\n/** Sentinel returned by path resolvers when a path can't be resolved. */\nexport const MISSING = Symbol('predicate.missing');\nexport type Missing = typeof MISSING;\n\n/**\n * Normalize a raw predicate path. Accepts both plain dotted paths (`foo.bar`)\n * and template-style paths (`${foo.bar}`). Returns `MISSING` for an empty path.\n */\nexport function normalizePredicatePath(rawPath: string): string | Missing {\n const templateMatch = PATH_PLACEHOLDER.exec(rawPath.trim());\n const path = templateMatch ? templateMatch[1]!.trim() : rawPath.trim();\n if (path === '') return MISSING;\n return path;\n}\n\n/**\n * Non-throwing dot-path traversal of an arbitrary object graph. Returns\n * `MISSING` if any segment can't be resolved, so callers can distinguish\n * \"no value\" from `null`.\n */\nexport function walk(root: unknown, path: string): unknown | Missing {\n if (path === '') return root;\n const parts = path.split('.');\n let value: unknown = root;\n for (const part of parts) {\n if (value === null || value === undefined) return MISSING;\n if (typeof value !== 'object') return MISSING;\n const record = value as Record<string, unknown>;\n // Own properties only: `in` would match prototype-chain keys (e.g.\n // `constructor`, `toString`), letting stored filter paths resolve to\n // inherited values instead of MISSING.\n if (!Object.hasOwn(record, part)) return MISSING;\n value = record[part];\n }\n return value;\n}\n\n/** A domain-supplied path resolver over that domain's context shape. */\nexport type PredicatePathResolver<TCtx> = (rawPath: string, ctx: TCtx) => unknown | Missing;\n\n/**\n * Compose a typed predicate evaluator from a domain path resolver.\n *\n * The returned evaluator never throws for path resolution failures — missing\n * paths propagate to `false` on comparison ops and `in`, to `true` on the\n * negated ops `notIn` and `notExists` (a missing value is trivially \"not in\"\n * any set), and to `false` on `exists`. It throws only if the\n * predicate shape itself is malformed (which `predicateSchema.parse` catches\n * at load time).\n */\nexport function createPredicateEvaluator<TCtx>(\n resolvePath: PredicatePathResolver<TCtx>,\n): (pred: Predicate, ctx: TCtx) => boolean {\n const resolveValue = (ref: PathOrLiteral, ctx: TCtx): unknown | Missing => {\n if ('literal' in ref) return ref.literal;\n return resolvePath(ref.path, ctx);\n };\n\n const evaluate = (pred: Predicate, ctx: TCtx): boolean => {\n switch (pred.op) {\n case 'and':\n return pred.args.every(arg => evaluate(arg, ctx));\n case 'or':\n return pred.args.some(arg => evaluate(arg, ctx));\n case 'not':\n return !evaluate(pred.arg, ctx);\n case 'exists': {\n const v = resolvePath(pred.path, ctx);\n return v !== MISSING;\n }\n case 'notExists': {\n const v = resolvePath(pred.path, ctx);\n return v === MISSING;\n }\n case 'truthy':\n case 'falsy': {\n const v = resolveValue(pred.value, ctx);\n const truthy = v !== MISSING && Boolean(v);\n return pred.op === 'truthy' ? truthy : !truthy;\n }\n case 'in':\n case 'notIn': {\n const v = resolveValue(pred.value, ctx);\n if (v === MISSING) return pred.op === 'notIn';\n const member = pred.set.some(candidate => strictEqual(candidate, v));\n return pred.op === 'in' ? member : !member;\n }\n case 'eq':\n case 'ne':\n case 'lt':\n case 'lte':\n case 'gt':\n case 'gte': {\n const left = resolveValue(pred.left, ctx);\n const right = resolveValue(pred.right, ctx);\n if (left === MISSING || right === MISSING) return false;\n return compare(pred.op, left, right);\n }\n }\n };\n\n return evaluate;\n}\n\nfunction strictEqual(a: unknown, b: unknown): boolean {\n // Set membership uses strict equality on scalars. `null === null` is true;\n // NaN never equals itself (matches SQL/JS semantics both).\n return a === b;\n}\n\nfunction compare(op: 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte', left: unknown, right: unknown): boolean {\n if (op === 'eq') return left === right;\n if (op === 'ne') return left !== right;\n // Ordering ops require comparable scalars. Anything else is `false`.\n if (\n (typeof left === 'number' && typeof right === 'number') ||\n (typeof left === 'string' && typeof right === 'string')\n ) {\n switch (op) {\n case 'lt':\n return left < right;\n case 'lte':\n return left <= right;\n case 'gt':\n return left > right;\n case 'gte':\n return left >= right;\n }\n }\n return false;\n}\n\n/**\n * Validate that every path referenced by a predicate starts with one of the\n * domain's known roots. Domains call this at definition time so typo'd roots\n * fail loud where they're cheap — evaluation stays fail-quiet by design.\n * Returns the list of offending paths (empty when valid).\n */\nexport function collectInvalidPredicatePaths(pred: Predicate, roots: readonly string[]): string[] {\n const invalid: string[] = [];\n const checkPath = (rawPath: string) => {\n const normalized = normalizePredicatePath(rawPath);\n if (normalized === MISSING) {\n invalid.push(rawPath);\n return;\n }\n const dot = normalized.indexOf('.');\n const scope = dot === -1 ? normalized : normalized.slice(0, dot);\n if (!roots.includes(scope)) invalid.push(rawPath);\n };\n const checkRef = (ref: PathOrLiteral) => {\n if ('path' in ref) checkPath(ref.path);\n };\n const visit = (p: Predicate) => {\n switch (p.op) {\n case 'and':\n case 'or':\n p.args.forEach(visit);\n break;\n case 'not':\n visit(p.arg);\n break;\n case 'exists':\n case 'notExists':\n checkPath(p.path);\n break;\n case 'truthy':\n case 'falsy':\n checkRef(p.value);\n break;\n case 'in':\n case 'notIn':\n checkRef(p.value);\n break;\n default:\n checkRef(p.left);\n checkRef(p.right);\n }\n };\n visit(pred);\n return invalid;\n}\n\n/**\n * Produce a short human-readable label for a predicate, suitable for\n * rendering as a condition-node label in a graph UI.\n * Bounded output length; no user-controlled text is passed through\n * unescaped — string literals go through JSON.stringify, and paths that\n * contain anything beyond plain identifier/dot characters are rendered as\n * JSON strings too, so a malicious value can't break out of the\n * surrounding rendering.\n */\nexport function derivePredicateLabel(pred: Predicate, maxLength = 80): string {\n const raw = renderPredicate(pred);\n if (raw.length <= maxLength) return raw;\n return raw.slice(0, maxLength - 1) + '…';\n}\n\nfunction renderPredicate(pred: Predicate): string {\n switch (pred.op) {\n case 'and':\n case 'or':\n return pred.args.map(arg => wrap(arg, renderPredicate(arg))).join(pred.op === 'and' ? ' AND ' : ' OR ');\n case 'not':\n return `NOT ${wrap(pred.arg, renderPredicate(pred.arg))}`;\n case 'exists':\n return `${renderPath(pred.path)} exists`;\n case 'notExists':\n return `${renderPath(pred.path)} missing`;\n case 'truthy':\n return `${renderValue(pred.value)} is truthy`;\n case 'falsy':\n return `${renderValue(pred.value)} is falsy`;\n case 'in':\n return `${renderValue(pred.value)} in ${JSON.stringify(pred.set)}`;\n case 'notIn':\n return `${renderValue(pred.value)} not in ${JSON.stringify(pred.set)}`;\n case 'eq':\n return `${renderValue(pred.left)} == ${renderValue(pred.right)}`;\n case 'ne':\n return `${renderValue(pred.left)} != ${renderValue(pred.right)}`;\n case 'lt':\n return `${renderValue(pred.left)} < ${renderValue(pred.right)}`;\n case 'lte':\n return `${renderValue(pred.left)} <= ${renderValue(pred.right)}`;\n case 'gt':\n return `${renderValue(pred.left)} > ${renderValue(pred.right)}`;\n case 'gte':\n return `${renderValue(pred.left)} >= ${renderValue(pred.right)}`;\n }\n}\n\nfunction wrap(child: Predicate, rendered: string): string {\n // Parenthesize child boolean composites so precedence is unambiguous.\n return child.op === 'and' || child.op === 'or' || child.op === 'not' ? `(${rendered})` : rendered;\n}\n\nfunction renderValue(ref: PathOrLiteral): string {\n if ('literal' in ref) return JSON.stringify(ref.literal);\n return renderPath(ref.path);\n}\n\n/**\n * Paths are only schema-validated as non-empty strings, so anything beyond\n * plain identifier/dot/template characters is escaped via JSON.stringify to\n * keep markup or quotes from reaching the rendered label unchanged.\n */\nfunction renderPath(path: string): string {\n return /^[\\w.$]+$/.test(path) ? path : JSON.stringify(path);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,iBAAiBA,OAAAA,EAAE,MAAM;CAACA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,QAAQ;CAAGA,OAAA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