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

kimi-doc-tables.ts

179 lines7.0 KB

1/**
2 * `<DocTable>` tables from a Kimi docs page (platform.kimi.com and
3 * platform.kimi.ai, both Mintlify). As of 2026-10-20 the `.md` export of a
4 * page renders each `<DocTable>` as an empty `<table>`, so the pricing
5 * tables are read from the HTML page instead. Its RSC payload embeds the
6 * page's compiled MDX: `_jsx(Heading,{level:`2`,…,children:`…`})` (or
7 * `_components.h2`) for each heading and
8 * `_jsx(DocTable,{columns:[…],rows:[[…]]})` for each table, with every
9 * string a template literal. The payload carries the body twice: first
10 * with a rendering `DocTable`, then with `DocTable=()=>null` (on
11 * platform.kimi.ai that copy has no `rows`). Only the first copy, up to its
12 * `_provideComponents(`, is read. As of 2026-10-23 a DocTable also carries
13 * `className`, `corner` and `groups` (styling and a header row over the
14 * column titles), a model id cell is a link, and a column title can be a
15 * `Tooltip` over its text.
16 */
17import { closing, literalEnd } from './compiled-mdx.ts'
18​
19const LABEL = 'kimi docs'
20​
21export interface KimiDocTable {
22 /** Text of the nearest level-1/2 heading above the table; null when not plain text. */
23 section: string | null
24 /** Text of the `###` heading under that section; null when none or not plain text. */
25 subsection: string | null
26 /**
27 * Column titles, read as a cell is or as a `Tooltip`'s text; null for a
28 * column whose title is not readable text.
29 */
30 titles: Array<string | null>
31 /**
32 * A cell is its text: a template literal, or a fragment of them joined
33 * (`<>{"$"}0.16</>` compiles to `_jsxs(_Fragment,{children:[`$`,`0.16`]})`,
34 * read as `$0.16`). A row's first cell (the model id) may also be a
35 * link, read as its text. Anything else (a struck price, a price behind
36 * a link or a footnote tooltip) is null.
37 */
38 rows: Array<Array<string | null>>
40​
41/** A template literal with no escape or `${`: its text is the source text. */
42const LITERAL = '`((?:[^`\\\\$]|\\$(?!\\{))*)`'
43const TEXT = new RegExp(`^${LITERAL}$`)
44const FRAGMENT = /^_jsxs?\(_Fragment,\{children:([\s\S]*)\}\)$/
45/** A link (the id cell) or a tooltip (a column title): its text is its `children`. */
46const LINK = /^_jsxs?\(_components\.a,\{/
47const TOOLTIP = /^_jsxs?\(Tooltip,\{/
48const HEADING = /_jsxs?\((?:Heading|_components\.h(\d)),\{/g
49const TABLE = /_jsxs?\(DocTable,\{/g
50/** DocTable props that style it or group its titles; they move no cell. */
51const STYLE_PROPS = new Set(['className', 'corner', 'groups'])
52​
53/** The comma-separated items between `open` and its closing bracket. */
54function items(source: string, open: number): Array<string> {
55 const close = closing(source, open, LABEL)
56 const out: Array<string> = []
57 let start = open + 1
58 for (let i = start; i < close; i++) {
59 const char = source[i]
60 if (char === '`') {
61 i = literalEnd(source, i, LABEL)
62 } else if (char === '[' || char === '{' || char === '(') {
63 i = closing(source, i, LABEL)
64 } else if (char === ',') {
65 out.push(source.slice(start, i))
66 start = i + 1
67 }
68 }
69 if (close > start) out.push(source.slice(start, close))
70 return out
72​
73/** The text of `item`; `wrapper` also unwraps that one component. */
74function cell(item: string, wrapper?: RegExp): string | null {
75 const text = TEXT.exec(item)
76 if (text) return text[1] ?? ''
77 const wrapped = wrapper?.exec(item)
78 if (wrapped) {
79 const open = wrapped[0].length - 1
80 if (closing(item, open, LABEL) !== item.length - 2) return null
81 const children = props(item, open).get('children')
82 return children === undefined ? null : cell(children)
83 }
84 const children = FRAGMENT.exec(item)?.[1]
85 if (children === undefined) return null
86 const parts = children.startsWith('[') ? items(children, 0) : [children]
87 const texts = parts.map((part) => TEXT.exec(part)?.[1])
88 return texts.every((part) => part !== undefined) ? texts.join('') : null
90​
91/** `key:value` props of the object literal opened at `open`. */
92function props(source: string, open: number): Map<string, string> {
93 const out = new Map<string, string>()
94 for (const prop of items(source, open)) {
95 const colon = prop.indexOf(':')
96 if (colon > 0) out.set(prop.slice(0, colon), prop.slice(colon + 1))
97 }
98 return out
100​
101/**
102 * Every DocTable on the page, in order, under the headings above it.
103 * Throws when the page has no compiled MDX body or no DocTable, when a
104 * heading's level is unreadable, when a DocTable's props are not `columns`
105 * then `rows` beside the style props, or a row is not an array, or when
106 * the body is malformed.
107 */
108export function parseKimiDocTables(html: string): Array<KimiDocTable> {
109 const start = html.search(/_jsxs?\((?:Heading|DocTable|_components\.h\d),/)
110 const end = start < 0 ? -1 : html.indexOf('_provideComponents(', start)
111 if (end < 0) throw new Error('kimi docs: page has no compiled MDX body')
112 const body = html.slice(start, end)
113​
114 const marks: Array<
115 | { at: number; level: number; text: string | null }
116 | { at: number; table: KimiDocTable }
117 > = []
118 for (const match of body.matchAll(HEADING)) {
119 const heading = props(body, match.index + match[0].length - 1)
120 const level = Number(
121 match[1] ?? TEXT.exec(heading.get('level') ?? '')?.[1] ?? NaN,
122 )
123 if (!Number.isInteger(level)) {
124 throw new Error('kimi docs: heading level is unreadable')
125 }
126 const children = heading.get('children')
127 const text =
128 children === undefined ? null : (TEXT.exec(children)?.[1] ?? null)
129 marks.push({ at: match.index, level, text })
130 }
131 for (const match of body.matchAll(TABLE)) {
132 const table = [...props(body, match.index + match[0].length - 1)].filter(
133 ([key]) => !STYLE_PROPS.has(key),
134 )
135 const [columns, rows] = table.map(([, value]) => value)
136 if (
137 table.map(([key]) => key).join() !== 'columns,rows' ||
138 !columns?.startsWith('[') ||
139 !rows?.startsWith('[')
140 ) {
141 throw new Error('kimi docs: DocTable props are not columns, rows')
142 }
143 const titles = items(columns, 0).map((column) => {
144 const title = column.startsWith('{')
145 ? props(column, 0).get('title')
146 : undefined
147 return title === undefined ? null : cell(title, TOOLTIP)
148 })
149 const cells = items(rows, 0).map((row) => {
150 if (!row.startsWith('[')) {
151 throw new Error('kimi docs: DocTable row is not an array')
152 }
153 return items(row, 0).map((item, index) =>
154 index === 0 ? cell(item, LINK) : cell(item),
155 )
156 })
157 marks.push({
158 at: match.index,
159 table: { section: null, subsection: null, titles, rows: cells },
160 })
161 }
162 marks.sort((a, b) => a.at - b.at)
163​
164 const tables: Array<KimiDocTable> = []
165 let section: string | null = null
166 let subsection: string | null = null
167 for (const mark of marks) {
168 if ('table' in mark) {
169 tables.push({ ...mark.table, section, subsection })
170 } else if (mark.level <= 2) {
171 section = mark.text
172 subsection = null
173 } else if (mark.level === 3) {
174 subsection = mark.text
175 }
176 }
177 if (tables.length === 0) throw new Error('kimi docs: page has no DocTable')
178 return tables