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

dimensions.ts

274 lines8.3 KB

1/**
2 * Distills "what dimensions can this image model produce?" out of an
3 * arbitrary input JSON Schema. Works generically: it walks every property
4 * (through $defs, anyOf/oneOf, and nested objects) looking for the
5 * dimension vocabulary providers actually use — `size`/`image_size` enums,
6 * `width`/`height` bounds, `aspect_ratio`/`aspectRatio`, `resolution`.
7 */
8​
9export type SchemaNode = { readonly [key: string]: unknown }
10​
11function isNode(value: unknown): value is SchemaNode {
12 return typeof value === 'object' && value !== null && !Array.isArray(value)
14​
15function str(node: SchemaNode, key: string): string | undefined {
16 const value = node[key]
17 return typeof value === 'string' ? value : undefined
19​
20function num(node: SchemaNode, key: string): number | undefined {
21 const value = node[key]
22 return typeof value === 'number' ? value : undefined
24​
25function strEnum(node: SchemaNode): Array<string> | undefined {
26 const values = node['enum']
27 if (!Array.isArray(values)) return undefined
28 const out = values.filter((v): v is string => typeof v === 'string')
29 return out.length > 0 ? out : undefined
31​
32export interface SizeBox {
33 label: string
34 width: number
35 height: number
36 /** 'exact' parsed from WxH; 'preset' mapped from a documented preset name. */
37 kind: 'exact' | 'preset'
38 isDefault: boolean
40​
41export interface AspectBox {
42 label: string
43 ratio: number
44 isDefault: boolean
46​
47export interface Bounds {
48 minWidth?: number
49 maxWidth?: number
50 minHeight?: number
51 maxHeight?: number
52 defaultWidth?: number
53 defaultHeight?: number
55​
56export interface DimensionReport {
57 sizes: Array<SizeBox>
58 aspects: Array<AspectBox>
59 bounds: Bounds | null
60 resolutions: Array<string>
61 modelIds: Array<string>
62 hasAny: boolean
64​
65/** FAL's documented named presets (fal.ai ImageSize), used only to draw
66 * preset enums to scale. Unknown presets fall back to a 1:1 box. */
67const PRESET_DIMS: Record<string, [number, number]> = {
68 square_hd: [1024, 1024],
69 square: [512, 512],
70 portrait_4_3: [768, 1024],
71 portrait_16_9: [576, 1024],
72 landscape_4_3: [1024, 768],
73 landscape_16_9: [1024, 576],
75​
76const SIZE_RE = /^(\d{2,5})\s*[x×]\s*(\d{2,5})$/i
77const ASPECT_RE = /^(\d{1,2})\s*:\s*(\d{1,2})$/
78​
79/**
80 * Google Discovery specs encode enum values as symbolic constants
81 * (`ASPECT_RATIO_SIXTEEN_BY_NINE`, `IMAGE_SIZE_TWO_K`) rather than the
82 * literal labels every other provider uses; map them back. `*_UNSPECIFIED`
83 * sentinels are dropped before these run.
84 */
85const GOOGLE_NUMBER_WORDS: Record<string, number> = {
86 ONE: 1,
87 TWO: 2,
88 THREE: 3,
89 FOUR: 4,
90 FIVE: 5,
91 SIX: 6,
92 SEVEN: 7,
93 EIGHT: 8,
94 NINE: 9,
95 TEN: 10,
96 SIXTEEN: 16,
97 TWENTY_ONE: 21,
99​
100const GOOGLE_IMAGE_SIZES: Record<string, string> = {
101 IMAGE_SIZE_FIVE_TWELVE: '512',
102 IMAGE_SIZE_ONE_K: '1K',
103 IMAGE_SIZE_TWO_K: '2K',
104 IMAGE_SIZE_FOUR_K: '4K',
106​
107/** `ASPECT_RATIO_SIXTEEN_BY_NINE` → `16:9`; undefined when not symbolic. */
108function googleAspectLabel(value: string): string | undefined {
109 const match = /^ASPECT_RATIO_(.+)_BY_(.+)$/.exec(value)
110 if (match?.[1] === undefined || match[2] === undefined) return undefined
111 const w = GOOGLE_NUMBER_WORDS[match[1]]
112 const h = GOOGLE_NUMBER_WORDS[match[2]]
113 if (w === undefined || h === undefined) return undefined
114 return `${String(w)}:${String(h)}`
116​
117function parseAspect(label: string): number | undefined {
118 const match = ASPECT_RE.exec(label)
119 if (match?.[1] === undefined || match[2] === undefined) return undefined
120 const w = Number(match[1])
121 const h = Number(match[2])
122 return h > 0 ? w / h : undefined
124​
125function resolveRef(node: SchemaNode, root: SchemaNode): SchemaNode {
126 let current = node
127 for (let hop = 0; hop < 8; hop++) {
128 const ref = str(current, '$ref')
129 if (ref === undefined || !ref.startsWith('#/$defs/')) return current
130 const defs = root['$defs']
131 const target = isNode(defs) ? defs[ref.slice('#/$defs/'.length)] : undefined
132 if (!isNode(target)) return current
133 current = target
134 }
135 return current
137​
138const ASPECT_KEYS = new Set(['aspect_ratio', 'aspectratio', 'ratio'])
139const SIZE_KEYS = new Set([
140 'size',
141 'image_size',
142 'imagesize',
143 'sampleimagesize',
144])
145const RESOLUTION_KEYS = new Set(['resolution', 'image_resolution'])
146​
147export function extractDimensions(schema: SchemaNode): DimensionReport {
148 const report: DimensionReport = {
149 sizes: [],
150 aspects: [],
151 bounds: null,
152 resolutions: [],
153 modelIds: [],
154 hasAny: false,
155 }
156 const seenSizes = new Set<string>()
157 const seenAspects = new Set<string>()
158​
159 const addSize = (label: string, isDefault: boolean) => {
160 if (seenSizes.has(label)) return
161 const exact = SIZE_RE.exec(label)
162 if (exact?.[1] !== undefined && exact[2] !== undefined) {
163 seenSizes.add(label)
164 report.sizes.push({
165 label,
166 width: Number(exact[1]),
167 height: Number(exact[2]),
168 kind: 'exact',
169 isDefault,
170 })
171 return
172 }
173 const preset = PRESET_DIMS[label]
174 if (preset !== undefined) {
175 seenSizes.add(label)
176 report.sizes.push({
177 label,
178 width: preset[0],
179 height: preset[1],
180 kind: 'preset',
181 isDefault,
182 })
183 return
184 }
185 const ratio = parseAspect(label)
186 if (ratio !== undefined) {
187 addAspect(label, isDefault)
188 return
189 }
190 // Unrecognized symbolic size ('auto', provider-specific names): list it
191 // as a named mode rather than inventing a rectangle for it.
192 seenSizes.add(label)
193 if (!report.resolutions.includes(label)) report.resolutions.push(label)
194 }
195​
196 const addAspect = (label: string, isDefault: boolean) => {
197 if (seenAspects.has(label)) return
198 const ratio = parseAspect(label)
199 if (ratio === undefined) return
200 seenAspects.add(label)
201 report.aspects.push({ label, ratio, isDefault })
202 }
203​
204 const visit = (node: SchemaNode, name: string, depth: number) => {
205 if (depth > 6) return
206 const resolved = resolveRef(node, schema)
207 const lower = name.toLowerCase()
208 const options = strEnum(resolved)
209 const fallback = str(resolved, 'default')
210​
211 if (lower === 'model' && options !== undefined) {
212 for (const id of options)
213 if (!report.modelIds.includes(id)) report.modelIds.push(id)
214 } else if (ASPECT_KEYS.has(lower) && options !== undefined) {
215 for (const option of options) {
216 if (option.endsWith('_UNSPECIFIED')) continue
217 addAspect(googleAspectLabel(option) ?? option, option === fallback)
218 }
219 } else if (RESOLUTION_KEYS.has(lower) && options !== undefined) {
220 for (const option of options) {
221 if (option.endsWith('_UNSPECIFIED')) continue
222 if (!report.resolutions.includes(option))
223 report.resolutions.push(option)
224 }
225 } else if (SIZE_KEYS.has(lower) && options !== undefined) {
226 for (const option of options) {
227 if (option.endsWith('_UNSPECIFIED')) continue
228 addSize(GOOGLE_IMAGE_SIZES[option] ?? option, option === fallback)
229 }
230 } else if (lower === 'width' || lower === 'height') {
231 const bounds: Bounds = report.bounds ?? {}
232 const min = num(resolved, 'minimum')
233 const max = num(resolved, 'maximum')
234 const def = num(resolved, 'default')
235 if (lower === 'width') {
236 if (min !== undefined) bounds.minWidth = min
237 if (max !== undefined) bounds.maxWidth = max
238 if (def !== undefined) bounds.defaultWidth = def
239 } else {
240 if (min !== undefined) bounds.minHeight = min
241 if (max !== undefined) bounds.maxHeight = max
242 if (def !== undefined) bounds.defaultHeight = def
243 }
244 report.bounds = bounds
245 }
246​
247 // Recurse: object properties, array items, anyOf/oneOf/allOf variants.
248 const props = resolved['properties']
249 if (isNode(props)) {
250 for (const [childName, child] of Object.entries(props)) {
251 if (isNode(child)) visit(child, childName, depth + 1)
252 }
253 }
254 const items = resolved['items']
255 if (isNode(items)) visit(items, name, depth + 1)
256 for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
257 const list = resolved[key]
258 if (Array.isArray(list)) {
259 for (const variant of list) {
260 if (isNode(variant)) visit(variant, name, depth + 1)
261 }
262 }
263 }
264 }
265​
266 visit(schema, '', 0)
267​
268 report.hasAny =
269 report.sizes.length > 0 ||
270 report.aspects.length > 0 ||
271 report.bounds !== null ||
272 report.resolutions.length > 0
273 return report