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

change-diff.ts

54 lines1.7 KB

1/**
2 * /changes rows: what a `model.updated` event changed, as short text.
3 * Reads the payload's `changed` fact paths against its before/after
4 * snapshots. An event written before `changed` existed shows nothing.
5 */
6export interface ChangeDiff {
7 path: string
8 before: string
9 after: string
11​
12function isRecord(value: unknown): value is Record<string, unknown> {
13 return typeof value === 'object' && value !== null && !Array.isArray(value)
15​
16function at(root: unknown, path: string): unknown {
17 let value = root
18 for (const key of path.split('.')) {
19 if (Array.isArray(value)) value = (value as Array<unknown>)[Number(key)]
20 else if (isRecord(value)) value = value[key]
21 else return undefined
22 }
23 return value
25​
26function show(value: unknown, path: string): string {
27 if (value === undefined) return '—'
28 if (value === null) return 'null'
29 // Rates are stored per token; a reader compares them per million.
30 if (typeof value === 'number' && path.startsWith('pricing.tables.')) {
31 return `$${String(Number((value * 1e6).toPrecision(6)))}/M`
32 }
33 if (typeof value === 'object') return path === 'pricing' ? 'card' : '{…}'
34 if (
35 typeof value === 'string' ||
36 typeof value === 'number' ||
37 typeof value === 'boolean' ||
38 typeof value === 'bigint'
39 ) {
40 return String(value)
41 }
42 return '{…}'
44​
45export function changeDiffs(payload: unknown): Array<ChangeDiff> {
46 if (!isRecord(payload) || !Array.isArray(payload.changed)) return []
47 return (payload.changed as Array<unknown>)
48 .filter((path): path is string => typeof path === 'string')
49 .map((path) => ({
50 path,
51 before: show(at(payload.before, path), path),
52 after: show(at(payload.after, path), path),
53 }))