Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2
3import { verifyExamples } from '@modelschemas/rate-card'
4
5import { NANO_BANANA_2 } from '../../../packages/rate-card/src/fixtures/nano-banana-2.ts'
6
7import {
8 FAL_PRICING_EXTRACT_CRONS,
9 FAL_PRICING_EXTRACT_CAP,
10 FAL_PRICING_EXTRACT_MODEL,
11 FAL_PRICING_FETCH_CAP,
12 FAL_PRICING_FETCH_FAIL_ABORT,
13 checkExtractedCard,
14 isRetryableLlmsStatus,
15 extractRateCardWithGrok,
16 isStubPricingSection,
17 pricingSection,
18 pricingSectionHash,
19 resumeIndex,
20 shouldSkipExtract,
21} from './extract-fal-pricing.ts'
22import { parseFalUnitRate } from './fal-unit-rate.ts'
23import { SPEC_SYNC_SHARD_CRONS } from './sync.ts'
24
25/** A fetch mock answering successive chat calls with these contents. */
26function grokReplies(...replies: Array<unknown>) {
27 const mock = vi.fn<typeof fetch>()
28 for (const reply of replies) {
29 const content = typeof reply === 'string' ? reply : JSON.stringify(reply)
30 mock.mockResolvedValueOnce(
31 new Response(JSON.stringify({ choices: [{ message: { content } }] }), {
32 status: 200,
33 }),
34 )
35 }
36 return mock
37}
38
39const NANO_LLMS = `# Nano Banana 2
40
41## Overview
42
43- **Endpoint**: \`https://fal.run/fal-ai/nano-banana-2\`
44
45## Pricing
46
47Your request will cost **$0.08** per image. For **$1.00**, you can run this model **12** times. 2K and 4K outputs will be charged at **1.5** times and **2** times the standard rate, respectively. 0.5K (512px) resolution outputs will be charged at **0.75** times the standard rate. If web search is used, an additional $0.015 will be charged. If high thinking is used, an additional $0.002 will be charged. **Note: Pricing is subject to change.**
48
49For more details, see [fal.ai pricing](https://fal.ai/pricing).
50
51## API Information
52
53This model can be used via our HTTP API.
54`
55
56describe('pricingSection', () => {
57 it('cuts the Pricing heading from llms.txt and ignores sibling sections', () => {
58 const section = pricingSection(NANO_LLMS)
59 expect(section.startsWith('## Pricing')).toBe(true)
60 expect(section).toContain('$0.08')
61 expect(section).not.toContain('API Information')
62 expect(section).not.toContain('Nano Banana 2 is')
63 })
64
65 it('is empty when the heading is absent', () => {
66 expect(pricingSection('# Title\n\n## Overview\n\nNope.\n')).toBe('')
67 })
68})
69
70describe('isStubPricingSection', () => {
71 it('treats empty, boilerplate, and zero-dollar sections as stubs', () => {
72 expect(isStubPricingSection('')).toBe(true)
73 expect(
74 isStubPricingSection(
75 '## Pricing\n\nFor more details, see [fal.ai pricing](https://fal.ai/pricing).',
76 ),
77 ).toBe(true)
78 expect(
79 isStubPricingSection(
80 '## Pricing\n\nYour request will cost **$0.00** per image.',
81 ),
82 ).toBe(true)
83 })
84
85 it('keeps a section that names a positive price', () => {
86 expect(isStubPricingSection(pricingSection(NANO_LLMS))).toBe(false)
87 })
88
89 it('keeps bold and suffix-$ prices the old regex missed (#70)', () => {
90 expect(isStubPricingSection('- **Price**: $**0.04** per images')).toBe(
91 false,
92 )
93 expect(isStubPricingSection('- **Price**: **0.17** $ per second')).toBe(
94 false,
95 )
96 })
97})
98
99describe('pricingSectionHash', () => {
100 it('hashes the Pricing section, not the rest of the file', async () => {
101 const a = await pricingSectionHash(pricingSection(NANO_LLMS))
102 const b = await pricingSectionHash(
103 pricingSection(NANO_LLMS.replace('Nano Banana 2', 'Renamed')),
104 )
105 const c = await pricingSectionHash(
106 pricingSection(NANO_LLMS.replace('$0.08', '$0.09')),
107 )
108 expect(a).toMatch(/^[0-9a-f]{64}$/)
109 expect(a).toBe(b)
110 expect(c).not.toBe(a)
111 })
112})
113
114describe('resumeIndex', () => {
115 const ids = ['a/one', 'b/two', 'c/three']
116
117 it('starts at 0 with no cursor and wraps past the tail', () => {
118 expect(resumeIndex(ids, null)).toBe(0)
119 expect(resumeIndex(ids, 'c/three')).toBe(0)
120 expect(resumeIndex(ids, 'b/two')).toBe(2)
121 })
122
123 it('resumes after a cursor that left the roster', () => {
124 expect(resumeIndex(ids, 'a/two')).toBe(1)
125 expect(resumeIndex(ids, 'z/gone')).toBe(0)
126 })
127})
128
129describe('shouldSkipExtract', () => {
130 const hash = 'a'.repeat(64)
131 const now = 1_781_150_000
132
133 it('skips an unchanged hash and re-extracts after expiresAt', () => {
134 expect(
135 shouldSkipExtract({
136 storedHash: hash,
137 sectionHash: hash,
138 hasCard: true,
139 stub: false,
140 expiresAt: undefined,
141 now,
142 }),
143 ).toBe(true)
144 expect(
145 shouldSkipExtract({
146 storedHash: hash,
147 sectionHash: 'b'.repeat(64),
148 hasCard: true,
149 stub: false,
150 expiresAt: undefined,
151 now,
152 }),
153 ).toBe(false)
154 expect(
155 shouldSkipExtract({
156 storedHash: hash,
157 sectionHash: hash,
158 hasCard: true,
159 stub: false,
160 expiresAt: '2020-01-01T00:00:00.000Z',
161 now,
162 }),
163 ).toBe(false)
164 expect(
165 shouldSkipExtract({
166 storedHash: hash,
167 sectionHash: hash,
168 hasCard: true,
169 stub: false,
170 expiresAt: '2099-01-01T00:00:00.000Z',
171 now,
172 }),
173 ).toBe(true)
174 })
175
176 it('retries an unchanged hash whose card is still null unless it is a stub (#84)', () => {
177 const base = { storedHash: hash, sectionHash: hash, expiresAt: undefined }
178 expect(
179 shouldSkipExtract({ ...base, hasCard: false, stub: false, now }),
180 ).toBe(false)
181 expect(
182 shouldSkipExtract({ ...base, hasCard: false, stub: true, now }),
183 ).toBe(true)
184 })
185})
186
187describe('FAL_PRICING_EXTRACT_CRONS', () => {
188 it('is six hourly daytime shards, none of them a spec-sync shard', () => {
189 expect([...FAL_PRICING_EXTRACT_CRONS]).toEqual([
190 '0 6 * * *',
191 '0 7 * * *',
192 '0 8 * * *',
193 '0 9 * * *',
194 '0 10 * * *',
195 '0 11 * * *',
196 ])
197 expect(FAL_PRICING_FETCH_CAP).toBe(250)
198 expect(FAL_PRICING_EXTRACT_CAP).toBe(40)
199 expect(FAL_PRICING_FETCH_FAIL_ABORT).toBe(8)
200 expect(FAL_PRICING_EXTRACT_MODEL).toBe('grok-4-fast')
201 for (const cron of FAL_PRICING_EXTRACT_CRONS) {
202 expect(
203 (SPEC_SYNC_SHARD_CRONS as ReadonlyArray<string>).includes(cron),
204 ).toBe(false)
205 expect(cron).not.toBe('*/15 * * * *')
206 }
207 // Six shards x 250 fetches covers the FAL roster in one calendar day.
208 expect(
209 FAL_PRICING_EXTRACT_CRONS.length * FAL_PRICING_FETCH_CAP,
210 ).toBeGreaterThanOrEqual(1500)
211 })
212
213 it('keeps wrangler.jsonc in lockstep', async () => {
214 const fs = await import('node:fs/promises')
215 const raw = await fs.readFile('wrangler.jsonc', 'utf8')
216 for (const cron of FAL_PRICING_EXTRACT_CRONS) {
217 expect(raw).toContain(`"${cron}"`)
218 }
219 expect(raw).toContain('"*/15 * * * *"')
220 for (const cron of SPEC_SYNC_SHARD_CRONS) {
221 expect(raw).toContain(`"${cron}"`)
222 }
223 })
224})
225
226describe('isRetryableLlmsStatus', () => {
227 it('retries network, 408, 429, and 5xx; 404 is done', () => {
228 expect(isRetryableLlmsStatus(0)).toBe(true)
229 expect(isRetryableLlmsStatus(408)).toBe(true)
230 expect(isRetryableLlmsStatus(429)).toBe(true)
231 expect(isRetryableLlmsStatus(500)).toBe(true)
232 expect(isRetryableLlmsStatus(503)).toBe(true)
233 expect(isRetryableLlmsStatus(404)).toBe(false)
234 expect(isRetryableLlmsStatus(400)).toBe(false)
235 })
236})
237
238async function extractError(
239 args: Parameters<typeof extractRateCardWithGrok>[0],
240): Promise<string | null> {
241 const result = await extractRateCardWithGrok(args)
242 return typeof result === 'object' && 'error' in result ? result.error : null
243}
244
245describe('extractRateCardWithGrok', () => {
246 const args = {
247 pricingText: pricingSection(NANO_LLMS),
248 requestProperties: new Set([
249 'num_images',
250 'resolution',
251 'enable_web_search',
252 'thinking_level',
253 ]),
254 sourceUrl: NANO_BANANA_2.source.url,
255 sourceHash: 'c'.repeat(64),
256 now: 1_781_150_000,
257 apiKey: 'xai-test',
258 }
259
260 it('stamps source and accepts a verified card', async () => {
261 const { source: _source, ...body } = NANO_BANANA_2
262 const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(
263 new Response(
264 JSON.stringify({
265 choices: [{ message: { content: JSON.stringify(body) } }],
266 }),
267 { status: 200 },
268 ),
269 )
270 vi.stubGlobal('fetch', fetchMock)
271 try {
272 const card = await extractRateCardWithGrok(args)
273 expect(card).not.toBe('unverified')
274 expect(card).not.toHaveProperty('error')
275 if (card === 'unverified' || 'error' in card) return
276 expect(card.source.hash).toBe(args.sourceHash)
277 expect(card.source.url).toBe(args.sourceUrl)
278 expect(fetchMock.mock.calls[0]?.[0]).toBe(
279 'https://api.x.ai/v1/chat/completions',
280 )
281 const init = fetchMock.mock.calls[0]?.[1]
282 expect(init?.method).toBe('POST')
283 const payload = JSON.parse(String(init?.body)) as {
284 model: string
285 }
286 expect(payload.model).toBe(FAL_PRICING_EXTRACT_MODEL)
287 } finally {
288 vi.unstubAllGlobals()
289 }
290 })
291
292 it('returns unverified only for a section that names no price', async () => {
293 const fetchMock = grokReplies({ unverified: true })
294 vi.stubGlobal('fetch', fetchMock)
295 try {
296 await expect(
297 extractRateCardWithGrok({
298 ...args,
299 pricingText:
300 '## Pricing\n\nSee [fal.ai pricing](https://fal.ai/pricing).',
301 }),
302 ).resolves.toBe('unverified')
303 expect(fetchMock).toHaveBeenCalledTimes(1)
304 } finally {
305 vi.unstubAllGlobals()
306 }
307 })
308
309 it('sends a priced section back once when the model says unverified (#88)', async () => {
310 const { source: _source, ...body } = NANO_BANANA_2
311 const fetchMock = grokReplies({ unverified: true }, body)
312 vi.stubGlobal('fetch', fetchMock)
313 try {
314 const card = await extractRateCardWithGrok(args)
315 expect(card).toMatchObject({ price: NANO_BANANA_2.price })
316 expect(fetchMock).toHaveBeenCalledTimes(2)
317 const retry = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body)) as {
318 model: string
319 messages: Array<{ role: string; content: string }>
320 }
321 expect(retry.model).toBe(FAL_PRICING_EXTRACT_MODEL)
322 expect(retry.messages.map((m) => m.role)).toEqual([
323 'system',
324 'user',
325 'assistant',
326 'user',
327 ])
328 expect(retry.messages[3]?.content).toContain('$0.08')
329 } finally {
330 vi.unstubAllGlobals()
331 }
332 })
333
334 it('returns the rejection when a priced section is refused twice', async () => {
335 const { source: _source, ...body } = NANO_BANANA_2
336 for (const reply of [{ unverified: true }, { ...body, examples: [] }]) {
337 const fetchMock = grokReplies(reply, reply)
338 vi.stubGlobal('fetch', fetchMock)
339 try {
340 expect(await extractError(args)).toMatch(
341 /^rejected twice: the section names/,
342 )
343 expect(fetchMock).toHaveBeenCalledTimes(2)
344 } finally {
345 vi.unstubAllGlobals()
346 }
347 }
348 })
349
350 it('returns the rejection when verifyExamples fails on both turns', async () => {
351 const { source: _source, examples, ...body } = NANO_BANANA_2
352 const first = examples[0]
353 const bad = {
354 ...body,
355 examples: first
356 ? [{ ...first, usd: 999 }]
357 : [{ params: {}, usd: 999, quote: 'nope' }],
358 }
359 const fetchMock = grokReplies(bad, bad)
360 vi.stubGlobal('fetch', fetchMock)
361 try {
362 expect(await extractError(args)).toMatch(
363 /^rejected twice: verifyExamples failed/,
364 )
365 const retry = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body)) as {
366 messages: Array<{ content: string }>
367 }
368 expect(retry.messages[3]?.content).toContain('verifyExamples failed')
369 } finally {
370 vi.unstubAllGlobals()
371 }
372 })
373
374 it('rejects a request-bound param the input schema does not have', async () => {
375 const { source: _source, ...body } = NANO_BANANA_2
376 const invented = {
377 ...body,
378 inputs: {
379 ...body.inputs,
380 num_images: { param: 'image_count', kind: 'number', default: 1 },
381 },
382 }
383 vi.stubGlobal('fetch', grokReplies(invented, invented))
384 try {
385 expect(await extractError(args)).toMatch(
386 /^rejected twice: a request-bound/,
387 )
388 } finally {
389 vi.unstubAllGlobals()
390 }
391 })
392
393 it('fails closed on a non-card payload', async () => {
394 vi.stubGlobal('fetch', grokReplies({ nope: true }, 'not json'))
395 try {
396 await expect(extractRateCardWithGrok(args)).resolves.toEqual({
397 error: 'rejected twice: reply is not JSON',
398 })
399 } finally {
400 vi.unstubAllGlobals()
401 }
402 })
403
404 it('returns the thrown message when the call throws (#394)', async () => {
405 vi.stubGlobal(
406 'fetch',
407 vi.fn<typeof fetch>().mockRejectedValue(new Error('network down')),
408 )
409 try {
410 await expect(extractRateCardWithGrok(args)).resolves.toEqual({
411 error: 'network down',
412 })
413 } finally {
414 vi.unstubAllGlobals()
415 }
416 })
417
418 it('returns the xAI status and body when the call fails (#394)', async () => {
419 const fetchMock = vi
420 .fn<typeof fetch>()
421 .mockResolvedValue(
422 new Response('{"error":"rate limited"}', { status: 429 }),
423 )
424 vi.stubGlobal('fetch', fetchMock)
425 try {
426 await expect(extractRateCardWithGrok(args)).resolves.toEqual({
427 error: 'xai 429: {"error":"rate limited"}',
428 })
429 expect(fetchMock).toHaveBeenCalledTimes(1)
430 } finally {
431 vi.unstubAllGlobals()
432 }
433 })
434})
435
436describe('checkExtractedCard', () => {
437 const base = {
438 requestProperties: new Set(['resolution', 'duration']),
439 sourceUrl:
440 'https://fal.ai/models/fal-ai/wan-25-preview/text-to-video/llms.txt',
441 sourceHash: 'd'.repeat(64),
442 now: 1_781_150_000,
443 }
444
445 /** Live fal-ai/wan-25-preview/text-to-video, read 2026-09-30. */
446 const WAN_TABLE = `## Pricing
447
448Your request will cost **$0.05** per second for **480p**, **$0.10** per second for **720p**, **$0.15** per second for **1080p**.
449
450For more details, see [fal.ai pricing](https://fal.ai/pricing).`
451
452 it('accepts a lookup calculator for a per-second resolution table', () => {
453 // The fast path refuses several rates by design — this is leftover work.
454 expect(parseFalUnitRate(WAN_TABLE)).toBeNull()
455 const reply = {
456 inputs: {
457 resolution: {
458 param: 'resolution',
459 kind: 'enum',
460 bound: 'request',
461 values: ['480p', '720p', '1080p'],
462 default: '1080p',
463 },
464 seconds: { param: 'seconds', kind: 'number', bound: 'usage' },
465 },
466 tables: { rate: { '480p': 0.05, '720p': 0.1, '1080p': 0.15 } },
467 price: {
468 '*': [
469 { var: 'seconds' },
470 { lookup: { table: 'rate', keys: [{ var: 'resolution' }] } },
471 ],
472 },
473 examples: [
474 {
475 params: { resolution: '480p', seconds: 1 },
476 usd: 0.05,
477 quote: 'Your request will cost **$0.05** per second for **480p**',
478 },
479 {
480 params: { resolution: '720p', seconds: 1 },
481 usd: 0.1,
482 quote: '**$0.10** per second for **720p**',
483 },
484 {
485 params: { seconds: 1 },
486 usd: 0.15,
487 quote: '**$0.15** per second for **1080p**',
488 },
489 ],
490 }
491 const card = checkExtractedCard(JSON.stringify(reply), {
492 ...base,
493 pricingText: WAN_TABLE,
494 })
495 if (card === 'unverified' || 'error' in card) {
496 throw new Error(JSON.stringify(card))
497 }
498 expect(card.source.hash).toBe(base.sourceHash)
499 expect(verifyExamples(card).every((r) => r.ok)).toBe(true)
500 expect(card.price).toMatchObject({
501 '*': [{ var: 'seconds' }, { lookup: {} }],
502 })
503 })
504
505 // #304: live grok-4-fast reply for xai/grok-imagine-video/extend-video,
506 // whose request has no resolution field.
507 it('refuses a usage-bound input with a default', () => {
508 const reply = {
509 inputs: {
510 resolution: {
511 param: 'resolution',
512 bound: 'usage',
513 kind: 'enum',
514 values: ['480p', '720p'],
515 default: '480p',
516 },
517 seconds: { param: 'seconds', bound: 'usage', kind: 'number' },
518 },
519 tables: { rate: { '480p': 0.05, '720p': 0.07 } },
520 price: {
521 '*': [
522 { var: 'seconds' },
523 { lookup: { table: 'rate', keys: [{ var: 'resolution' }] } },
524 ],
525 },
526 examples: [
527 {
528 params: { resolution: '480p', seconds: 1 },
529 usd: 0.05,
530 quote: 'Cost is **$0.05** per second of 480p output video',
531 },
532 ],
533 }
534 const pricingText =
535 '## Pricing\n\nCost is **$0.05** per second of 480p output video (**$0.07** at 720p).'
536 const refused = checkExtractedCard(JSON.stringify(reply), {
537 ...base,
538 requestProperties: new Set(['prompt']),
539 pricingText,
540 })
541 expect(
542 typeof refused === 'object' && 'error' in refused && refused.error,
543 ).toContain('usage-bound enums have a default (resolution)')
544 const { default: _default, ...resolution } = reply.inputs.resolution
545 const card = checkExtractedCard(
546 JSON.stringify({ ...reply, inputs: { ...reply.inputs, resolution } }),
547 { ...base, requestProperties: new Set(['prompt']), pricingText },
548 )
549 expect(typeof card === 'object' && 'inputs' in card).toBe(true)
550 })
551
552 it('refuses unverified for the table but allows it for a zero-price stub', () => {
553 const refused = checkExtractedCard('{"unverified":true}', {
554 ...base,
555 pricingText: WAN_TABLE,
556 })
557 expect(
558 typeof refused === 'object' && 'error' in refused && refused.error,
559 ).toContain('$0.05')
560 expect(
561 checkExtractedCard('{"unverified":true}', {
562 ...base,
563 pricingText:
564 '## Pricing\n\nYour request will cost **$0.00** per image.',
565 }),
566 ).toBe('unverified')
567 })
568})