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

generate-fal-image-field-map.ts

362 lines11.9 KB

1/**
2 * Generates the fal image-conditioning field-override map from the
3 * `EndpointTypeMap` types shipped with `@fal-ai/client`.
4 *
5 * fal endpoints use inconsistent field names for image-conditioned
6 * generation (`image_url` vs `image_urls` vs `first_frame_url` vs
7 * `mask_image_url`, ...). The runtime mapper in
8 * `packages/ai-fal/src/image/image-inputs.ts` applies a default
9 * field per input role; this script walks every endpoint's input type with
10 * the TypeScript checker and records, per role, the field the endpoint
11 * actually accepts whenever it differs from that default. Endpoints that
12 * match the defaults (the vast majority) are omitted, keeping the shipped
13 * artifact small.
14 *
15 * The emitted file type-checks each recorded field name against
16 * `EndpointTypeMap` via `satisfies` (a type-only import, erased at runtime),
17 * so a fal SDK bump that renames a field fails `tsc` until this script is
18 * re-run. A unit test compares the recorded endpoints.d.ts hash against the
19 * installed SDK to catch staleness.
20 *
21 * Usage:
22 * pnpm tsx scripts/generate-fal-image-field-map.ts # regenerate
23 * pnpm tsx scripts/generate-fal-image-field-map.ts --check # CI staleness check
24 */
25​
26import { createHash } from 'node:crypto'
27import { readFileSync, writeFileSync } from 'node:fs'
28import { dirname, resolve } from 'node:path'
29import { fileURLToPath } from 'node:url'
30import ts from 'typescript'
31​
32const __dirname = dirname(fileURLToPath(import.meta.url))
33const ROOT = resolve(__dirname, '..')
34const FAL_PKG = resolve(ROOT, 'packages/ai-fal')
35const ENDPOINTS_DTS = resolve(
36 FAL_PKG,
37 'node_modules/@fal-ai/client/src/types/endpoints.d.ts',
39const CLIENT_PKG_JSON = resolve(
40 FAL_PKG,
41 'node_modules/@fal-ai/client/package.json',
43const OUT_FILE = resolve(
44 FAL_PKG,
45 'src/image/generated/image-field-overrides.ts',
47​
48// ---------------------------------------------------------------------------
49// Role classification
50// ---------------------------------------------------------------------------
51​
52/**
53 * Routing roles used by the runtime mapper. `single` / `multi` cover unroled
54 * source images; the rest correspond to `MediaInputRole` values.
55 */
56type RoleKey =
57 | 'single'
58 | 'multi'
59 | 'mask'
60 | 'control'
61 | 'reference'
62 | 'start'
63 | 'end'
64​
65/**
66 * Default field per role — must stay in sync with `DEFAULT_FIELDS` in
67 * image-inputs.ts. An override is only emitted when the chosen candidate
68 * differs from this default.
69 */
70const DEFAULTS: Record<RoleKey, string> = {
71 single: 'image_url',
72 multi: 'image_urls',
73 mask: 'mask_url',
74 control: 'control_image_url',
75 reference: 'reference_image_urls',
76 start: 'start_image_url',
77 end: 'end_image_url',
79​
80/**
81 * Candidate fields per role, in priority order. The first candidate present
82 * on the endpoint's input type wins. Names here are deliberately
83 * conservative: only fields whose semantics unambiguously match the role.
84 *
85 * `start` / `end` are only consumed by the video mapper (the image mapper
86 * treats those roles as plain sources), so they are only computed for
87 * endpoints whose output contains video — that's also why `image_url` is a
88 * valid `start` candidate: on image-to-video endpoints the source image IS
89 * the start frame.
90 */
91const CANDIDATES: Record<RoleKey, Array<string>> = {
92 single: [
93 'image_url',
94 'input_image_url',
95 'image_data_url',
96 'image_urls',
97 'input_image_urls',
98 ],
99 multi: [
100 'image_urls',
101 'input_image_urls',
102 'ref_image_urls',
103 'reference_image_urls',
104 ],
105 mask: ['mask_url', 'mask_image_url'],
106 control: ['control_image_url'],
107 reference: [
108 'reference_image_urls',
109 'ref_image_urls',
110 'reference_image_url',
111 'image_urls',
112 'input_image_urls',
113 ],
114 start: ['start_image_url', 'first_frame_url', 'first_image_url', 'image_url'],
115 end: ['end_image_url', 'last_frame_url', 'last_image_url', 'tail_image_url'],
117​
118/** Roles only meaningful for endpoints that produce video. */
119const VIDEO_ONLY_ROLES = new Set<RoleKey>(['start', 'end'])
120​
121/**
122 * Fields that take an array of images. The runtime mapper wraps/refuses
123 * values based on this same set (`LIST_FIELDS` in image-inputs.ts); the
124 * generator asserts the actual types agree so the two never drift.
125 */
126const LIST_FIELDS = new Set([
127 'image_urls',
128 'input_image_urls',
129 'ref_image_urls',
130 'reference_image_urls',
131])
132​
133// ---------------------------------------------------------------------------
134// Type extraction
135// ---------------------------------------------------------------------------
136​
137interface EndpointFields {
138 /** All input field names for this endpoint */
139 fields: Set<string>
140 /** Field name -> whether the field accepts an array */
141 isList: Map<string, boolean>
142 /** Whether the endpoint's output contains video */
143 producesVideo: boolean
145​
146function extractEndpointInputs(): Map<string, EndpointFields> {
147 const program = ts.createProgram([ENDPOINTS_DTS], {
148 target: ts.ScriptTarget.ES2022,
149 skipLibCheck: true,
150 })
151 const checker = program.getTypeChecker()
152 const source = program.getSourceFile(ENDPOINTS_DTS)
153 if (!source) throw new Error(`Could not load ${ENDPOINTS_DTS}`)
154​
155 let mapType: ts.Type | undefined
156 source.forEachChild((node) => {
157 if (
158 ts.isTypeAliasDeclaration(node) &&
159 node.name.text === 'EndpointTypeMap'
160 ) {
161 mapType = checker.getTypeAtLocation(node.name)
162 }
163 })
164 if (!mapType) throw new Error('EndpointTypeMap not found in endpoints.d.ts')
165​
166 const endpoints = new Map<string, EndpointFields>()
167 for (const endpoint of mapType.getProperties()) {
168 const endpointType = checker.getTypeOfSymbol(endpoint)
169 const inputSymbol = endpointType.getProperty('input')
170 if (!inputSymbol) continue
171 const inputType = checker.getTypeOfSymbol(inputSymbol)
172​
173 const fields = new Set<string>()
174 const isList = new Map<string, boolean>()
175 for (const field of inputType.getProperties()) {
176 const name = field.getName()
177 fields.add(name)
178 const fieldType = checker.getTypeOfSymbol(field)
179 isList.set(name, typeAcceptsArray(checker, fieldType))
180 }
181​
182 const outputSymbol = endpointType.getProperty('output')
183 const producesVideo = outputSymbol
184 ? checker
185 .getTypeOfSymbol(outputSymbol)
186 .getProperties()
187 .some((p) => p.getName() === 'video' || p.getName() === 'videos')
188 : false
189​
190 endpoints.set(endpoint.getName(), { fields, isList, producesVideo })
191 }
192 return endpoints
194​
195function typeAcceptsArray(checker: ts.TypeChecker, type: ts.Type): boolean {
196 const parts = type.isUnion() ? type.types : [type]
197 return parts.some((part) => checker.isArrayLikeType(part))
199​
200// ---------------------------------------------------------------------------
201// Override computation
202// ---------------------------------------------------------------------------
203​
204const ROLE_ORDER: Array<RoleKey> = [
205 'single',
206 'multi',
207 'mask',
208 'control',
209 'reference',
210 'start',
211 'end',
213​
214function computeOverrides(
215 endpoints: Map<string, EndpointFields>,
216): Map<string, Partial<Record<RoleKey, string>>> {
217 const overrides = new Map<string, Partial<Record<RoleKey, string>>>()
218​
219 for (const [endpointId, { fields, isList, producesVideo }] of endpoints) {
220 const entry: Partial<Record<RoleKey, string>> = {}
221 for (const role of ROLE_ORDER) {
222 if (VIDEO_ONLY_ROLES.has(role) && !producesVideo) continue
223 const chosen = CANDIDATES[role].find((candidate) => fields.has(candidate))
224 if (!chosen) continue
225​
226 // Arity sanity check: the runtime mapper decides array-wrapping from
227 // the static LIST_FIELDS set, so the actual type must agree. Run this
228 // for default-selected fields too, otherwise a default field's type
229 // could drift silently.
230 const actualIsList = isList.get(chosen) ?? false
231 const assumedIsList = LIST_FIELDS.has(chosen)
232 if (actualIsList !== assumedIsList) {
233 throw new Error(
234 `Arity mismatch for ${endpointId}.${chosen}: type says ` +
235 `${actualIsList ? 'array' : 'scalar'} but LIST_FIELDS assumes ` +
236 `${assumedIsList ? 'array' : 'scalar'}. Update LIST_FIELDS here ` +
237 `and LIST_FIELDS in image-inputs.ts.`,
238 )
239 }
240 if (chosen === DEFAULTS[role]) continue
241 entry[role] = chosen
242 }
243 if (Object.keys(entry).length > 0) overrides.set(endpointId, entry)
244 }
245 return overrides
247​
248// ---------------------------------------------------------------------------
249// Emission
250// ---------------------------------------------------------------------------
251​
252function render(
253 overrides: Map<string, Partial<Record<RoleKey, string>>>,
254): string {
255 const clientVersion = (
256 JSON.parse(readFileSync(CLIENT_PKG_JSON, 'utf8')) as { version: string }
257 ).version
258 const dtsHash = createHash('sha256')
259 .update(readFileSync(ENDPOINTS_DTS))
260 .digest('hex')
261​
262 const sortedIds = [...overrides.keys()].sort()
263 const entries = sortedIds
264 .map((id) => {
265 const entry = overrides.get(id)!
266 const pairs = ROLE_ORDER.filter((role) => entry[role]).map(
267 (role) => `${role}: '${entry[role]}'`,
268 )
269 return ` '${id}': { ${pairs.join(', ')} },`
270 })
271 .join('\n')
272​
273 // Union of every field name the runtime mapper may emit: the per-role
274 // defaults plus every field referenced by an override.
275 const fieldNames = new Set<string>(Object.values(DEFAULTS))
276 for (const entry of overrides.values()) {
277 for (const field of Object.values(entry)) fieldNames.add(field)
278 }
279 const fieldNameUnion = [...fieldNames]
280 .sort()
281 .map((name) => ` | '${name}'`)
282 .join('\n')
283​
284 return `/* eslint-disable */
285// ---------------------------------------------------------------------------
286// AUTO-GENERATED — do not edit by hand.
287//
288// Generated from @fal-ai/client@${clientVersion} EndpointTypeMap by
289// scripts/generate-fal-image-field-map.ts. Regenerate after bumping
290// @fal-ai/client:
291//
292// pnpm tsx scripts/generate-fal-image-field-map.ts
293//
294// Maps fal endpoint ids to the image-conditioning input fields they accept
295// whenever those differ from the defaults in image-inputs.ts. Endpoints
296// matching the defaults are omitted. The \`satisfies\` clause below checks
297// every field name against the SDK's endpoint input types at compile time
298// (type-only import — nothing from endpoints.d.ts is shipped at runtime).
299// ---------------------------------------------------------------------------
300import type { EndpointTypeMap } from '@fal-ai/client/endpoints'
301​
302/** sha256 of the endpoints.d.ts this file was generated from. */
303export const FAL_ENDPOINTS_DTS_SHA256 =
304 '${dtsHash}'
305​
306/** Every input field name the image-input mappers may emit. */
307export type FalImageFieldName =
308${fieldNameUnion}
309​
310/**
311 * Per-role input-field overrides. Roles: \`single\` / \`multi\` route unroled
312 * source images; the rest mirror \`MediaInputRole\` (\`start\` / \`end\` map the
313 * \`start_frame\` / \`end_frame\` roles).
314 */
315export interface FalImageFieldOverride {
316 single?: string
317 multi?: string
318 mask?: string
319 control?: string
320 reference?: string
321 start?: string
322 end?: string
324​
325type InputFieldOf<K extends keyof EndpointTypeMap> = Extract<
326 keyof EndpointTypeMap[K]['input'],
327 string
329​
330export const FAL_IMAGE_FIELD_OVERRIDES = {
331${entries}
332} as const satisfies {
333 [K in keyof EndpointTypeMap]?: {
334 [Role in keyof FalImageFieldOverride]?: InputFieldOf<K>
335 }
339​
340// ---------------------------------------------------------------------------
341// Main
342// ---------------------------------------------------------------------------
343​
344const endpoints = extractEndpointInputs()
345const overrides = computeOverrides(endpoints)
346const output = render(overrides)
347​
348if (process.argv.includes('--check')) {
349 const current = readFileSync(OUT_FILE, 'utf8')
350 if (current !== output) {
351 console.error(
352 'image-field-overrides.ts is stale. Run: pnpm tsx scripts/generate-fal-image-field-map.ts',
353 )
354 process.exit(1)
355 }
356 console.log('image-field-overrides.ts is up to date.')
357} else {
358 writeFileSync(OUT_FILE, output)
359 console.log(
360 `Wrote ${overrides.size} endpoint overrides (of ${endpoints.size} endpoints) to ${OUT_FILE}`,
361 )