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

card.ts

187 lines5.9 KB

1/**
2 * The rate-card expression language as plain TypeScript: the types, the
3 * closed op set and the currency wrapper rule. No runtime dependencies, so
4 * the evaluator runs on any edge runtime. `rate-card.schema.ts` is the zod
5 * schema for the same shape; a type test keeps the two equal.
6 */
7​
8/**
9 * The version of the card language this package reads. The package's
10 * MAJOR.MINOR version is this version: a change to what a card can say (a
11 * new op, a new wrapper) bumps both, and a fix that reads the same cards is
12 * a patch release.
13 *
14 * - `0.1`: the core ops, `lookup` and input `estimate`s. USD only.
15 * - `0.2`: the `{ currency: [code, expr] }` price wrapper.
16 */
17export const RATE_CARD_LANGUAGE = '0.2'
18​
19export const CORE_OPS = [
20 'var',
21 'missing',
22 '+',
23 '-',
24 '*',
25 '/',
26 'max',
27 'min',
28 'if',
29 '==',
30 '!=',
31 '<',
32 '<=',
33 '>',
34 '>=',
35 'and',
36 'or',
37 'ceil',
38 'floor',
39] as const
40​
41export type CoreOp = (typeof CORE_OPS)[number]
42​
43export type Expr =
44 | number
45 | string
46 | boolean
47 | { lookup: { table: string; keys: Expr[]; default?: Expr } }
48 | { [op in CoreOp]?: Expr | Expr[] }
49​
50/** Nested numeric lookup: `tables.rate['720p'].video` → number. */
51export type Table = { [key: string]: number | Table }
52​
53type InputBase = {
54 /**
55 * Request-body or usage-object field this lever reads (`image_urls`).
56 * JSONLogic `{ var }` uses the input's object key, which may differ.
57 */
58 param: string
59 /**
60 * Where `price` reads `param` from: a real request-body field
61 * (`duration`, `image_size`; the default) or a usage quantity the caller
62 * supplies because it is not on the request (`input_tokens`).
63 */
64 bound?: 'request' | 'usage'
66​
67/** sha256 of fetched source text, plus where it came from. */
68type SourceRef = { url: string; hash: string }
69​
70/** An input kind every input shares. Only a card input has an `estimate`. */
71export type RateCardPlainInput =
72 | (InputBase & { kind: 'number'; default?: number })
73 | (InputBase & { kind: 'enum'; values: string[]; default?: string })
74 | (InputBase & { kind: 'boolean'; default?: boolean })
75 /** Length of a list param (`image_urls`), 0 when absent. */
76 | (InputBase & { kind: 'count' })
77 /**
78 * `{width, height}`, a `WxH` string or a preset name; binds
79 * `<name>.width` / `<name>.height`. A `levels` name (Ark's `2K`, sized
80 * by the provider) binds `<name>.level` instead, with no width or height.
81 */
82 | (InputBase & {
83 kind: 'dimensions'
84 presets?: Record<string, [number, number]>
85 levels?: string[]
86 default?: string
87 })
88​
89/**
90 * A source-published way to estimate a number the caller did not supply
91 * (`completion_tokens` from resolution × ratio × duration). Used only when
92 * the input is absent; the result then names the input as estimated, never
93 * as a billed price. `inputs` bind only on that path, so a caller who
94 * supplies the real number is not asked for them. `value` also reads the
95 * card's own bound inputs; estimate input names may not repeat them, and
96 * an input with an estimate has no `default` (which would silently win).
97 */
98export type RateCardEstimate = {
99 inputs: Record<string, RateCardPlainInput>
100 value: Expr
101 /** The text the estimate method was read from. */
102 source: SourceRef
104​
105export type RateCardInput =
106 | Exclude<RateCardPlainInput, { kind: 'number' }>
107 | (InputBase & {
108 kind: 'number'
109 default?: number
110 estimate?: RateCardEstimate
111 })
112​
113export type RateCardExample = {
114 /**
115 * Flat bag of request-body fields plus usage quantities, keyed by each
116 * input's `param`. `verifyExamples` feeds it as both `request` and `usage`.
117 */
118 params: Record<string, unknown>
119 /** In the card's currency; the name predates `currency`. */
120 usd: number
121 /** The sentence in the source text this example comes from. */
122 quote: string
124​
125/**
126 * JSONLogic yielding the amount for one request: USD, or, wrapped as
127 * `{ currency: ['CNY', expr] }`, the ISO-4217 currency named. The wrapper
128 * is the only place a card states a currency, so a USD card is exactly
129 * what it was before cards had one.
130 *
131 * `currency` is deliberately not a core op. An evaluator that predates it
132 * (0.1.0, or a rolled-back service) fails to parse the card and throws
133 * `unknown-op` on its price, so it refuses a yuan amount instead of
134 * reporting it as dollars. Amounts in different currencies are never
135 * added, compared or converted.
136 */
137export type RateCardPrice = { currency: [string, Expr] } | Expr
138​
139export type RateCard = {
140 /**
141 * Not a field. A card that states its currency here instead of wrapping
142 * `price` is refused, never read as USD.
143 */
144 currency?: undefined
145 inputs: Record<string, RateCardInput>
146 tables: Record<string, Table>
147 price: RateCardPrice
148 examples: RateCardExample[]
149 source: {
150 url: string
151 /** sha256 of the source text the card was read from. */
152 hash: string
153 /** ISO date-time. */
154 extractedAt: string
155 /** When the text names a promo end — re-extract after this. */
156 expiresAt?: string
157 }
159​
160/**
161 * The one rule for a price's currency wrapper, shared by the schema and
162 * the evaluator: `null` for a bare (USD) price, the code and inner
163 * expression for `{ currency: ['CNY', expr] }`, `'malformed'` for anything
164 * else carrying a `currency` key. The code is three capitals and never
165 * `USD`: USD is said only by having no wrapper, so a USD card can never
166 * become one that 0.1.0 refuses.
167 */
168export function currencyWrapper(
169 price: unknown,
170): { currency: string; expr: unknown } | null | 'malformed' {
171 if (typeof price !== 'object' || price === null || !('currency' in price)) {
172 return null
173 }
174 const pair = price.currency
175 if (
176 Object.keys(price).length !== 1 ||
177 !Array.isArray(pair) ||
178 pair.length !== 2 ||
179 typeof pair[0] !== 'string' ||
180 !/^[A-Z]{3}$/.test(pair[0]) ||
181 pair[0] === 'USD' ||
182 pair[1] == null
183 ) {
184 return 'malformed'
185 }
186 return { currency: pair[0], expr: pair[1] }