Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

evaluate.ts

484 lines14.8 KB

1/**
2 * Deterministic rate-card evaluator. ~100 lines of JSONLogic over
3 * the closed vocabulary in `rate-card.schema.ts` — smaller than json-logic-js,
4 * no `eval`, and it refuses instead of coercing: an unknown op, an unbound
5 * input, a missing table key or a non-numeric operand throws, and so does a
6 * price that is not a finite positive number. A refusal is an honest
7 * "unknown"; a made-up number is a wrong price.
8 */
9import { CORE_OPS, currencyWrapper } from './rate-card.schema.ts'
10import type {
11 CoreOp,
12 Expr,
13 RateCard,
14 RateCardEstimate,
15 RateCardExample,
16 Table,
17} from './rate-card.schema.ts'
18​
19export type RateCardErrorCode =
20 | 'unknown-op'
21 | 'unbound-var'
22 | 'bad-input'
23 | 'missing-key'
24 | 'not-a-number'
25 | 'not-comparable'
26 | 'bad-result'
27 | 'estimate-unavailable'
28​
29export class RateCardError extends Error {
30 constructor(
31 readonly code: RateCardErrorCode,
32 message: string,
33 ) {
34 super(message)
35 this.name = 'RateCardError'
36 }
38​
39type Vars = Record<string, unknown>
40​
41/**
42 * A card's currency and the expression that yields the amount in it. Safe
43 * on a card that was never parsed: a malformed wrapper, or no price at
44 * all, throws `unknown-op` rather than naming a currency it cannot vouch
45 * for.
46 */
47export function cardPrice(card: Pick<RateCard, 'price'>): {
48 currency: string
49 expr: Expr
50} {
51 const loose = card as { price?: unknown; currency?: unknown } | null
52 const raw = loose?.price
53 const wrapper = currencyWrapper(raw)
54 if (raw == null || wrapper === 'malformed') {
55 throw new RateCardError(
56 'unknown-op',
57 `price is not an expression or { currency: [code, expr] }: ${JSON.stringify(raw)}`,
58 )
59 }
60 // The schema refuses this key; an unparsed card meant as another
61 // currency must not be read as USD here either.
62 if (loose?.currency !== undefined) {
63 throw new RateCardError(
64 'unknown-op',
65 'currency is stated by wrapping price, not by a top-level key',
66 )
67 }
68 return wrapper === null
69 ? { currency: 'USD', expr: raw }
70 : { currency: wrapper.currency, expr: wrapper.expr as Expr }
72​
73/** The ISO-4217 code a card's amounts are in: USD unless its price says. */
74export function cardCurrency(card: Pick<RateCard, 'price'>): string {
75 return cardPrice(card).currency
77​
78const isRecord = (v: unknown): v is Record<string, unknown> =>
79 typeof v === 'object' && v !== null && !Array.isArray(v)
80​
81const isCoreOp = (op: string): op is CoreOp =>
82 (CORE_OPS as readonly string[]).includes(op)
83​
84/** `{var: 'image_size.width'}` walks dotted paths. */
85function readVar(vars: Vars, path: string): unknown {
86 let value: unknown = vars
87 for (const key of path.split('.')) {
88 if (!isRecord(value) || !(key in value)) return undefined
89 value = value[key]
90 }
91 return value
93​
94/**
95 * `==` is strict, unlike JSONLogic's loose `==`: a number against a string
96 * (Kling's `duration` "5" is bound as 5) refuses instead of quietly taking
97 * the wrong branch.
98 */
99function same(a: unknown, b: unknown): boolean {
100 const kind = (v: unknown) =>
101 typeof v === 'number' || typeof v === 'string' || typeof v === 'boolean'
102 ? typeof v
103 : undefined
104 if (kind(a) === undefined || kind(a) !== kind(b)) {
105 throw new RateCardError(
106 'not-comparable',
107 `${JSON.stringify(a)} vs ${JSON.stringify(b)}`,
108 )
109 }
110 return a === b
112​
113const truthy = (v: unknown): boolean =>
114 Array.isArray(v) ? v.length > 0 : Boolean(v)
115​
116function lookup(
117 tables: Record<string, Table>,
118 table: string,
119 path: string[],
120): number | undefined {
121 let node: number | Table | undefined = tables[table]
122 for (const key of path) {
123 node = typeof node === 'object' ? node[key] : undefined
124 }
125 return typeof node === 'number' ? node : undefined
127​
128function evalExpr(
129 expr: Expr,
130 vars: Vars,
131 tables: Record<string, Table>,
132): unknown {
133 if (typeof expr !== 'object') return expr
134 const ev = (e: Expr) => evalExpr(e, vars, tables)
135 const num = (e: Expr): number => {
136 const v = ev(e)
137 if (typeof v !== 'number' || !Number.isFinite(v)) {
138 throw new RateCardError(
139 'not-a-number',
140 `${JSON.stringify(e)} → ${JSON.stringify(v)}`,
141 )
142 }
143 return v
144 }
145​
146 if ('lookup' in expr) {
147 const { table, keys, default: fallback } = expr.lookup
148 const path = keys.map((k) => {
149 const key = ev(k)
150 if (typeof key === 'string') return key
151 if (typeof key === 'number') return String(key)
152 throw new RateCardError(
153 'missing-key',
154 `${table}: key ${JSON.stringify(key)}`,
155 )
156 })
157 const hit = lookup(tables, table, path)
158 if (hit !== undefined) return hit
159 if (fallback !== undefined) return ev(fallback)
160 throw new RateCardError('missing-key', `${table}[${path.join('][')}]`)
161 }
162​
163 const keys = Object.keys(expr)
164 const op = keys[0]
165 if (keys.length !== 1 || op === undefined || !isCoreOp(op)) {
166 throw new RateCardError('unknown-op', keys.join(','))
167 }
168 const raw = expr[op]
169 const args: Expr[] = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]
170 const arg = (i: number): Expr => {
171 const e = args[i]
172 if (e === undefined) {
173 throw new RateCardError('unknown-op', `${op}: missing operand ${i}`)
174 }
175 return e
176 }
177 const name = (e: Expr): string => {
178 if (typeof e !== 'string') {
179 throw new RateCardError('unbound-var', JSON.stringify(e))
180 }
181 return e
182 }
183​
184 switch (op) {
185 case 'var': {
186 const v = readVar(vars, name(arg(0)))
187 if (v === undefined) throw new RateCardError('unbound-var', name(arg(0)))
188 return v
189 }
190 case 'missing':
191 return args.map(name).filter((n) => readVar(vars, n) === undefined)
192 case '+':
193 return args.reduce<number>((sum, e) => sum + num(e), 0)
194 case '*':
195 return args.reduce<number>((product, e) => product * num(e), 1)
196 case '-':
197 return args.length === 1 ? -num(arg(0)) : num(arg(0)) - num(arg(1))
198 case '/':
199 return num(arg(0)) / num(arg(1))
200 case 'max':
201 return Math.max(...args.map(num))
202 case 'min':
203 return Math.min(...args.map(num))
204 case 'ceil':
205 return Math.ceil(num(arg(0)))
206 case 'floor':
207 return Math.floor(num(arg(0)))
208 case '==':
209 return same(ev(arg(0)), ev(arg(1)))
210 case '!=':
211 return !same(ev(arg(0)), ev(arg(1)))
212 case '<':
213 return num(arg(0)) < num(arg(1))
214 case '<=':
215 return num(arg(0)) <= num(arg(1))
216 case '>':
217 return num(arg(0)) > num(arg(1))
218 case '>=':
219 return num(arg(0)) >= num(arg(1))
220 case 'and': {
221 let last: unknown = true
222 for (const e of args) {
223 last = ev(e)
224 if (!truthy(last)) return last
225 }
226 return last
227 }
228 case 'or': {
229 let last: unknown = false
230 for (const e of args) {
231 last = ev(e)
232 if (truthy(last)) return last
233 }
234 return last
235 }
236 case 'if': {
237 // [cond, then, cond, then, ..., else]
238 for (let i = 0; i + 1 < args.length; i += 2) {
239 if (truthy(ev(arg(i)))) return ev(arg(i + 1))
240 }
241 return args.length % 2 === 1 ? ev(arg(args.length - 1)) : null
242 }
243 }
245​
246const isNumeric = (v: unknown): v is number | string =>
247 (typeof v === 'number' && Number.isFinite(v)) ||
248 (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)))
249​
250/**
251 * Bind every input from `vars` by param name, with defaults. Never applies
252 * an `estimate`: a number input with one but no value throws `required`
253 * here (see `priceDetailed`).
254 */
255export function bindInputs(card: Pick<RateCard, 'inputs'>, params: Vars): Vars {
256 const vars: Vars = {}
257 for (const [name, input] of Object.entries(card.inputs)) {
258 const raw = params[input.param]
259 const bad = (why: string, value?: unknown) =>
260 new RateCardError(
261 'bad-input',
262 `${name} (${input.param}): ${why}${value === undefined ? '' : ` ${JSON.stringify(value)}`}`,
263 )
264 switch (input.kind) {
265 case 'count':
266 if (raw === undefined) vars[name] = 0
267 else if (Array.isArray(raw)) vars[name] = raw.length
268 else throw bad('expected a list, got', raw)
269 break
270 case 'number': {
271 const value = raw ?? input.default
272 if (value === undefined) throw bad('required')
273 // Enum-typed durations arrive as strings ("5").
274 if (!isNumeric(value)) throw bad('not a number:', value)
275 vars[name] = Number(value)
276 break
277 }
278 case 'boolean': {
279 const value = raw ?? input.default
280 if (value === undefined) throw bad('required')
281 if (typeof value !== 'boolean')
282 throw bad('expected a boolean, got', value)
283 vars[name] = value
284 break
285 }
286 case 'enum': {
287 const value = raw ?? input.default
288 if (value === undefined) throw bad('required')
289 if (typeof value !== 'string' || !input.values.includes(value)) {
290 throw bad(`not one of ${input.values.join('|')}:`, value)
291 }
292 vars[name] = value
293 break
294 }
295 case 'dimensions': {
296 const value = raw ?? input.default
297 if (
298 isRecord(value) &&
299 isNumeric(value.width) &&
300 isNumeric(value.height)
301 ) {
302 vars[name] = {
303 width: Number(value.width),
304 height: Number(value.height),
305 }
306 break
307 }
308 const pixels =
309 typeof value === 'string' ? /^(\d+)x(\d+)$/.exec(value) : null
310 if (pixels) {
311 vars[name] = { width: Number(pixels[1]), height: Number(pixels[2]) }
312 break
313 }
314 if (typeof value === 'string' && input.levels?.includes(value)) {
315 vars[name] = { level: value }
316 break
317 }
318 const preset =
319 typeof value === 'string' ? input.presets?.[value] : undefined
320 if (!preset) throw bad('unknown size:', value)
321 vars[name] = { width: preset[0], height: preset[1] }
322 break
323 }
324 }
325 }
326 return vars
328​
329/**
330 * The amount for this call, as billed, in the card's currency
331 * (`cardCurrency(card)`; USD unless the card says otherwise). Never add
332 * or compare amounts from cards in different currencies. Request-bound
333 * levers read `request`;
334 * usage-bound levers read `usage`. A usage key on the request body, or a
335 * request field in usage, is not read. Omit `usage` only when every
336 * usage-bound input has a default (or the card has none); token cards that
337 * require `input_tokens` / `output_tokens` throw `bad-input` without them.
338 * Never estimates: an omitted input that carries an `estimate` throws
339 * `required` like any other — call `priceDetailed` to get a labelled
340 * estimate. Throws `RateCardError` rather than returning a number it
341 * cannot stand behind.
342 */
343export function price(
344 card: RateCard,
345 request: Vars = {},
346 usage: Vars = {},
347): number {
348 return evaluate(card, request, usage, false).amount
350​
351export interface PriceResult {
352 /** The price, in `currency`. */
353 amount: number
354 /** ISO-4217 code `amount` is in. */
355 currency: string
356 /** `amount` again when `currency` is USD; absent for any other currency. */
357 usd?: number
358 /**
359 * Params of inputs the caller omitted whose value came from the card's
360 * published `estimate`. Empty means every input was supplied (or a plain
361 * default), so `amount` is the price as billed.
362 */
363 estimated: string[]
365​
366/** Read each input's param from the request or usage object by bound. */
367function collect(inputs: RateCard['inputs'], request: Vars, usage: Vars): Vars {
368 const vars: Vars = {}
369 for (const input of Object.values(inputs)) {
370 const from = input.bound === 'usage' ? usage : request
371 if (input.param in from) vars[input.param] = from[input.param]
372 }
373 return vars
375​
376/**
377 * `price`, but an omitted input that carries an `estimate` is estimated
378 * by it and named in `estimated`. An estimate that cannot be made for this
379 * request throws `estimate-unavailable` naming the input to pass instead.
380 */
381export function priceDetailed(
382 card: RateCard,
383 request: Vars = {},
384 usage: Vars = {},
385): PriceResult {
386 return evaluate(card, request, usage, true)
388​
389function evaluate(
390 card: RateCard,
391 request: Vars,
392 usage: Vars,
393 estimates: boolean,
394): PriceResult {
395 const given = collect(card.inputs, request, usage)
396 const estimated: string[] = []
397 const direct: RateCard['inputs'] = {}
398 const pending: Array<[string, string, RateCardEstimate]> = []
399 for (const [name, input] of Object.entries(card.inputs)) {
400 if (
401 estimates &&
402 input.kind === 'number' &&
403 input.estimate &&
404 !(input.param in given)
405 ) {
406 pending.push([name, input.param, input.estimate])
407 estimated.push(input.param)
408 } else {
409 direct[name] = input
410 }
411 }
412 const vars = bindInputs({ inputs: direct }, given)
413 for (const [name, param, estimate] of pending) {
414 try {
415 const own = bindInputs(estimate, collect(estimate.inputs, request, usage))
416 const value = evalExpr(estimate.value, { ...vars, ...own }, card.tables)
417 if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
418 throw new RateCardError(
419 'bad-result',
420 `estimate evaluated to ${JSON.stringify(value)}`,
421 )
422 }
423 vars[name] = value
424 } catch (error) {
425 if (!(error instanceof RateCardError)) throw error
426 throw new RateCardError(
427 'estimate-unavailable',
428 `${name} (${param}): not supplied, and cannot be estimated for this request: ${error.message}`,
429 )
430 }
431 }
432 const { currency, expr } = cardPrice(card)
433 const amount = evalExpr(expr, vars, card.tables)
434 // A source-published free card has a literal zero price. A paid formula that
435 // evaluates to zero still signals an invalid or missing billable quantity.
436 if (
437 typeof amount !== 'number' ||
438 !Number.isFinite(amount) ||
439 amount < 0 ||
440 (amount === 0 && expr !== 0)
441 ) {
442 throw new RateCardError(
443 'bad-result',
444 `price evaluated to ${JSON.stringify(amount)}`,
445 )
446 }
447 return {
448 amount,
449 currency,
450 ...(currency === 'USD' && { usd: amount }),
451 estimated,
452 }
454​
455/** Relative tolerance when reproducing a source's worked example. */
456const EXAMPLE_TOLERANCE = 0.01
457​
458export type ExampleResult = {
459 example: RateCardExample
460 ok: boolean
461 usd?: number
462 error?: string
464​
465/** Every worked example must reproduce within 1% or the card is rejected. */
466export function verifyExamples(card: RateCard): ExampleResult[] {
467 return card.examples.map((example) => {
468 try {
469 // Examples are a flat bag; each lever is read from request or usage
470 // by bound, so the same dict in both slots is correct.
471 const usd = price(card, example.params, example.params)
472 const ok = Math.abs(usd - example.usd) <= example.usd * EXAMPLE_TOLERANCE
473 return ok
474 ? { example, ok, usd }
475 : { example, ok, usd, error: `expected ${example.usd}, got ${usd}` }
476 } catch (error) {
477 const message =
478 error instanceof RateCardError
479 ? `${error.code}: ${error.message}`
480 : String(error)
481 return { example, ok: false, error: message }
482 }
483 })