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

xiaomi-docs.ts

298 lines10.0 KB

1/** Xiaomi's public MDX schema trees and tables, converted without model tables. */
2import type { OpenApiDocument } from './types.ts'
3​
4type RecordValue = Record<string, unknown>
5export const XIAOMI_DOCS = 'https://mimo.mi.com/static/docs/'
6export const XIAOMI_MODELS = `${XIAOMI_DOCS}quick-start/summary/model.md`
7export const XIAOMI_PRICING = `${XIAOMI_DOCS}price/pay-as-you-go.md`
8export const XIAOMI_THINKING = `${XIAOMI_DOCS}quick-start/usage-guide/text-generation/deep-thinking.md`
9export const XIAOMI_SCHEMA_URLS = [
10 'api/chat/openai-api.md',
11 'api/chat/responses.md',
12 'api/chat/anthropic-api.md',
13 'api/audio/Speech-Recognition.md',
14 'api/audio/tts.md',
15].map((path) => `${XIAOMI_DOCS}${path}`)
16​
17function fail(message: string): never {
18 throw new Error(`xiaomi: ${message}`)
20function record(value: unknown): value is RecordValue {
21 return typeof value === 'object' && value !== null && !Array.isArray(value)
23export function plain(text: string): string {
24 return text
25 .replace(/<[^>]*>/g, ' ')
26 .replace(/&nbsp;/g, ' ')
27 .replace(/&amp;/g, '&')
28 .replace(/\s+/g, ' ')
29 .trim()
31​
32/** Expand actual table spans before assigning a model its neighboring cells. */
33export function htmlTables(text: string): Array<Array<Array<string>>> {
34 const tables: Array<Array<Array<string>>> = []
35 for (const table of text.matchAll(/<table\b[^>]*>([\s\S]*?)<\/table>/g)) {
36 const rows: Array<Array<string>> = []
37 const spans = new Map<number, { value: string; remaining: number }>()
38 for (const row of (table[1] ?? '').matchAll(
39 /<tr\b[^>]*>([\s\S]*?)<\/tr>/g,
40 )) {
41 const cells: Array<string> = []
42 let column = 0
43 const fill = () => {
44 while (spans.has(column)) {
45 const span = spans.get(column)
46 if (!span) fail('missing table span')
47 cells.push(span.value)
48 span.remaining--
49 if (span.remaining === 0) spans.delete(column)
50 column++
51 }
52 }
53 for (const cell of (row[1] ?? '').matchAll(
54 /<t[dh]\b([^>]*)>([\s\S]*?)<\/t[dh]>/g,
55 )) {
56 fill()
57 const attrs = cell[1] ?? ''
58 if (/colspan/.test(attrs)) fail('unsupported table colspan')
59 const rowspan = Number(/rowspan="(\d+)"/.exec(attrs)?.[1] ?? '1')
60 if (!Number.isInteger(rowspan) || rowspan < 1)
61 fail('invalid table rowspan')
62 const value = cell[2] ?? ''
63 cells.push(value)
64 if (rowspan > 1) spans.set(column, { value, remaining: rowspan - 1 })
65 column++
66 }
67 fill()
68 if (cells.length) rows.push(cells)
69 }
70 if (spans.size) fail('table rowspan extends past table')
71 if (rows.length) tables.push(rows)
72 }
73 if (!tables.length) fail('document contains no model tables')
74 return tables
76​
77interface NativeNode {
78 name: string
79 type: Array<string>
80 isBold: boolean
81 required?: boolean
82 description?: string
83 children: Array<NativeNode>
85function node(value: unknown): NativeNode {
86 if (
87 !record(value) ||
88 typeof value.name !== 'string' ||
89 !value.name ||
90 typeof value.isBold !== 'boolean'
91 )
92 fail('invalid native schema node')
93 const types = typeof value.type === 'string' ? [value.type] : value.type
94 if (
95 !Array.isArray(types) ||
96 !types.length ||
97 !types.every(
98 (type): type is string =>
99 typeof type === 'string' &&
100 [
101 'string',
102 'object',
103 'array',
104 'integer',
105 'number',
106 'boolean',
107 'null',
108 'long',
109 ].includes(type),
110 )
111 )
112 fail(`unsupported native type for ${value.name}`)
113 if (value.required !== undefined && typeof value.required !== 'boolean')
114 fail(`invalid required flag for ${value.name}`)
115 if (value.description !== undefined && typeof value.description !== 'string')
116 fail(`invalid description for ${value.name}`)
117 if (value.children !== undefined && !Array.isArray(value.children))
118 fail(`invalid children for ${value.name}`)
119 return {
120 name: value.name,
121 type: types.map((type) => (type === 'long' ? 'integer' : type)),
122 isBold: value.isBold,
123 ...(typeof value.required === 'boolean'
124 ? { required: value.required }
125 : {}),
126 ...(typeof value.description === 'string'
127 ? { description: value.description }
128 : {}),
129 children: (value.children as Array<unknown> | undefined)?.map(node) ?? [],
130 }
132​
133/** Only a flat explicit options list becomes an enum; conditional prose stays prose. */
134function options(description: string): Array<string> | null {
135 const tail = description.split(/Available options:\s*/).at(-1)
136 if (tail === description || !tail || /<ul|<blockquote/.test(tail)) return null
137 const codes = [...tail.matchAll(/<code\b[^>]*>([^<]+)<\/code>/g)].map(
138 (match) => match[1] ?? '',
139 )
140 const remainder = tail
141 .replace(/<code\b[^>]*>[^<]+<\/code>/g, '')
142 .replace(/<br\s*\/?\s*>/g, '')
143 .trim()
144 return codes.length && /^[\s,.;]*$/.test(remainder) ? codes : null
146function objectSchema(children: Array<NativeNode>): RecordValue {
147 if (children.some((child) => !child.isBold))
148 fail('anonymous variants mixed with named object fields')
149 const properties: RecordValue = {}
150 const required: Array<string> = []
151 for (const child of children) {
152 if (child.name in properties)
153 fail(`duplicate schema property ${child.name}`)
154 properties[child.name] = schema(child)
155 if (child.required) required.push(child.name)
156 }
157 return {
158 type: 'object',
159 properties,
160 ...(required.length ? { required } : {}),
161 }
163function alternatives(children: Array<NativeNode>): RecordValue {
164 const variants = children.map(schema)
165 if (!variants.length) fail('empty schema alternatives')
166 return variants.length === 1
167 ? (variants[0] ?? fail('empty schema variant'))
168 : { anyOf: variants }
170function schema(value: NativeNode): RecordValue {
171 let out: RecordValue = {
172 type: value.type.length === 1 ? value.type[0] : value.type,
173 }
174 const children = value.children
175 if (children.length) {
176 if (children.every((child) => !child.isBold)) {
177 // A same-type wrapper describes the value itself, not another array level.
178 if (
179 value.type.length > 1 ||
180 children.every((child) => value.type.includes(child.type[0] ?? ''))
181 ) {
182 out = alternatives(children)
183 if (
184 value.type.includes('null') &&
185 !children.some((child) => child.type.includes('null'))
186 )
187 out = { anyOf: [out, { type: 'null' }] }
188 } else if (value.type.includes('array')) {
189 out.items = alternatives(children)
190 } else if (value.type.includes('object')) {
191 out = alternatives(children)
192 } else fail(`children do not describe ${value.name}`)
193 } else if (children.every((child) => child.isBold)) {
194 if (value.type.includes('array')) out.items = objectSchema(children)
195 else if (value.type.includes('object'))
196 out = {
197 ...objectSchema(children),
198 type: value.type.length === 1 ? 'object' : value.type,
199 }
200 else fail(`primitive ${value.name} has named children`)
201 } else if (value.type.includes('object')) {
202 // Video sources share fps/media_resolution across URL and base64 variants.
203 out = {
204 allOf: [
205 objectSchema(children.filter((child) => child.isBold)),
206 alternatives(children.filter((child) => !child.isBold)),
207 ],
208 }
209 } else fail(`mixed native children in ${value.name}`)
210 }
211 if (value.description) {
212 out.description = plain(value.description)
213 const values = options(value.description)
214 if (values && value.type.length === 1 && value.type[0] === 'string')
215 out.enum = values
216 }
217 return out
219​
220export function nativeSchemas(text: string): Array<RecordValue> {
221 const schemas: Array<RecordValue> = []
222 for (const match of text.matchAll(
223 /<InlineSchemaV2 schema=\{`([\s\S]*?)`\}/g,
224 )) {
225 const raw = (match[1] ?? '')
226 .replace(/\\\\/g, '\\')
227 .replace(/\\`/g, '`')
228 .replace(/\\\$/g, '$')
229 let parsed: unknown
230 try {
231 parsed = JSON.parse(raw)
232 } catch {
233 fail('native schema is not valid JSON')
234 }
235 if (!Array.isArray(parsed) || !parsed.length)
236 fail('native schema is not a nonempty node list')
237 schemas.push(objectSchema(parsed.map(node)))
238 }
239 if (!schemas.length) fail('document contains no native schemas')
240 return schemas
242​
243/** Actual documented endpoints; multiple model families share chat/completions. */
244export function xiaomiSpec(
245 docs: Array<{ text: string; url: string }>,
246): OpenApiDocument {
247 const grouped = new Map<
248 string,
249 { requests: Array<RecordValue>; responses: Array<RecordValue> }
250 >()
251 for (const doc of docs) {
252 const address =
253 /## Request Address\s*```(?:bash)?\s*(https:\/\/api\.xiaomimimo\.com\/[^\s`]+)\s*```/.exec(
254 doc.text,
255 )?.[1]
256 if (!address) fail(`no native request address in ${doc.url}`)
257 const path = new URL(address).pathname
258 const parsed = nativeSchemas(doc.text)
259 const request = parsed[0]
260 const response = parsed[1]
261 if (!request || !response)
262 fail(`missing native request/response in ${doc.url}`)
263 const group = grouped.get(path) ?? { requests: [], responses: [] }
264 group.requests.push(request)
265 group.responses.push(response)
266 grouped.set(path, group)
267 }
268 const combine = (schemas: Array<RecordValue>) =>
269 schemas.length === 1 ? schemas[0] : { anyOf: schemas }
270 return {
271 openapi: '3.1.0',
272 info: { title: 'Xiaomi MiMo', version: 'native-docs' },
273 servers: [{ url: 'https://api.xiaomimimo.com' }],
274 paths: Object.fromEntries(
275 [...grouped].map(([path, group]) => [
276 path,
277 {
278 post: {
279 requestBody: {
280 required: true,
281 content: {
282 'application/json': { schema: combine(group.requests) },
283 },
284 },
285 responses: {
286 '200': {
287 description: 'Documented non-streaming response',
288 content: {
289 'application/json': { schema: combine(group.responses) },
290 },
291 },
292 },
293 },
294 },
295 ]),
296 ),
297 }