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

rate-card-form.ts

183 lines6.4 KB

1/**
2 * Form state for the interactive rate card: one field per card input,
3 * seeded from the card's worked examples, turned back into the
4 * `{ request, usage }` pair `POST /v1/estimate` prices.
5 */
6import type { RateCard } from '@modelschemas/rate-card'
7​
8type CardInput = RateCard['inputs'][string]
9​
10/** Numbers stay strings while being edited; the estimator reports bad ones. */
11export type FieldValue = string | boolean | { width: string; height: string }
12​
13/** `$1.5` for USD, `CNY 1.5` for anything else (ISO-4217 code). */
14export function formatAmount(n: number, currency: string): string {
15 const symbol = currency === 'USD' ? '$' : `${currency} `
16 if (Number.isInteger(n)) return `${symbol}${String(n)}`
17 const fixed = n >= 0.01 ? n.toFixed(4) : n.toFixed(6)
18 return `${symbol}${fixed.replace(/0+$/, '').replace(/\.$/, '')}`
20​
21const TOKEN_DEFAULT = 1_000_000
22​
23const isRecord = (value: unknown): value is Record<string, unknown> =>
24 typeof value === 'object' && value !== null && !Array.isArray(value)
25​
26function seedField(input: CardInput, example: unknown): FieldValue {
27 switch (input.kind) {
28 case 'number': {
29 // A published estimate runs only when this value is omitted.
30 if (input.estimate && example === undefined) return ''
31 const value =
32 typeof example === 'number' || typeof example === 'string'
33 ? example
34 : (input.default ??
35 (input.param.endsWith('_tokens') ? TOKEN_DEFAULT : 1))
36 return String(value)
37 }
38 case 'count':
39 return String(Array.isArray(example) ? example.length : 1)
40 case 'boolean':
41 return typeof example === 'boolean' ? example : (input.default ?? false)
42 case 'enum':
43 if (
44 example === undefined &&
45 input.param === 'resolution' &&
46 input.default === undefined &&
47 input.values.includes('720p')
48 ) {
49 return '720p'
50 }
51 return typeof example === 'string' && input.values.includes(example)
52 ? example
53 : (input.default ?? input.values[0] ?? '')
54 case 'dimensions': {
55 if (isRecord(example)) {
56 return { width: String(example.width), height: String(example.height) }
57 }
58 const presets = input.presets ?? {}
59 const preset =
60 (typeof example === 'string' ? presets[example] : undefined) ??
61 (input.default !== undefined ? presets[input.default] : undefined) ??
62 Object.values(presets).at(0) ??
63 ([1024, 1024] as const)
64 return { width: String(preset[0]), height: String(preset[1]) }
65 }
66 }
68​
69/**
70 * Worked video examples on provider pages are 16:9 and 5 seconds. Those
71 * are form seeds only; omitting them on the API still refuses.
72 */
73function seedEstimateField(input: CardInput, example: unknown): FieldValue {
74 if (example === undefined && input.kind === 'enum') {
75 if (input.values.includes('16:9')) return '16:9'
76 }
77 if (
78 example === undefined &&
79 input.kind === 'number' &&
80 input.param === 'duration' &&
81 input.default === undefined
82 ) {
83 return '5'
84 }
85 return seedField(input, example)
87​
88export interface FormField {
89 name: string
90 input: CardInput
91 /** This field feeds an estimate of `estimates`, and is not itself billed. */
92 estimates?: string
94​
95/**
96 * Fields the calculator draws. Estimate inputs (duration, ratio) sit in
97 * front of the number they fill.
98 */
99export function formFields(inputs: RateCard['inputs']): FormField[] {
100 const fields: FormField[] = []
101 for (const [name, input] of Object.entries(inputs)) {
102 if (input.kind === 'number' && input.estimate) {
103 for (const [ename, einput] of Object.entries(input.estimate.inputs)) {
104 fields.push({ name: ename, input: einput, estimates: input.param })
105 }
106 }
107 fields.push({ name, input })
108 }
109 return fields
111​
112/** Seed every input from the example that sets the most of them. */
113export function seedValues(
114 card: Pick<RateCard, 'inputs' | 'examples'>,
115): Record<string, FieldValue> {
116 const params = Object.values(card.inputs).map((input) => input.param)
117 const covered = (example: RateCard['examples'][number]) =>
118 params.filter((param) => param in example.params).length
119 const best = card.examples.reduce<RateCard['examples'][number] | undefined>(
120 (top, example) =>
121 top === undefined || covered(example) > covered(top) ? example : top,
122 undefined,
123 )
124 const values: Record<string, FieldValue> = Object.fromEntries(
125 Object.entries(card.inputs).map(([name, input]) => [
126 name,
127 seedField(input, best?.params[input.param]),
128 ]),
129 )
130 for (const input of Object.values(card.inputs)) {
131 if (input.kind !== 'number' || !input.estimate) continue
132 for (const [name, einput] of Object.entries(input.estimate.inputs)) {
133 values[name] = seedEstimateField(einput, best?.params[einput.param])
134 }
135 }
136 return values
138​
139// ponytail: lists past this are sent raw and refused, not built in memory.
140const MAX_COUNT = 1000
141​
142/**
143 * `count` prices a list's length; the items are never read. Anything but a
144 * whole number up to MAX_COUNT goes through as-is so the estimator refuses
145 * it ("expected a list") instead of pricing a guessed length.
146 */
147function countList(value: FieldValue): unknown {
148 if (typeof value !== 'string' || !/^\d+$/.test(value)) return value
149 const length = Number(value)
150 return length <= MAX_COUNT ? Array.from({ length }, () => '') : value
152​
153function assign(
154 slot: Record<string, unknown>,
155 input: CardInput,
156 value: FieldValue,
157): void {
158 // Blank means omitted, so a published estimate can run.
159 if (input.kind === 'number' && value === '') return
160 slot[input.param] = input.kind === 'count' ? countList(value) : value
162​
163/** Split field values into the estimate body's request/usage slots. */
164export function toEstimateParts(
165 inputs: RateCard['inputs'],
166 values: Record<string, FieldValue>,
167): { request: Record<string, unknown>; usage: Record<string, unknown> } {
168 const request: Record<string, unknown> = {}
169 const usage: Record<string, unknown> = {}
170 for (const [name, input] of Object.entries(inputs)) {
171 const value = values[name]
172 if (value !== undefined) {
173 assign(input.bound === 'usage' ? usage : request, input, value)
174 }
175 if (input.kind !== 'number' || !input.estimate) continue
176 for (const [ename, einput] of Object.entries(input.estimate.inputs)) {
177 const estimated = values[ename]
178 if (estimated === undefined) continue
179 assign(einput.bound === 'usage' ? usage : request, einput, estimated)
180 }
181 }
182 return { request, usage }