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