Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 RateCardError,
4 bindInputs,
5 cardCurrency,
6 cardPrice,
7 price,
8 priceDetailed,
9 verifyExamples,
10} from './evaluate.ts'
11import { z } from 'zod'
12
13import { CORE_OPS, rateCardSchema } from './rate-card.schema.ts'
14import type { Expr, RateCard } from './rate-card.schema.ts'
15
16const source = {
17 url: 'https://example.test/llms.txt',
18 hash: 'a'.repeat(64),
19 extractedAt: '2026-09-13T00:00:00Z',
20}
21
22/** A card whose price is `expr`, over number inputs `x` (default 4) and `y` (default 2). */
23const cardFor = (expr: Expr, extra: Partial<RateCard> = {}): RateCard => ({
24 inputs: {
25 x: { param: 'x', kind: 'number', default: 4 },
26 y: { param: 'y', kind: 'number', default: 2 },
27 },
28 tables: { t: { a: { p: 1.5 }, b: { p: 3 } } },
29 price: expr,
30 examples: [],
31 source,
32 ...extra,
33})
34
35const usd = (expr: Expr, params: Record<string, unknown> = {}) =>
36 price(cardFor(expr), params)
37
38describe('ops', () => {
39 it.each<[string, Expr, number]>([
40 ['+ variadic', { '+': [{ var: 'x' }, { var: 'y' }, 1] }, 7],
41 ['- binary', { '-': [{ var: 'x' }, { var: 'y' }] }, 2],
42 ['* variadic', { '*': [{ var: 'x' }, { var: 'y' }, 0.5] }, 4],
43 ['/', { '/': [{ var: 'x' }, { var: 'y' }] }, 2],
44 ['max', { max: [1, { var: 'x' }, 3] }, 4],
45 ['min', { min: [{ var: 'x' }, 3, { var: 'y' }] }, 2],
46 ['ceil', { ceil: [{ '/': [{ var: 'x' }, 3] }] }, 2],
47 ['floor', { floor: [{ '/': [{ var: 'x' }, 3] }] }, 1],
48 [
49 'if chain',
50 {
51 if: [
52 { '<': [{ var: 'x' }, 2] },
53 10,
54 { '<': [{ var: 'x' }, 5] },
55 20,
56 30,
57 ],
58 },
59 20,
60 ],
61 ['== literal', { if: [{ '==': [{ var: 'x' }, 4] }, 1, 2] }, 1],
62 ['!=', { if: [{ '!=': [{ var: 'x' }, 4] }, 1, 2] }, 2],
63 ['<=', { if: [{ '<=': [{ var: 'x' }, 4] }, 1, 2] }, 1],
64 ['>', { if: [{ '>': [{ var: 'x' }, 4] }, 1, 2] }, 2],
65 ['>=', { if: [{ '>=': [{ var: 'x' }, 4] }, 1, 2] }, 1],
66 ['and', { if: [{ and: [true, { '>': [{ var: 'x' }, 1] }] }, 1, 2] }, 1],
67 ['or', { if: [{ or: [false, { '>': [{ var: 'x' }, 1] }] }, 1, 2] }, 1],
68 [
69 'missing → falsy when nothing is missing',
70 { if: [{ missing: ['x'] }, 1, 2] },
71 2,
72 ],
73 [
74 'missing → truthy when something is',
75 { if: [{ missing: ['x', 'nope'] }, 1, 2] },
76 1,
77 ],
78 ['lookup nested', { lookup: { table: 't', keys: ['b', 'p'] } }, 3],
79 [
80 'lookup default',
81 { lookup: { table: 't', keys: ['zzz'], default: 9 } },
82 9,
83 ],
84 ])('%s', (_name, expr, expected) => {
85 expect(usd(expr)).toBe(expected)
86 })
87})
88
89describe('binding', () => {
90 const card: RateCard = {
91 inputs: {
92 duration: { param: 'duration', kind: 'number', default: 5 },
93 res: {
94 param: 'resolution',
95 kind: 'enum',
96 values: ['480p', '720p'],
97 default: '480p',
98 },
99 audio: { param: 'generate_audio', kind: 'boolean', default: true },
100 refs: { param: 'image_urls', kind: 'count' },
101 size: {
102 param: 'image_size',
103 kind: 'dimensions',
104 presets: { square_hd: [1024, 1024] },
105 default: 'square_hd',
106 },
107 },
108 tables: {},
109 price: 1,
110 examples: [],
111 source,
112 }
113
114 it('binds by request param name, falling back to defaults', () => {
115 expect(bindInputs(card, {})).toEqual({
116 duration: 5,
117 res: '480p',
118 audio: true,
119 refs: 0,
120 size: { width: 1024, height: 1024 },
121 })
122 })
123
124 it('reads a numeric string duration, a list length and explicit pixels', () => {
125 expect(
126 bindInputs(card, {
127 duration: '8',
128 resolution: '720p',
129 generate_audio: false,
130 image_urls: ['a', 'b'],
131 image_size: { width: 1920, height: 1080 },
132 }),
133 ).toEqual({
134 duration: 8,
135 res: '720p',
136 audio: false,
137 refs: 2,
138 size: { width: 1920, height: 1080 },
139 })
140 })
141
142 it('reads WxH as pixels and a level by name', () => {
143 const c: RateCard = {
144 ...card,
145 inputs: {
146 ...card.inputs,
147 size: { param: 'image_size', kind: 'dimensions', levels: ['2K'] },
148 },
149 }
150 expect(bindInputs(c, { image_size: '2048x1152' }).size).toEqual({
151 width: 2048,
152 height: 1152,
153 })
154 expect(bindInputs(c, { image_size: '2K' }).size).toEqual({ level: '2K' })
155 expect(() => bindInputs(c, { image_size: '4K' })).toThrow(RateCardError)
156 })
157
158 it('var walks dotted paths into dimensions', () => {
159 const c: RateCard = {
160 ...card,
161 price: { '*': [{ var: 'size.width' }, 0.001] },
162 }
163 expect(price(c, {})).toBe(1.024)
164 })
165
166 it.each<[string, Record<string, unknown>]>([
167 ['enum outside values', { resolution: '1080p' }],
168 ['non-numeric number', { duration: 'five' }],
169 ['non-boolean boolean', { generate_audio: 'yes' }],
170 ['non-list count', { image_urls: 'a' }],
171 ['unknown size preset', { image_size: 'portrait_4_3' }],
172 ])('refuses %s', (_name, params) => {
173 expect(() => price(card, params)).toThrow(RateCardError)
174 })
175})
176
177/** Outside the vocabulary; parsed so no assertion has to lie about its type. */
178const unknownOp = JSON.parse('{"cat":[1,2]}') as Expr
179
180describe('refusals', () => {
181 it.each<[string, Expr, string]>([
182 ['unknown op', unknownOp, 'unknown-op'],
183 ['unbound var', { var: 'nope' }, 'unbound-var'],
184 [
185 'missing lookup key without default',
186 { lookup: { table: 't', keys: ['zzz', 'p'] } },
187 'missing-key',
188 ],
189 ['non-numeric operand', { '+': [{ var: 'x' }, 'text'] }, 'not-a-number'],
190 // JSONLogic's == is loose; ours refuses a type mismatch instead of returning false.
191 [
192 '== across types',
193 { if: [{ '==': [{ var: 'x' }, '4'] }, 1, 2] },
194 'not-comparable',
195 ],
196 [
197 '!= across types',
198 { if: [{ '!=': [{ var: 'x' }, '4'] }, 1, 2] },
199 'not-comparable',
200 ],
201 [
202 '== on a list',
203 { if: [{ '==': [{ missing: ['x'] }, 0] }, 1, 2] },
204 'not-comparable',
205 ],
206 ['zero price', { '-': [{ var: 'x' }, 4] }, 'bad-result'],
207 ['negative price', { '-': [1, { var: 'x' }] }, 'bad-result'],
208 ['non-finite price', { '/': [{ var: 'x' }, 0] }, 'bad-result'],
209 ['non-numeric price', { '<': [1, 2] }, 'bad-result'],
210 ])('%s', (_name, expr, code) => {
211 expect(() => usd(expr)).toThrow(expect.objectContaining({ code }))
212 })
213
214 const doubleX: Expr = { '*': [{ var: 'x' }, 2] }
215 const yuan = { ...cardFor(doubleX), price: { currency: ['CNY', doubleX] } }
216
217 it('accepts source-published literal free prices in USD and CNY', () => {
218 const free = cardFor(0, { inputs: {}, tables: {} })
219 expect(priceDetailed(rateCardSchema.parse(free))).toEqual({
220 amount: 0,
221 currency: 'USD',
222 usd: 0,
223 estimated: [],
224 })
225 const cny = rateCardSchema.parse({
226 ...free,
227 price: { currency: ['CNY', 0] },
228 })
229 expect(priceDetailed(cny)).toEqual({
230 amount: 0,
231 currency: 'CNY',
232 estimated: [],
233 })
234 expect(price(cny)).toBe(0)
235 })
236
237 it('rejects negative native currency and computed zero paid prices', () => {
238 const negative = rateCardSchema.parse({
239 ...cardFor(1),
240 price: { currency: ['CNY', -1] },
241 })
242 expect(() => price(negative)).toThrow(
243 expect.objectContaining({ code: 'bad-result' }),
244 )
245 const paid = rateCardSchema.parse(yuan)
246 expect(() => price(paid, { x: 0 })).toThrow(
247 expect.objectContaining({ code: 'bad-result' }),
248 )
249 })
250
251 it('prices a card in its own currency and never calls it USD', () => {
252 const parsed = rateCardSchema.parse(yuan)
253 expect(cardCurrency(parsed)).toBe('CNY')
254 expect(priceDetailed(parsed)).toEqual({
255 amount: 8,
256 currency: 'CNY',
257 estimated: [],
258 })
259 // The wrapper changes the label, never the amount.
260 expect(price(parsed)).toBe(price(cardFor(doubleX)))
261 // A bare price is USD: a card stored before currencies reads unchanged.
262 expect(cardCurrency(cardFor(1))).toBe('USD')
263 expect(priceDetailed(cardFor(1))).toMatchObject({ currency: 'USD', usd: 1 })
264 })
265
266 it.each(['yuan', 'cny', '¥', 'RMBX', ''])(
267 'schema rejects %j as a currency',
268 (currency) => {
269 const card = { ...cardFor(1), price: { currency: [currency, 1] } }
270 expect(rateCardSchema.safeParse(card).success).toBe(false)
271 },
272 )
273
274 it('schema takes the currency wrapper at the root of price only', () => {
275 const nested = { '+': [1, { currency: ['CNY', 1] }] }
276 expect(
277 rateCardSchema.safeParse({ ...cardFor(1), price: nested }).success,
278 ).toBe(false)
279 const beside = { currency: ['CNY', 1], '+': [1, 2] }
280 expect(
281 rateCardSchema.safeParse({ ...cardFor(1), price: beside }).success,
282 ).toBe(false)
283 })
284
285 it('schema refuses a top-level currency rather than read the card as USD', () => {
286 for (const currency of ['CNY', 'USD', null, 156]) {
287 expect(
288 rateCardSchema.safeParse({ ...cardFor(1), currency }).success,
289 ).toBe(false)
290 }
291 })
292
293 it('schema refuses a USD wrapper: USD is said only by having none', () => {
294 const card = { ...cardFor(1), price: { currency: ['USD', 1] } }
295 expect(rateCardSchema.safeParse(card).success).toBe(false)
296 })
297
298 // Wrappers the schema refuses, handed to the evaluator unparsed.
299 it.each([
300 ['a lowercase code', { currency: ['cny', 1] }],
301 ['a numeric code', { currency: [156, 1] }],
302 ['USD', { currency: ['USD', 1] }],
303 ['three items', { currency: ['CNY', 1, 2] }],
304 ['a sibling op', { currency: ['CNY', 1], '+': [1, 2] }],
305 ['a bare code', { currency: 'CNY' }],
306 ['no price', undefined],
307 ['a null price', null],
308 ['a null wrapper payload', { currency: null }],
309 ['a null wrapped expression', { currency: ['CNY', null] }],
310 ])('evaluator refuses %s with its own error', (_name, bad) => {
311 const card = { ...cardFor(1), price: bad } as unknown as RateCard
312 expect(rateCardSchema.safeParse(card).success).toBe(false)
313 for (const read of [cardPrice, cardCurrency, price, priceDetailed]) {
314 expect(() => read(card)).toThrow(RateCardError)
315 expect(() => read(card)).toThrow(
316 expect.objectContaining({ code: 'unknown-op' }),
317 )
318 }
319 })
320
321 it('evaluator refuses a stray top-level currency on an unparsed card', () => {
322 const card = { ...cardFor(1), currency: 'CNY' } as unknown as RateCard
323 for (const read of [cardCurrency, price, priceDetailed]) {
324 expect(() => read(card)).toThrow(
325 expect.objectContaining({ code: 'unknown-op' }),
326 )
327 }
328 })
329
330 it('evaluator refuses a null card with its own error', () => {
331 expect(() => cardCurrency(null as unknown as RateCard)).toThrow(
332 RateCardError,
333 )
334 })
335
336 /**
337 * What @modelschemas/rate-card 0.1.0 (and a service rolled back to before
338 * currencies) does with an expression node: its schema accepts only the
339 * ops below, and its evaluator throws `unknown-op` on any other key. The
340 * op list is the published one, frozen here on purpose.
341 */
342 const OPS_0_1_0 = [
343 ...['var', 'missing', '+', '-', '*', '/', 'max', 'min', 'if'],
344 ...['==', '!=', '<', '<=', '>', '>=', 'and', 'or', 'ceil', 'floor'],
345 ]
346 const expr010: z.ZodType = z.lazy(() =>
347 z.union([
348 z.number(),
349 z.string(),
350 z.boolean(),
351 z.strictObject({ lookup: z.unknown() }),
352 z
353 .partialRecord(z.enum(OPS_0_1_0), z.union([expr010, z.array(expr010)]))
354 .refine((ops) => Object.keys(ops).length === 1, 'one op per node'),
355 ]),
356 )
357
358 it('a pre-currency evaluator refuses a non-USD card instead of calling it dollars', () => {
359 // It reads USD cards as before, so the reproduction is not just strict.
360 expect(expr010.safeParse(doubleX).success).toBe(true)
361 expect(expr010.safeParse(yuan.price).success).toBe(false)
362 // Its evaluator would throw `unknown-op` on the root key.
363 expect(Object.keys(yuan.price)).toEqual(['currency'])
364 expect(OPS_0_1_0).not.toContain('currency')
365 // The op must never become a core op, or old schemas that are handed
366 // the new list would start reading yuan as dollars.
367 expect(CORE_OPS).toEqual(OPS_0_1_0)
368 })
369
370 it('schema rejects an op outside the vocabulary', () => {
371 expect(rateCardSchema.safeParse(cardFor(unknownOp)).success).toBe(false)
372 })
373
374 it('schema rejects a lookup node carrying a sibling op (would be stripped silently)', () => {
375 const expr = JSON.parse(
376 '{"lookup":{"table":"t","keys":["a","p"]},"+":[1,2]}',
377 ) as Expr
378 expect(rateCardSchema.safeParse(cardFor(expr)).success).toBe(false)
379 })
380
381 it.each<[string, Partial<RateCard>]>([
382 [
383 'enum default outside values',
384 {
385 inputs: {
386 r: { param: 'r', kind: 'enum', values: ['a'], default: 'zzz' },
387 },
388 },
389 ],
390 [
391 'dimensions default that is not a preset',
392 {
393 inputs: {
394 s: { param: 's', kind: 'dimensions', presets: {}, default: 'nope' },
395 },
396 },
397 ],
398 [
399 'extractedAt that is not a date',
400 { source: { ...source, extractedAt: 'yesterday' } },
401 ],
402 [
403 'expiresAt that is not a date',
404 { source: { ...source, expiresAt: 'soon' } },
405 ],
406 ])('schema rejects %s', (_name, extra) => {
407 expect(rateCardSchema.safeParse(cardFor(1, extra)).success).toBe(false)
408 })
409})
410
411describe('verifyExamples', () => {
412 const expr: Expr = { '*': [{ var: 'x' }, 0.1] }
413 it('passes within 1% and fails outside it, reporting the priced USD', () => {
414 const card = cardFor(expr, {
415 examples: [
416 { params: { x: 10 }, usd: 1.0, quote: 'ten' },
417 { params: { x: 10 }, usd: 1.009, quote: 'ten-ish' },
418 { params: { x: 10 }, usd: 1.02, quote: 'not ten' },
419 ],
420 })
421 const [exact, close, off] = verifyExamples(card)
422 expect(exact).toMatchObject({ ok: true, usd: 1 })
423 expect(close).toMatchObject({ ok: true })
424 expect(off).toMatchObject({
425 ok: false,
426 usd: 1,
427 error: expect.stringContaining('1.02') as string,
428 })
429 })
430
431 it('reports a refusal as a failed example instead of throwing', () => {
432 const card = cardFor(expr, {
433 examples: [{ params: { x: 'many' }, usd: 1, quote: 'bad input' }],
434 })
435 expect(verifyExamples(card)[0]).toMatchObject({
436 ok: false,
437 error: expect.stringContaining('bad-input') as string,
438 })
439 })
440})
441
442describe('estimate', () => {
443 // rate × tokens; tokens estimated as seconds × per-second[resolution].
444 const card: RateCard = {
445 inputs: {
446 resolution: { param: 'resolution', kind: 'enum', values: ['480p'] },
447 tokens: {
448 param: 'tokens',
449 bound: 'usage',
450 kind: 'number',
451 estimate: {
452 inputs: { seconds: { param: 'seconds', kind: 'number' } },
453 value: {
454 '*': [
455 { var: 'seconds' },
456 {
457 lookup: { table: 'per_second', keys: [{ var: 'resolution' }] },
458 },
459 ],
460 },
461 source: { url: 'https://example.test/guide', hash: 'b'.repeat(64) },
462 },
463 },
464 },
465 tables: { per_second: { '480p': 1000 } },
466 price: { '*': [{ var: 'tokens' }, 0.001] },
467 examples: [],
468 source,
469 }
470
471 it('prices supplied usage as billed, without the estimate inputs', () => {
472 expect(rateCardSchema.parse(card)).toEqual(card)
473 expect(
474 priceDetailed(card, { resolution: '480p' }, { tokens: 500 }),
475 ).toEqual({ amount: 0.5, currency: 'USD', usd: 0.5, estimated: [] })
476 })
477
478 it('labels an estimated input and binds its own inputs only then', () => {
479 expect(priceDetailed(card, { resolution: '480p', seconds: 2 }, {})).toEqual(
480 { amount: 2, currency: 'USD', usd: 2, estimated: ['tokens'] },
481 )
482 expect(() => priceDetailed(card, { resolution: '480p' }, {})).toThrow(
483 /tokens \(tokens\): not supplied, and cannot be estimated.*seconds.*required/,
484 )
485 })
486
487 it('never estimates through price(), the billed entry point', () => {
488 expect(price(card, { resolution: '480p' }, { tokens: 500 })).toBe(0.5)
489 expect(() => price(card, { resolution: '480p', seconds: 2 }, {})).toThrow(
490 /tokens \(tokens\): required/,
491 )
492 })
493
494 it('refuses a non-positive estimate rather than pricing it', () => {
495 expect(() =>
496 priceDetailed(card, { resolution: '480p', seconds: -1 }, {}),
497 ).toThrow(
498 expect.objectContaining({ code: 'estimate-unavailable' }) as Error,
499 )
500 })
501
502 it('rejects an estimate beside a default, or shadowing a card input', () => {
503 const tokens = card.inputs.tokens
504 if (tokens?.kind !== 'number' || !tokens.estimate) throw new Error('shape')
505 const withDefault = {
506 ...card,
507 inputs: { ...card.inputs, tokens: { ...tokens, default: 1 } },
508 }
509 expect(rateCardSchema.safeParse(withDefault).success).toBe(false)
510 const shadowing = {
511 ...card,
512 inputs: {
513 ...card.inputs,
514 tokens: {
515 ...tokens,
516 estimate: {
517 ...tokens.estimate,
518 inputs: {
519 resolution: { param: 'resolution', kind: 'enum', values: ['1'] },
520 },
521 },
522 },
523 },
524 }
525 expect(rateCardSchema.safeParse(shadowing).success).toBe(false)
526 })
527})