Open History to see the last commit
1/**
2 * Kling list prices from https://kling.ai/dev/pricing (issue #122). The
3 * page embeds an English price table as JSON. A single dollar amount
4 * becomes a card. Two different amounts for one catalog id, or a model
5 * the table does not name, stays unpriced. 4K is not a `mode` value
6 * (`std` is 720p, `pro` is 1080p), so it is not a key on the card.
7 */
8import { compileUnitCard } from '@modelschemas/rate-card'
9import type { UnitCardSpec } from '@modelschemas/rate-card'
10
11import { tagDocsFacts } from './fact-sources.ts'
12import { assertParsed, cachedDocs } from './model-facts.ts'
13import { fetchText, sha256Text } from './types.ts'
14import type { ModelInfo } from './types.ts'
15
16export const KLING_PRICING_URL = 'https://kling.ai/dev/pricing'
17
18/** Display name on the pricing page → catalog raw id, when that is 1:1. */
19const CATALOG_IDS: Record<string, string> = {
20 'Kling Image O1': 'kling-image-o1',
21 'Kling 3.0': 'kling-v3',
22}
23
24const DOLLARS = /\$(\d+(?:\.\d+)?)\)/
25
26interface ImageRow {
27 model?: string
28 price?: string | Array<string>
29}
30
31interface VideoRow {
32 model?: string
33 spec?: string
34 function?: string | Array<string>
35 p720?: string | Array<string>
36 p1080?: string | Array<string>
37}
38
39interface KlingPage {
40 en?: {
41 newImageApi?: {
42 main?: { list?: Array<{ table?: { data?: Array<ImageRow> } }> }
43 }
44 newVideoApi?: {
45 main?: { list?: Array<{ table?: { data?: Array<VideoRow> } }> }
46 }
47 }
48}
49
50function dollars(cell: string | undefined): number | null {
51 const match = cell?.match(DOLLARS)?.[1]
52 return match === undefined ? null : Number(match)
53}
54
55function asList(value: string | Array<string> | undefined): Array<string> {
56 if (value === undefined) return []
57 return Array.isArray(value) ? value : [value]
58}
59
60/** One shared per-image price, or null when the row quotes more than one. */
61function imageRate(row: ImageRow): number | null {
62 const amounts = asList(row.price)
63 .map((cell) => dollars(cell))
64 .filter((amount): amount is number => amount !== null)
65 if (amounts.length === 0) return null
66 return amounts.every((amount) => amount === amounts[0])
67 ? (amounts[0] ?? null)
68 : null
69}
70
71/**
72 * `mode` × `sound` per-second rates. Null unless both published features
73 * have a 720p and a 1080p dollar amount and no further feature is priced.
74 */
75function videoSpec(row: VideoRow): UnitCardSpec | null {
76 if (row.spec !== 'Per second') return null
77 const features = asList(row.function)
78 const p720 = asList(row.p720)
79 const p1080 = asList(row.p1080)
80 if (features.length !== 2 || p720.length !== 2 || p1080.length !== 2) {
81 return null
82 }
83 const rates: Partial<Record<'off' | 'on', { std: number; pro: number }>> = {}
84 for (const [index, feature] of features.entries()) {
85 const sound =
86 feature === 'No Native Audio'
87 ? 'off'
88 : feature === 'With Native Audio x No Voice Control'
89 ? 'on'
90 : null
91 const std = dollars(p720[index])
92 const pro = dollars(p1080[index])
93 if (sound === null || std === null || pro === null) return null
94 rates[sound] = { std, pro }
95 }
96 const off = rates.off
97 const on = rates.on
98 if (!off || !on) return null
99 return {
100 quantity: { param: 'duration', bound: 'request' },
101 keys: [
102 { param: 'sound', values: ['off', 'on'], default: 'off' },
103 { param: 'mode', values: ['std', 'pro'], default: 'std' },
104 ],
105 rates: {
106 off: { std: off.std, pro: off.pro },
107 on: { std: on.std, pro: on.pro },
108 },
109 }
110}
111
112function pageJson(text: string): KlingPage | null {
113 const trimmed = text.trim()
114 if (trimmed.startsWith('{')) {
115 return JSON.parse(trimmed) as KlingPage
116 }
117 const marker = text.indexOf('devModelPageInfo')
118 const brace = marker < 0 ? -1 : text.indexOf('{', marker)
119 if (brace < 0) return null
120 let depth = 0
121 for (let index = brace; index < text.length; index++) {
122 const char = text[index]
123 if (char === '{') depth++
124 else if (char === '}') {
125 depth--
126 if (depth === 0) {
127 return JSON.parse(text.slice(brace, index + 1)) as KlingPage
128 }
129 }
130 }
131 return null
132}
133
134/** Catalog id → unit sheet. Ids the page does not price once are absent. */
135export function parseKlingPricing(page: string): Map<string, UnitCardSpec> {
136 const parsed = pageJson(page)
137 const out = new Map<string, UnitCardSpec>()
138 const images =
139 parsed?.en?.newImageApi?.main?.list?.flatMap(
140 (block) => block.table?.data ?? [],
141 ) ?? []
142 for (const row of images) {
143 const id = row.model ? CATALOG_IDS[row.model] : undefined
144 const rate = imageRate(row)
145 if (!id || rate === null || out.has(id)) continue
146 out.set(id, {
147 quantity: { param: 'n', bound: 'request', default: 1 },
148 rates: rate,
149 })
150 }
151 const videos =
152 parsed?.en?.newVideoApi?.main?.list?.flatMap(
153 (block) => block.table?.data ?? [],
154 ) ?? []
155 for (const row of videos) {
156 const id = row.model ? CATALOG_IDS[row.model] : undefined
157 const spec = videoSpec(row)
158 if (!id || !spec || out.has(id)) continue
159 out.set(id, spec)
160 }
161 return out
162}
163
164type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
165
166/** Card lookup by listed model id. */
167export async function klingModelPricing(
168 kv?: KVNamespace,
169): Promise<(rawId: string) => PricedFacts> {
170 const doc = await cachedDocs(kv, KLING_PRICING_URL, async () => {
171 const page = await fetchText(KLING_PRICING_URL)
172 const parsed = parseKlingPricing(page)
173 assertParsed(parsed, 'kling pricing page')
174 return {
175 rates: Object.fromEntries(parsed),
176 hash: await sha256Text(page),
177 extractedAt: new Date().toISOString(),
178 }
179 })
180 return (rawId) => {
181 const row = doc.rates[rawId]
182 if (!row) return {}
183 const pricing = compileUnitCard(row, {
184 url: KLING_PRICING_URL,
185 hash: doc.hash,
186 extractedAt: doc.extractedAt,
187 })
188 if (!pricing) return {}
189 return {
190 pricing,
191 factSources: tagDocsFacts({ pricing }, KLING_PRICING_URL, doc.hash),
192 }
193 }
194}