The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Conformance tests: uploads, chained steps, film gaps, lyrics, maxima and unknown fields
Adarsh11c4345521ec
diff --git a/tests/fixtures/provider-schemas/fal/fal-ai__ffmpeg-api__merge-audio-video.json b/tests/fixtures/provider-schemas/fal/fal-ai__ffmpeg-api__merge-audio-video.jsonnew file mode 100644index 00000000..57b80d07--- /dev/null+++ b/tests/fixtures/provider-schemas/fal/fal-ai__ffmpeg-api__merge-audio-video.json@@ -0,0 +1,328 @@+{+ "components": {+ "schemas": {+ "FfmpegApiMergeAudioVideoInput": {+ "properties": {+ "audio_url": {+ "description": "URL of the audio file to use as the audio track",+ "examples": [+ "https://storage.googleapis.com/falserverless/example_inputs/ffmpeg-audio.wav"+ ],+ "title": "Audio Url",+ "type": "string"+ },+ "start_offset": {+ "default": 0,+ "description": "Offset in seconds for when the audio should start relative to the video",+ "minimum": 0,+ "title": "Start Offset",+ "type": "number"+ },+ "video_url": {+ "description": "URL of the video file to use as the video track",+ "examples": [+ "https://storage.googleapis.com/falserverless/example_inputs/ffmpeg-video.mp4"+ ],+ "title": "Video Url",+ "type": "string"+ }+ },+ "required": [+ "video_url",+ "audio_url"+ ],+ "title": "CombineInput",+ "type": "object",+ "x-fal-order-properties": [+ "video_url",+ "audio_url",+ "start_offset"+ ]+ },+ "FfmpegApiMergeAudioVideoOutput": {+ "properties": {+ "video": {+ "$ref": "#/components/schemas/File",+ "description": "Output video with merged audio."+ }+ },+ "required": [+ "video"+ ],+ "title": "CombineOutput",+ "type": "object",+ "x-fal-order-properties": [+ "video"+ ]+ },+ "File": {+ "properties": {+ "content_type": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The mime type of the file.",+ "examples": [+ "image/png"+ ],+ "title": "Content Type"+ },+ "file_name": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The name of the file. It will be auto-generated if not provided.",+ "examples": [+ "z9RV14K95DvU.png"+ ],+ "title": "File Name"+ },+ "file_size": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "description": "The size of the file in bytes.",+ "examples": [+ 4404019+ ],+ "title": "File Size"+ },+ "url": {+ "description": "The URL where the file can be downloaded from.",+ "title": "Url",+ "type": "string"+ }+ },+ "required": [+ "url"+ ],+ "title": "File",+ "type": "object",+ "x-fal-order-properties": [+ "url",+ "content_type",+ "file_name",+ "file_size"+ ]+ },+ "QueueStatus": {+ "properties": {+ "cancel_url": {+ "description": "The cancel url.",+ "type": "string"+ },+ "logs": {+ "additionalProperties": true,+ "description": "The logs.",+ "type": "object"+ },+ "metrics": {+ "additionalProperties": true,+ "description": "The metrics.",+ "type": "object"+ },+ "queue_position": {+ "description": "The queue position.",+ "type": "integer"+ },+ "request_id": {+ "description": "The request id.",+ "type": "string"+ },+ "response_url": {+ "description": "The response url.",+ "type": "string"+ },+ "status": {+ "enum": [+ "IN_QUEUE",+ "IN_PROGRESS",+ "COMPLETED"+ ],+ "type": "string"+ },+ "status_url": {+ "description": "The status url.",+ "type": "string"+ }+ },+ "required": [+ "status",+ "request_id"+ ],+ "type": "object"+ }+ },+ "securitySchemes": {+ "apiKeyAuth": {+ "description": "Fal Key",+ "in": "header",+ "name": "Authorization",+ "type": "apiKey"+ }+ }+ },+ "info": {+ "description": "The OpenAPI schema for the fal-ai/ffmpeg-api/merge-audio-video queue.",+ "title": "Queue OpenAPI for fal-ai/ffmpeg-api/merge-audio-video",+ "version": "1.0.0",+ "x-fal-metadata": {+ "about": "Combine",+ "category": "video-to-video",+ "documentationUrl": "https://fal.ai/models/fal-ai/ffmpeg-api/merge-audio-video/api",+ "endpointId": "fal-ai/ffmpeg-api/merge-audio-video",+ "playgroundUrl": "https://fal.ai/models/fal-ai/ffmpeg-api/merge-audio-video",+ "thumbnailUrl": "https://storage.googleapis.com/fal_cdn/fal/Sound-5.jpg"+ }+ },+ "openapi": "3.1.0",+ "paths": {+ "/fal-ai/ffmpeg-api/merge-audio-video": {+ "post": {+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FfmpegApiMergeAudioVideoInput"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QueueStatus"+ }+ }+ },+ "description": "The request status."+ }+ }+ }+ },+ "/fal-ai/ffmpeg-api/merge-audio-video/requests/{request_id}": {+ "get": {+ "parameters": [+ {+ "in": "path",+ "name": "request_id",+ "required": true,+ "schema": {+ "description": "Request ID",+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/FfmpegApiMergeAudioVideoOutput"+ }+ }+ },+ "description": "Result of the request."+ }+ }+ }+ },+ "/fal-ai/ffmpeg-api/merge-audio-video/requests/{request_id}/cancel": {+ "put": {+ "parameters": [+ {+ "in": "path",+ "name": "request_id",+ "required": true,+ "schema": {+ "description": "Request ID",+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "properties": {+ "success": {+ "description": "Whether the request was cancelled successfully.",+ "type": "boolean"+ }+ },+ "type": "object"+ }+ }+ },+ "description": "The request was cancelled."+ }+ }+ }+ },+ "/fal-ai/ffmpeg-api/merge-audio-video/requests/{request_id}/status": {+ "get": {+ "parameters": [+ {+ "in": "path",+ "name": "request_id",+ "required": true,+ "schema": {+ "description": "Request ID",+ "type": "string"+ }+ },+ {+ "in": "query",+ "name": "logs",+ "required": false,+ "schema": {+ "description": "Whether to include logs (`1`) in the response or not (`0`).",+ "type": "number"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QueueStatus"+ }+ }+ },+ "description": "The request status."+ }+ }+ }+ }+ },+ "security": [+ {+ "apiKeyAuth": []+ }+ ],+ "servers": [+ {+ "url": "https://queue.fal.run"+ }+ ]+}diff --git a/tests/fixtures/provider-schemas/index.json b/tests/fixtures/provider-schemas/index.jsonindex 9d309a56..2bb27e6a 100644--- a/tests/fixtures/provider-schemas/index.json+++ b/tests/fixtures/provider-schemas/index.json@@ -5,6 +5,7 @@"bria/video/background-removal/green-screen-despill","elevenlabs/music/v2.5","fal-ai/deepfilternet3",+ "fal-ai/ffmpeg-api/merge-audio-video","fal-ai/kandinsky6-lite/image-to-video","fal-ai/kandinsky6-lite/text-to-video","fal-ai/kandinsky6-pro/image-to-video",diff --git a/tests/helpers/provider-schemas.ts b/tests/helpers/provider-schemas.tsnew file mode 100644index 00000000..3a0f2ad8--- /dev/null+++ b/tests/helpers/provider-schemas.ts@@ -0,0 +1,221 @@+/**+ * The providers' own API schemas kept in tests/fixtures/provider-schemas/ (scripts/refresh-provider-schemas.mjs, public GETs+ * only), read for the conformance tests: an endpoint's input and output schema, an ajv validator for each, a documented+ * answer made from the output schema, and the body fal.ts or replicate.ts sends for a planned run.+ */+import fs from "node:fs";+import path from "node:path";+import Ajv, { type ValidateFunction } from "ajv";+import { loraEndpointFor, routeLoraField } from "@/lib/catalog/loras";+import { buildPayload } from "@/lib/catalog/payload";+import type { planGeneration } from "@/lib/catalog/plan";+import type { GenerationRequest, GenInput, GenParams, ModelRoute } from "@/lib/catalog/types";++export const SCHEMA_DIR = path.join(__dirname, "../fixtures/provider-schemas");+export const SCHEMA_INDEX = JSON.parse(fs.readFileSync(path.join(SCHEMA_DIR, "index.json"), "utf8")) as { fal: string[]; replicate: string[] };+export const schemaFile = (provider: string, endpoint: string) => path.join(SCHEMA_DIR, provider, `${endpoint.replaceAll("/", "__")}.json`);++export type Provider = "fal" | "replicate";++/** The parts of a JSON schema (OpenAPI 3) read here. */+export interface Schema {+ $ref?: string;+ examples?: unknown[];+ example?: unknown;+ anyOf?: Schema[];+ oneOf?: Schema[];+ allOf?: Schema[];+ default?: unknown;+ enum?: unknown[];+ type?: string | string[];+ properties?: Record<string, Schema>;+ items?: Schema;+ title?: string;+ format?: string;+ minimum?: number;+ maximum?: number;+ maxItems?: number;+ maxLength?: number;+ additionalProperties?: boolean | Schema;+}+type Body = { content?: Record<string, { schema?: Schema }> };+export type Doc = {+ paths?: Record<string, Record<string, { requestBody?: Body; responses?: Record<string, Body> }>>;+ components?: { schemas?: Record<string, Schema> };+};++const docs = new Map<string, Doc>();+/** An endpoint's OpenAPI document (fal's queue OpenAPI; Replicate's version openapi_schema). */+export function schemaDoc(provider: Provider, endpoint: string): Doc {+ const key = `${provider}:${endpoint}`;+ if (!docs.has(key)) {+ const raw = JSON.parse(fs.readFileSync(schemaFile(provider, endpoint), "utf8"));+ docs.set(key, provider === "fal" ? raw : raw.openapi_schema);+ }+ return docs.get(key)!;+}++export const refName = (s: Schema | undefined): string | undefined => (typeof s?.$ref === "string" ? s.$ref.split("/").pop() : undefined);++/** The endpoint's input and output schema names (fal: the queue submit body and result; Replicate: Input and Output). */+export function schemaNames(provider: Provider, endpoint: string): { input: string; output: string } {+ if (provider === "replicate") return { input: "Input", output: "Output" };+ const d = schemaDoc(provider, endpoint);+ const submit = d.paths?.[`/${endpoint}`]?.post;+ const result = d.paths?.[`/${endpoint}/requests/{request_id}`]?.get;+ const input = refName(submit?.requestBody?.content?.["application/json"]?.schema);+ const output = refName(result?.responses?.["200"]?.content?.["application/json"]?.schema);+ if (!input || !output) throw new Error(`${endpoint}: no input or output schema in its fixture`);+ return { input, output };+}++/** The endpoint's input schema, as written. */+export function inputSchema(provider: Provider, endpoint: string): Schema {+ return schemaDoc(provider, endpoint).components!.schemas![schemaNames(provider, endpoint).input];+}++// OpenAPI keywords ajv doesn't know (x-*, examples, nullable) are left to it as annotations; "uri" and other formats are+// not checked (a run's files are URLs the provider fetches).+const ajv = new Ajv({ strict: false, allErrors: true, validateFormats: false, validateSchema: false });+const validators = new Map<string, ValidateFunction>();+export function schemaValidator(provider: Provider, endpoint: string, name: string): ValidateFunction {+ const id = `${provider}:${endpoint}`;+ const key = `${id}#${name}`;+ if (!validators.has(key)) {+ if (!ajv.getSchema(id)) ajv.addSchema({ $id: id, components: schemaDoc(provider, endpoint).components }, id);+ validators.set(key, ajv.compile({ $ref: `${id}#/components/schemas/${name}` }));+ }+ return validators.get(key)!;+}++export const errorsOf = (fn: ValidateFunction) =>+ (fn.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}${e.params && "allowedValues" in e.params ? ` ${JSON.stringify(e.params.allowedValues)}` : ""}`);++/**+ * What's wrong with a request body for the endpoint, in words; [] when it fits. Besides the schema itself, every top-level+ * key must be one of its fields: most fal schemas don't forbid others, and fal ignores them without a word, so a misspelled+ * or unknown field would otherwise go unnoticed.+ */+export function bodyProblems(provider: Provider, endpoint: string, body: Record<string, unknown>): string[] {+ const fn = schemaValidator(provider, endpoint, schemaNames(provider, endpoint).input);+ const out = fn(body) ? [] : errorsOf(fn);+ const props = Object.keys(inputSchema(provider, endpoint).properties ?? {});+ for (const k of Object.keys(body)) if (!props.includes(k)) out.push(`/${k} is not a field of ${endpoint}`);+ return out;+}++// ---------------------------------------------------------------------------+// The runs the studio sends++export const IMG = "https://v3b.fal.media/files/in/start.png";+export const END = "https://v3b.fal.media/files/in/end.png";+export const CLIP = "https://v3b.fal.media/files/in/clip.mp4";+export const VOICE = "https://v3b.fal.media/files/in/voice.mp3";+export const SONG = "https://v3b.fal.media/files/in/song.mp3";+export const GLB = "https://v3b.fal.media/files/in/model.glb";+export const PROMPT = "A dancer in a silver coat turns slowly under warm stage light, the camera drifting closer";++export type Inputs = NonNullable<GenerationRequest["inputs"]>;+export interface Variant {+ label: string;+ inputs: Inputs;+ params: GenParams;+ prompt?: string;+ negativePrompt?: string;+}++/**+ * The body fal.ts or replicate.ts would send for this route (their submit: LoRA field, LoRA endpoint, a song uploaded first),+ * and the upload's own body when a song goes through Mureka's files/upload first.+ */+export function routeRequest(route: ModelRoute, input: GenInput): { endpoint: string; body: Record<string, unknown>; upload?: { endpoint: string; body: Record<string, unknown> } } {+ const map = { ...route.map, loras: routeLoraField(route) };+ const body = buildPayload(map, input);+ const song = map.songSource;+ let upload: { endpoint: string; body: Record<string, unknown> } | undefined;+ if (song && body[song.songId] === undefined) {+ // fal.ts uploadSong: { file_url, purpose } to the upload endpoint, then the id it answers in the tool's upload field.+ upload = { endpoint: song.upload.endpoint, body: { file_url: input.audio, purpose: song.upload.purpose } };+ body[song.uploadId] = "mureka-upload-id";+ }+ return { endpoint: loraEndpointFor({ ...route, map }, input.loras).split(":")[0], body, ...(upload && { upload }) };+}++/** The input the server hands the adapter (generations.ts handOver), files already uploaded. */+export function handOverInput(plan: ReturnType<typeof planGeneration>, v: Pick<Variant, "inputs" | "negativePrompt">): GenInput {+ // A song extended at its end (or, before its start, at 0) unless the run says where, as handOver sets it.+ const extendAt = plan.op === "song-extend" && plan.params.startTime === undefined ? (plan.params.extra?.extend_type === "head" ? 0 : plan.params.sourceDuration) : undefined;+ return {+ ...plan.params,+ ...(extendAt !== undefined && { startTime: extendAt }),+ prompt: plan.prompt || undefined,+ negativePrompt: v.negativePrompt,+ images: v.inputs.images ?? [],+ endImage: v.inputs.endImage,+ video: v.inputs.video,+ audio: v.inputs.audio,+ videos: v.inputs.videos ?? [],+ audios: v.inputs.audios ?? [],+ model3d: v.inputs.model3d,+ loras: plan.loras,+ };+}++// ---------------------------------------------------------------------------+// Answers made from the output schemas++/** Replicate's example prediction's output (the model page's own), else one made from the Output schema. */+export function replicateAnswer(model: string, d: Doc): unknown {+ const raw = JSON.parse(fs.readFileSync(schemaFile("replicate", model), "utf8"));+ return raw.example_prediction?.output ?? exampleOf(d.components?.schemas?.Output, d);+}++/** The endpoint's documented answer: Replicate's example prediction, else a value made from its output schema. */+export function documentedAnswer(provider: Provider, endpoint: string): unknown {+ const d = schemaDoc(provider, endpoint);+ return provider === "replicate" ? replicateAnswer(endpoint, d) : exampleOf(d.components?.schemas?.[schemaNames(provider, endpoint).output], d);+}++const EXT: Record<string, string> = { image: "png", video: "mp4", audio: "mp3", model3d: "glb" };+const MIME: Record<string, string> = { image: "image/png", video: "video/mp4", audio: "audio/mpeg", model3d: "model/gltf-binary" };++/**+ * A value for a schema: its own example where it has one, else one of its type. Every optional field is filled too (a+ * still fal may send beside the video is part of the answer), flags are false, and a file with no example gets a URL with+ * the extension its title or field name suggests.+ */+export function exampleOf(schema: Schema | undefined, d: Doc, key = "", depth = 0): unknown {+ if (!schema || depth > 12) return undefined;+ if (Array.isArray(schema.examples) && schema.examples.length) return schema.examples[0];+ if (schema.example !== undefined) return schema.example;+ const ref = refName(schema);+ if (ref) return exampleOf(d.components?.schemas?.[ref], d, key, depth + 1);+ const branch = schema.anyOf ?? schema.oneOf;+ if (branch) return exampleOf(branch.find((b) => b.type !== "null") ?? branch[0], d, key, depth + 1);+ if (schema.allOf) return Object.assign({}, ...schema.allOf.map((s) => exampleOf(s, d, key, depth + 1)));+ if (schema.default !== undefined && schema.default !== null) return schema.default;+ if (Array.isArray(schema.enum)) return schema.enum[0];+ const type = Array.isArray(schema.type) ? schema.type.find((t) => t !== "null") : schema.type;+ if (type === "object" || schema.properties) {+ const props = Object.entries(schema.properties ?? {}).map(([k, s]) => [k, exampleOf(s, d, k, depth + 1)] as const);+ const obj: Record<string, unknown> = Object.fromEntries(props.filter(([, v]) => v !== undefined));+ // A file object with no example of its own (fal's shared File and Image schemas carry a PNG's name and type as their+ // fields' examples): a file of the kind its field name or title says, with a URL, name and type to match.+ if ("url" in (schema.properties ?? {})) {+ const words = `${key} ${schema.title ?? ""}`;+ const kind = /video/i.test(words) ? "video" : /audio|song|stem|vocal|track|voice/i.test(words) ? "audio" : /image|cover|thumb|picture/i.test(words) ? "image" : "model3d";+ obj.url = `https://v3b.fal.media/files/out/${key || "file"}.${EXT[kind]}`;+ if ("file_name" in obj) obj.file_name = `${key || "file"}.${EXT[kind]}`;+ if ("content_type" in obj) obj.content_type = MIME[kind];+ }+ return obj;+ }+ if (type === "array") {+ const item = exampleOf(schema.items, d, key, depth + 1);+ return item === undefined ? [] : [item];+ }+ if (type === "boolean") return false;+ if (type === "integer" || type === "number") return schema.minimum ?? 1;+ if (type === "string") return /url|uri/i.test(key) || schema.format === "uri" ? `https://v3b.fal.media/files/out/${key}.bin` : "text";+ return undefined;+}diff --git a/tests/provider-conformance-paths.test.ts b/tests/provider-conformance-paths.test.tsnew file mode 100644index 00000000..65c85f48--- /dev/null+++ b/tests/provider-conformance-paths.test.ts@@ -0,0 +1,333 @@+/**+ * The untested hosted routes' paths that tests/provider-conformance.test.ts doesn't reach with its one-setting-at-a-time+ * variants, checked with ajv against the providers' own schemas (tests/fixtures/provider-schemas/, public GETs only):+ *+ * - Mureka's files/upload: the upload's own body ({file_url, purpose}) and the id its answer gives; a song of Mureka's own+ * going by its song_id instead.+ * - Clean dialogue on a video: extract-audio (FLAC), DeepFilterNet 3 and merge-audio-video, each step's body; VEED's video.+ * - Fuobe Animation's cloud film: every gap length the film sends to Wan 2.2's /lora (17-81 frames in steps of 4 at 16 fps),+ * with the user's own LoRAs on top of AniSora.+ * - Songs with lyrics (Mureka, MiniMax Music 3, Lyria 3.5 in its prompt), instrumentals, and the API's limits on lengths.+ * - Pictures and clips beside the main input (Lyria's picture, Insert's references, Turbo extend's voices), each list at+ * the catalog's own maximum, and the 12-file total.+ * - The longest prompt, the largest seeds, and lengths an API caller sends outside the composer's lists.+ *+ * Every body is also held to the schema's own fields: an unknown key fails, even where fal would ignore it.+ */+import { describe, expect, it } from "vitest";+import { cleanDialogueProblem, planCleanDialogue } from "@/lib/av/clean-dialogue";+import { getModel, getPreset } from "@/lib/catalog";+import { extractOutputs } from "@/lib/catalog/payload";+import { planGeneration, routesFor } from "@/lib/catalog/plan";+import type { GenerationRequest, GenParams, LoraRef } from "@/lib/catalog/types";+import { GAP_STEP, MAX_GAP_FRAMES, MIN_GAP_FRAMES } from "@/lib/inbetween";+import { LYRICS_PARAM, SONG_ID_PARAM } from "@/lib/lyrics";+import { bodyProblems, CLIP, documentedAnswer, END, handOverInput, IMG, PROMPT, routeRequest, schemaNames, SCHEMA_INDEX, SONG, VOICE, type Inputs } from "./helpers/provider-schemas";++const LYRICS = "[Verse]\nNeon light on the runway tonight\n\n[Chorus]\nWalk it, own it";+const refs = (kind: "png" | "mp4" | "mp3", n: number) => Array.from({ length: n }, (_, i) => `https://v3b.fal.media/files/in/ref${i}.${kind}`);++interface Run {+ modelId: string;+ op?: GenerationRequest["op"];+ prompt?: string;+ inputs?: Inputs;+ params?: GenParams;+ loras?: LoraRef[];+ engine?: GenerationRequest["engine"];+}++/** The plan, the route it goes to, and what fal.ts or replicate.ts sends for it (a song's upload too). */+function sent(run: Run) {+ const model = getModel(run.modelId)!;+ const req: GenerationRequest = { feature: model.kind, ...run, inputs: run.inputs ?? {}, params: run.params ?? {} };+ const plan = planGeneration(req, getModel, getPreset);+ const route = routesFor(plan.model, plan.op, plan.params).find((r) => r.provider !== "comfyui")!;+ const out = routeRequest(route, handOverInput(plan, { inputs: run.inputs ?? {} }));+ return { plan, route, ...out };+}++/** The run's body (and its upload's), held to the endpoint's schema: [] when it fits. */+function problems(run: Run): string[] {+ const s = sent(run);+ const provider = s.route.provider as "fal" | "replicate";+ const out = bodyProblems(provider, s.endpoint, s.body).map((p) => `${s.endpoint} ${p} ${JSON.stringify(s.body)}`);+ if (s.upload) out.push(...bodyProblems("fal", s.upload.endpoint, s.upload.body).map((p) => `${s.upload!.endpoint} ${p}`));+ return out;+}++const fits = (run: Run) => expect(problems(run), JSON.stringify(run)).toEqual([]);++describe("Mureka's song tools: the upload, its answer, and a song sent by its id", () => {+ for (const [modelId, purpose] of [+ ["mureka-extend", "audio"],+ ["mureka-remix", "remix"],+ ] as const) {+ const run: Run = { modelId, prompt: "Warm synth-pop, female vocal", inputs: { audio: SONG }, params: { sourceDuration: 120, extra: { [LYRICS_PARAM]: LYRICS } } };++ it(`${modelId}: a song Mureka didn't make goes through files/upload as {file_url, purpose: "${purpose}"}`, () => {+ const s = sent(run);+ expect(s.upload).toEqual({ endpoint: "mureka/api/files/upload", body: { file_url: SONG, purpose } });+ expect(s.body.upload_audio_id).toBe("mureka-upload-id");+ expect(s.body).not.toHaveProperty("song_id");+ fits(run);+ });++ it(`${modelId}: one of Mureka's own goes by its song_id, with nothing uploaded`, () => {+ const byId: Run = { ...run, params: { ...run.params, extra: { ...run.params!.extra, [SONG_ID_PARAM]: "song_1" } } };+ const s = sent(byId);+ expect(s.upload).toBeUndefined();+ expect(s.body.song_id).toBe("song_1");+ expect(s.body).not.toHaveProperty("upload_audio_id");+ fits(byId);+ });+ }++ it("the upload's documented answer carries the id the tool then takes", () => {+ const answer = documentedAnswer("fal", "mureka/api/files/upload") as { id?: unknown };+ expect(schemaNames("fal", "mureka/api/files/upload").output).toBeTruthy();+ expect(typeof answer.id).toBe("string");+ expect((answer.id as string).length).toBeGreaterThan(0);+ });++ it("a song's documented answer keeps its song_id on the result, for Extend and Remix to send", () => {+ for (const endpoint of ["mureka/v9.5/generate/song", "mureka/v9/generate/song", "mureka/v8/song/extend", "mureka/v8/song/remix"]) {+ const answer = { ...(documentedAnswer("fal", endpoint) as object), song_id: "song_42" };+ const outs = extractOutputs(answer, "music");+ expect(outs.map((o) => [o.kind, o.meta?.songId]), endpoint).toEqual([["audio", "song_42"]]);+ }+ });+});++describe("Clean dialogue on a video in the cloud: each step's body", () => {+ const VIDEO = "/api/files/uploads/2026-11-06/vlog.mp4";++ it("keeps the schemas of every step it sends", () => {+ for (const e of ["fal-ai/workflow-utilities/extract-audio", "fal-ai/deepfilternet3", "fal-ai/ffmpeg-api/merge-audio-video", "veed/clean-audio"]) expect(SCHEMA_INDEX.fal).toContain(e);+ });++ it("DeepFilterNet 3: the soundtrack is extracted as FLAC, cleaned, then put back on the video", () => {+ const plan = planCleanDialogue({ engine: "cloud", media: VIDEO, kind: "video", cleaner: "deepfilternet", seconds: 42 });+ expect(plan.steps.map((s) => [s.request.modelId, s.chain?.map((c) => c.slot)])).toEqual([+ ["extract-soundtrack", undefined],+ ["deepfilternet3", ["audio"]],+ ["merge-audio-video", ["audio"]],+ ]);+ // Each step as the server hands it over: files uploaded, the chained slot filled with the step before's result.+ const filled: Record<string, Inputs> = {+ "extract-soundtrack": { video: CLIP },+ deepfilternet3: { audio: "https://v3b.fal.media/files/out/extracted.flac" },+ "merge-audio-video": { video: CLIP, audio: "https://v3b.fal.media/files/out/clean.flac" },+ };+ const endpoints: string[] = [];+ for (const step of plan.steps) {+ const run: Run = { ...step.request, modelId: step.request.modelId!, inputs: filled[step.request.modelId!] };+ const s = sent(run);+ endpoints.push(s.endpoint);+ fits(run);+ if (s.endpoint === "fal-ai/workflow-utilities/extract-audio") expect(s.body).toEqual({ video_url: CLIP, audio_format: "flac" });+ if (s.endpoint === "fal-ai/ffmpeg-api/merge-audio-video") expect(s.body).toMatchObject({ video_url: CLIP, audio_url: filled["merge-audio-video"].audio });+ }+ expect(endpoints).toEqual(["fal-ai/workflow-utilities/extract-audio", "fal-ai/deepfilternet3", "fal-ai/ffmpeg-api/merge-audio-video"]);+ });++ it("each step's documented answer reads as the file the next step takes", () => {+ expect(extractOutputs(documentedAnswer("fal", "fal-ai/workflow-utilities/extract-audio"), "separate-audio").map((o) => o.kind)).toEqual(["audio"]);+ expect(extractOutputs(documentedAnswer("fal", "fal-ai/deepfilternet3"), "enhance-voice").map((o) => o.kind)).toEqual(["audio"]);+ expect(extractOutputs(documentedAnswer("fal", "fal-ai/ffmpeg-api/merge-audio-video"), "mux").map((o) => o.kind)).toEqual(["video"]);+ });++ it("VEED takes the video itself as its audio_url ('a video's audio track is used'), then the clean voice goes back on it", () => {+ const plan = planCleanDialogue({ engine: "cloud", media: VIDEO, kind: "video", cleaner: "veed", seconds: 42, strength: 0.6 });+ expect(plan.steps.map((s) => s.request.modelId)).toEqual(["veed-clean-audio", "merge-audio-video"]);+ const run: Run = { ...plan.steps[0].request, modelId: "veed-clean-audio", inputs: { video: CLIP } };+ expect(sent(run).body).toEqual({ audio_url: CLIP, output_format: "flac", strength: 0.6 });+ fits(run);+ });++ it("fal's size limits are said before anything is uploaded", () => {+ expect(cleanDialogueProblem({ engine: "cloud", media: VIDEO, kind: "video", cleaner: "deepfilternet", bytes: 100_000_001 })).toMatch(/100 MB/);+ expect(cleanDialogueProblem({ engine: "cloud", media: VIDEO, kind: "video", cleaner: "veed", bytes: 512 * 1024 * 1024 + 1 })).toMatch(/512 MB/);+ });+});++describe("Fuobe Animation's cloud film: every gap the film sends, against Wan 2.2's /lora schema", () => {+ const anim = getModel("fuobe-animation")!;+ // The user's own LoRAs (Wan 2.2 high-noise ones with a hosted copy) on top of AniSora. The schema's loras list has no+ // maxItems; each scale must be 0 to 4 (LoRAWeight.scale).+ const own = (n: number): LoraRef[] =>+ Array.from({ length: n }, (_, i) => ({ file: `my-style-${i}.safetensors`, url: `https://huggingface.co/me/style-${i}/resolve/main/style.safetensors`, hostedUrl: `https://v3b.fal.media/files/loras/style-${i}.safetensors`, strength: 0.8, target: "high" }));++ /** One gap's clip as createKeyframeFilm makes it: start and end frames, as long as the gap's own frames at 16 fps. */+ const gap = (frames: number, extra: Partial<Run> = {}): Run => ({+ modelId: anim.id,+ engine: "cloud",+ op: "flf2v",+ prompt: "a fox leaps. it lands",+ inputs: { images: [IMG], endImage: END },+ params: { aspectRatio: "16:9", resolution: "480p", seed: 42, numOutputs: 1, duration: (frames - 1) / 16 },+ ...extra,+ });++ it("each gap length, 17 to 81 frames in steps of 4, goes to /lora with AniSora and num_frames of that gap", () => {+ for (let f = MIN_GAP_FRAMES; f <= MAX_GAP_FRAMES; f += GAP_STEP) {+ const s = sent(gap(f));+ expect(s.endpoint, `${f}`).toBe("fal-ai/wan/v2.2-a14b/image-to-video/lora");+ expect(s.body.num_frames, `${f}`).toBe(f);+ expect((s.body.loras as { path: string }[]).length, `${f}`).toBe(1);+ fits(gap(f));+ }+ });++ it("the user's own LoRAs go on top of AniSora, AniSora first", () => {+ for (const n of [1, 2, 3, 4]) {+ const run = gap(41, { loras: own(n) });+ const s = sent(run);+ const loras = s.body.loras as { path: string; scale: number; transformer: string }[];+ expect(loras.length, `${n}`).toBe(n + 1);+ expect(loras[0].path, `${n}`).toMatch(/anisora/i);+ for (const l of loras) expect(["high", "low", "both"]).toContain(l.transformer);+ fits(run);+ }+ });++ it("every shape and size the studio offers the film fits", () => {+ for (const aspectRatio of anim.options.aspectRatios ?? []) fits(gap(33, { params: { ...gap(33).params, aspectRatio } }));+ for (const resolution of anim.options.resolutions ?? []) fits(gap(33, { params: { ...gap(33).params, resolution } }));+ fits(gap(33, { params: { ...gap(33).params, seed: 2 ** 31 + 5 } }));+ });+});++describe("Songs: lyrics, instrumentals and the API's limits", () => {+ it("Mureka 9.5 and 9 sing your lyrics with a style of up to 1,024 characters", () => {+ for (const modelId of ["mureka-song", "mureka-9"]) {+ const run: Run = { modelId, prompt: "x".repeat(1024), params: { extra: { [LYRICS_PARAM]: LYRICS } } };+ expect(sent(run).body.lyrics, modelId).toBe(LYRICS);+ fits(run);+ // Without lyrics the description is the whole song's, up to 2,000.+ fits({ modelId, prompt: "x".repeat(2000) });+ }+ });++ it("the instrumentals take their 1,024-character description", () => {+ for (const modelId of ["mureka-9-5-instrumental", "mureka-9-instrumental"]) fits({ modelId, prompt: "x".repeat(1024) });+ });++ it("MiniMax Music 3 sings the user's lyrics, and sends [instrumental] when there are none", () => {+ const sung: Run = { modelId: "minimax-music-3", prompt: PROMPT, params: { extra: { [LYRICS_PARAM]: LYRICS } } };+ expect(sent(sung).body.lyrics).toBe(LYRICS);+ fits(sung);+ expect(sent({ modelId: "minimax-music-3", prompt: PROMPT }).body.lyrics).toBe("[instrumental]");+ });++ it("Lyria 3.5 reads the lyrics after the prompt, within its 5,000 characters, and takes a picture", () => {+ const run: Run = { modelId: "lyria-3-5", prompt: "Glossy synth-pop", inputs: { images: [IMG] }, params: { extra: { [LYRICS_PARAM]: LYRICS } } };+ const s = sent(run);+ expect(String(s.body.prompt)).toContain("Walk it, own it");+ expect(s.body.image_url).toBe(IMG);+ fits(run);+ fits({ modelId: "lyria-3-5", prompt: "x".repeat(5000) });+ });++ it("an API caller's length is kept inside the API's own limits (whole seconds or ms where the schema says integer)", () => {+ for (const duration of [1, 90.5, 151.4, 300, 900]) {+ fits({ modelId: "mureka-song", prompt: PROMPT, params: { duration } });+ fits({ modelId: "minimax-music-3", prompt: PROMPT, params: { duration } });+ fits({ modelId: "elevenlabs-music-2-5", prompt: PROMPT, params: { duration } });+ }+ });++ it("Extend starts where the song ends, in whole milliseconds, wherever that is", () => {+ for (const sourceDuration of [61.3457, 120, 299.9999]) {+ const run: Run = { modelId: "mureka-extend", inputs: { audio: SONG }, params: { sourceDuration, extra: { [LYRICS_PARAM]: LYRICS } } };+ expect(Number.isInteger(sent(run).body.extend_at), `${sourceDuration}`).toBe(true);+ fits(run);+ }+ });+});++describe("Pictures, clips and voices at the catalog's own maximums", () => {+ it("references: each list at its maximum, and as many as the 12-file total allows", () => {+ for (const modelId of ["minimax-h3-max-turbo-refs", "vidu-q4", "minimax-h3-lite", "minimax-h3-highspeed"]) {+ const o = getModel(modelId)!.options;+ const base: Run = { modelId, op: "ref2v", prompt: PROMPT, inputs: {} };+ fits({ ...base, inputs: { images: refs("png", o.maxImages ?? 1) } });+ if (o.maxVideos) fits({ ...base, inputs: { images: [IMG], videos: refs("mp4", o.maxVideos) } });+ if (o.maxAudios) fits({ ...base, inputs: { images: [IMG], audios: refs("mp3", o.maxAudios) } });+ if (o.maxReferences) {+ const images = o.maxReferences - (o.maxVideos ?? 0) - (o.maxAudios ?? 0);+ fits({ ...base, inputs: { images: refs("png", images), videos: refs("mp4", o.maxVideos ?? 0), audios: refs("mp3", o.maxAudios ?? 0) } });+ // One more is refused before it is sent.+ expect(() => sent({ ...base, inputs: { images: refs("png", images + 1), videos: refs("mp4", o.maxVideos ?? 0), audios: refs("mp3", o.maxAudios ?? 0) } }), modelId).toThrow(/up to 12 references in all/);+ }+ }+ });++ it("Insert a moment takes its 9 pictures and 3 clips beside the clip it goes into", () => {+ const run: Run = {+ modelId: "minimax-h3-max-insert",+ prompt: PROMPT,+ inputs: { video: CLIP, images: refs("png", 9), videos: refs("mp4", 3) },+ params: { sourceDuration: 8, sourceSize: { width: 1280, height: 720 }, startTime: 2, endTime: 5 },+ };+ const s = sent(run);+ expect([(s.body.reference_image_urls as string[]).length, (s.body.reference_video_urls as string[]).length]).toEqual([9, 3]);+ fits(run);+ });++ it("Turbo extend takes up to three voices beside the clip", () => {+ for (const n of [1, 2, 3]) fits({ modelId: "minimax-h3-max-turbo-extend", prompt: PROMPT, inputs: { video: CLIP, audios: refs("mp3", n) }, params: { sourceDuration: 8, sourceSize: { width: 1280, height: 720 } } });+ });+});++describe("Values at the edges: the longest prompt, the largest seeds, lengths outside the lists", () => {+ it("the longest prompt each route takes fits its schema", () => {+ for (const [modelId, op, inputs] of [+ ["vidu-q4", "i2v", { images: [IMG] }],+ ["vidu-q4", "ref2v", { images: [IMG] }],+ ["meshy-7-retexture", "retexture-3d", { model3d: "https://v3b.fal.media/files/in/model.glb" }],+ ["meshy-6-retexture", "retexture-3d", { model3d: "https://v3b.fal.media/files/in/model.glb" }],+ ["mureka-remix", "song-remix", { audio: SONG }],+ ] as [string, GenerationRequest["op"], Inputs][]) {+ const route = getModel(modelId)!.routes.find((r) => r.op === op)!;+ const max = route.map!.promptMax!;+ expect(max, modelId).toBeGreaterThan(0);+ fits({ modelId, op, prompt: "y".repeat(max), inputs, params: { sourceDuration: 120, extra: { [LYRICS_PARAM]: LYRICS } } });+ }+ });++ it("seeds past a schema's top are folded into it, on every route whose schema bounds the seed", () => {+ const runs: Run[] = [+ { modelId: "minimax-h3-max-lipsync", inputs: { images: [IMG], audio: VOICE }, params: { sourceDuration: 12 } },+ { modelId: "minimax-h3-max-insert", prompt: PROMPT, inputs: { video: CLIP }, params: { sourceDuration: 8, sourceSize: { width: 1280, height: 720 }, startTime: 2, endTime: 5 } },+ { modelId: "minimax-h3-max-turbo", prompt: PROMPT },+ { modelId: "minimax-h3-max-turbo-refs", op: "ref2v", prompt: PROMPT, inputs: { images: [IMG] } },+ { modelId: "minimax-h3-max-look-vhs", prompt: PROMPT },+ ];+ for (const run of runs) for (const seed of [0, 2 ** 31 - 1, 2 ** 31, 2 ** 32 + 7, 999_999_999_999]) fits({ ...run, params: { ...run.params, seed } });+ });++ it("a length outside the composer's list (an API caller, Assist) goes as one the route takes", () => {+ for (const [modelId, inputs] of [+ ["vidu-q4", { images: [IMG] }],+ ["minimax-h3-max-turbo", {}],+ ["minimax-h3-max-turbo", { images: [IMG] }],+ ["minimax-h3-lite", {}],+ ] as [string, Inputs][]) {+ for (const duration of [4.5, 7, 9.25, 14.9]) fits({ modelId, prompt: PROMPT, inputs, params: { duration } });+ }+ });++ it("Cinema's lengths for Turbo, 1 to 15 s, fit its schema", () => {+ for (const duration of [1, 2, 7, 9, 11, 14, 15]) fits({ modelId: "minimax-h3-max-turbo", prompt: PROMPT, params: { duration } });+ });++ it("settings together, not only one at a time: every shape with every size and length", () => {+ for (const modelId of ["minimax-h3-max-turbo", "minimax-h3-lite", "kandinsky-6"]) {+ const o = getModel(modelId)!.options;+ for (const aspectRatio of o.aspectRatios ?? [undefined])+ for (const resolution of o.resolutions ?? [undefined])+ for (const duration of o.durations ?? [undefined]) fits({ modelId, prompt: PROMPT, params: { aspectRatio, resolution, duration } });+ }+ });+});diff --git a/tests/provider-conformance.test.ts b/tests/provider-conformance.test.tsindex 03709a4f..65408f89 100644--- a/tests/provider-conformance.test.ts+++ b/tests/provider-conformance.test.ts@@ -4,108 +4,44 @@** - Each route's request, for every setting the studio offers it (shape, size, length, the model's own controls, sound,* seed, negative words, references up to the model's limits), is built by the real planner and payload builder (as- * fal.ts and replicate.ts submit it) and validated with ajv against the endpoint's input schema.+ * fal.ts and replicate.ts submit it) and validated with ajv against the endpoint's input schema, with no field the+ * schema doesn't name (a song's files/upload body too).* - Each endpoint's answer, made from its output schema (its examples, else a value of each field's type), is read by* the real result parser: it gives the files the run makes, of the kind the run makes, and nothing else.*+ * Paths these one-setting-at-a-time variants don't reach (uploads, chained steps, film gaps, lyrics, maxima together, edge+ * values) are in tests/provider-conformance-paths.test.ts; the shared readers are in tests/helpers/provider-schemas.ts.+ ** A provider that changes an endpoint shows up as a fixture diff when the schemas are refreshed, and here as the request* or answer that no longer fits.*/import fs from "node:fs";-import path from "node:path";-import Ajv, { type ValidateFunction } from "ajv";import { describe, expect, it } from "vitest";import { getModel, getPreset, MODELS } from "@/lib/catalog";import { HOSTED_UNTESTED_ENDPOINTS, isHostedUntested } from "@/lib/catalog/hosted-untested";-import { loraEndpointFor, routeLoraField } from "@/lib/catalog/loras";-import { buildPayload, extractOutputs } from "@/lib/catalog/payload";+import { extractOutputs } from "@/lib/catalog/payload";import { planGeneration, routesFor } from "@/lib/catalog/plan";-import { operationOutput, type GenerationRequest, type GenInput, type GenParams, type ModelDef, type ModelRoute, type Operation } from "@/lib/catalog/types";--const DIR = path.join(__dirname, "fixtures/provider-schemas");-const INDEX = JSON.parse(fs.readFileSync(path.join(DIR, "index.json"), "utf8")) as { fal: string[]; replicate: string[] };-const fileFor = (provider: string, endpoint: string) => path.join(DIR, provider, `${endpoint.replaceAll("/", "__")}.json`);--/** The parts of a JSON schema (OpenAPI 3) read here. */-interface Schema {- $ref?: string;- examples?: unknown[];- example?: unknown;- anyOf?: Schema[];- oneOf?: Schema[];- allOf?: Schema[];- default?: unknown;- enum?: unknown[];- type?: string | string[];- properties?: Record<string, Schema>;- items?: Schema;- title?: string;- format?: string;- minimum?: number;-}-type Body = { content?: Record<string, { schema?: Schema }> };-type Doc = {- paths?: Record<string, Record<string, { requestBody?: Body; responses?: Record<string, Body> }>>;- components?: { schemas?: Record<string, Schema> };-};-const docs = new Map<string, Doc>();-function doc(provider: "fal" | "replicate", endpoint: string): Doc {- const key = `${provider}:${endpoint}`;- if (!docs.has(key)) {- const raw = JSON.parse(fs.readFileSync(fileFor(provider, endpoint), "utf8"));- docs.set(key, provider === "fal" ? raw : raw.openapi_schema);- }- return docs.get(key)!;-}--const refName = (s: Schema | undefined): string | undefined => (typeof s?.$ref === "string" ? s.$ref.split("/").pop() : undefined);--/** The endpoint's input and output schema names (fal: the queue submit body and result; Replicate: Input and Output). */-function schemaNames(provider: "fal" | "replicate", endpoint: string): { input: string; output: string } {- if (provider === "replicate") return { input: "Input", output: "Output" };- const d = doc(provider, endpoint);- const submit = d.paths?.[`/${endpoint}`]?.post;- const result = d.paths?.[`/${endpoint}/requests/{request_id}`]?.get;- const input = refName(submit?.requestBody?.content?.["application/json"]?.schema);- const output = refName(result?.responses?.["200"]?.content?.["application/json"]?.schema);- if (!input || !output) throw new Error(`${endpoint}: no input or output schema in its fixture`);- return { input, output };-}--// OpenAPI keywords ajv doesn't know (x-*, examples, nullable) are left to it as annotations; "uri" and other formats are-// not checked (a run's files are URLs the provider fetches).-const ajv = new Ajv({ strict: false, allErrors: true, validateFormats: false, validateSchema: false });-const validators = new Map<string, ValidateFunction>();-function validator(provider: "fal" | "replicate", endpoint: string, name: string): ValidateFunction {- const id = `${provider}:${endpoint}`;- const key = `${id}#${name}`;- if (!validators.has(key)) {- if (!ajv.getSchema(id)) ajv.addSchema({ $id: id, components: doc(provider, endpoint).components }, id);- validators.set(key, ajv.compile({ $ref: `${id}#/components/schemas/${name}` }));- }- return validators.get(key)!;-}+import { operationOutput, type GenerationRequest, type GenParams, type ModelDef, type ModelRoute, type Operation } from "@/lib/catalog/types";+import {+ bodyProblems,+ CLIP,+ documentedAnswer,+ END,+ GLB,+ handOverInput,+ IMG,+ PROMPT,+ routeRequest,+ SCHEMA_INDEX as INDEX,+ schemaFile as fileFor,+ SONG,+ VOICE,+ type Variant,+} from "./helpers/provider-schemas";// ---------------------------------------------------------------------------// The runs the studio can send each route.-const IMG = "https://v3b.fal.media/files/in/start.png";-const END = "https://v3b.fal.media/files/in/end.png";-const CLIP = "https://v3b.fal.media/files/in/clip.mp4";-const VOICE = "https://v3b.fal.media/files/in/voice.mp3";-const SONG = "https://v3b.fal.media/files/in/song.mp3";-const GLB = "https://v3b.fal.media/files/in/model.glb";-const PROMPT = "A dancer in a silver coat turns slowly under warm stage light, the camera drifting closer";--type Inputs = NonNullable<GenerationRequest["inputs"]>;-interface Variant {- label: string;- inputs: Inputs;- params: GenParams;- prompt?: string;- negativePrompt?: string;-}-/** What each operation's run carries (a clip's length, a song's), as the studio sends it. */function baseRun(model: ModelDef, op: Operation): Omit<Variant, "label"> {const o = model.options;@@ -182,9 +118,10 @@ function variants(model: ModelDef, op: Operation): Variant[] {if (o.negativePrompt) add("negative words", { negativePrompt: "blur, flicker" });for (const s of o.sliders ?? []) for (const v of [s.min, s.max]) add(`${s.param} ${v}`, { params: { extra: { [s.param]: v } } });if (op === "ref2v") {- const imgs = Math.min(o.maxImages ?? 1, 3);- const vids = Math.min(o.maxVideos ?? 0, 3);- const auds = Math.min(o.maxAudios ?? 0, 3);+ // Each list at the catalog's own maximum (tests/provider-conformance-paths.test.ts also sends them together).+ const imgs = o.maxImages ?? 1;+ const vids = o.maxVideos ?? 0;+ const auds = o.maxAudios ?? 0;if (imgs > 1) add(`${imgs} pictures`, { inputs: { images: Array.from({ length: imgs }, (_, i) => `https://v3b.fal.media/files/in/ref${i}.png`) } });if (vids) add(`${vids} clips`, { inputs: { videos: Array.from({ length: vids }, (_, i) => `https://v3b.fal.media/files/in/ref${i}.mp4`) } });if (auds) add(`${auds} voices`, { inputs: { audios: Array.from({ length: auds }, (_, i) => `https://v3b.fal.media/files/in/voice${i}.mp3`) } });@@ -195,37 +132,6 @@ function variants(model: ModelDef, op: Operation): Variant[] {return out;}-/** The body fal.ts or replicate.ts would send for this route (their submit: LoRA field, LoRA endpoint, a song uploaded first). */-function request(route: ModelRoute, input: GenInput): { endpoint: string; body: Record<string, unknown> } {- const map = { ...route.map, loras: routeLoraField(route) };- const body = buildPayload(map, input);- const song = map.songSource;- if (song && body[song.songId] === undefined) body[song.uploadId] = "mureka-upload-id";- return { endpoint: loraEndpointFor({ ...route, map }, input.loras).split(":")[0], body };-}--/** The input the server hands the adapter (generations.ts handOver), files already uploaded. */-function genInput(plan: ReturnType<typeof planGeneration>, v: Variant): GenInput {- // A song extended at its end (or, before its start, at 0) unless the run says where, as handOver sets it.- const extendAt = plan.op === "song-extend" && plan.params.startTime === undefined ? (plan.params.extra?.extend_type === "head" ? 0 : plan.params.sourceDuration) : undefined;- return {- ...plan.params,- ...(extendAt !== undefined && { startTime: extendAt }),- prompt: plan.prompt || undefined,- negativePrompt: v.negativePrompt,- images: v.inputs.images ?? [],- endImage: v.inputs.endImage,- video: v.inputs.video,- audio: v.inputs.audio,- videos: v.inputs.videos ?? [],- audios: v.inputs.audios ?? [],- model3d: v.inputs.model3d,- loras: plan.loras,- };-}--const errorsOf = (fn: ValidateFunction) => (fn.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}${e.params && "allowedValues" in e.params ? ` ${JSON.stringify(e.params.allowedValues)}` : ""}`);-// ---------------------------------------------------------------------------// The routes.@@ -268,19 +174,21 @@ describe("provider conformance: the untested hosted routes", () => {}// The variant's route (a quality control picks Kandinsky's Pro or Lite endpoint): only this one is checked here.if (!routesFor(model, plan.op, plan.params).includes(route)) continue;- const { endpoint, body } = request(route, genInput(plan, v));- const fn = validator(provider, endpoint, schemaNames(provider, endpoint).input);+ const { endpoint, body, upload } = routeRequest(route, handOverInput(plan, v));checked++;- if (!fn(body)) problems.push(`${v.label} → ${endpoint} ${JSON.stringify(body)}: ${errorsOf(fn).join("; ")}`);+ // The schema, and no field it doesn't name (fal ignores those without a word).+ const wrong = bodyProblems(provider, endpoint, body);+ if (wrong.length) problems.push(`${v.label} → ${endpoint} ${JSON.stringify(body)}: ${wrong.join("; ")}`);+ // A song Mureka didn't make goes through its files/upload first: that body too.+ const upWrong = upload ? bodyProblems("fal", upload.endpoint, upload.body) : [];+ if (upWrong.length) problems.push(`${v.label} → ${upload!.endpoint} ${JSON.stringify(upload!.body)}: ${upWrong.join("; ")}`);}expect(problems, problems.join("\n")).toEqual([]);expect(checked).toBeGreaterThan(0);});it(`${name}: its documented answer reads as the run's result`, () => {- const names = schemaNames(provider, route.endpoint.split(":")[0]);- const d = doc(provider, route.endpoint.split(":")[0]);- const answer = provider === "replicate" ? replicateAnswer(route.endpoint.split(":")[0], d) : exampleOf(d.components?.schemas?.[names.output], d);+ const answer = documentedAnswer(provider, route.endpoint.split(":")[0]);// Stems come back as one zip (Mureka's zip_url), which fal.ts unpacks into one result per stem.if (op === "song-stems") return expect(typeof (answer as { zip_url?: unknown })?.zip_url).toBe("string");const outs = extractOutputs(answer, op);@@ -290,56 +198,3 @@ describe("provider conformance: the untested hosted routes", () => {});}});--// ----------------------------------------------------------------------------// Answers made from the output schemas.--/** Replicate's example prediction's output (the model page's own), else one made from the Output schema. */-function replicateAnswer(model: string, d: Doc): unknown {- const raw = JSON.parse(fs.readFileSync(fileFor("replicate", model), "utf8"));- return raw.example_prediction?.output ?? exampleOf(d.components?.schemas?.Output, d);-}--const EXT: Record<string, string> = { image: "png", video: "mp4", audio: "mp3", model3d: "glb" };-const MIME: Record<string, string> = { image: "image/png", video: "video/mp4", audio: "audio/mpeg", model3d: "model/gltf-binary" };--/**- * A value for a schema: its own example where it has one, else one of its type. Every optional field is filled too (a- * still fal may send beside the video is part of the answer), flags are false, and a file with no example gets a URL with- * the extension its title or field name suggests.- */-function exampleOf(schema: Schema | undefined, d: Doc, key = "", depth = 0): unknown {- if (!schema || depth > 12) return undefined;- if (Array.isArray(schema.examples) && schema.examples.length) return schema.examples[0];- if (schema.example !== undefined) return schema.example;- const ref = refName(schema);- if (ref) return exampleOf(d.components?.schemas?.[ref], d, key, depth + 1);- const branch = schema.anyOf ?? schema.oneOf;- if (branch) return exampleOf(branch.find((b) => b.type !== "null") ?? branch[0], d, key, depth + 1);- if (schema.allOf) return Object.assign({}, ...schema.allOf.map((s) => exampleOf(s, d, key, depth + 1)));- if (schema.default !== undefined && schema.default !== null) return schema.default;- if (Array.isArray(schema.enum)) return schema.enum[0];- const type = Array.isArray(schema.type) ? schema.type.find((t) => t !== "null") : schema.type;- if (type === "object" || schema.properties) {- const props = Object.entries(schema.properties ?? {}).map(([k, s]) => [k, exampleOf(s, d, k, depth + 1)] as const);- const obj: Record<string, unknown> = Object.fromEntries(props.filter(([, v]) => v !== undefined));- // A file object with no example of its own (fal's shared File and Image schemas carry a PNG's name and type as their- // fields' examples): a file of the kind its field name or title says, with a URL, name and type to match.- if ("url" in (schema.properties ?? {})) {- const words = `${key} ${schema.title ?? ""}`;- const kind = /video/i.test(words) ? "video" : /audio|song|stem|vocal|track|voice/i.test(words) ? "audio" : /image|cover|thumb|picture/i.test(words) ? "image" : "model3d";- obj.url = `https://v3b.fal.media/files/out/${key || "file"}.${EXT[kind]}`;- if ("file_name" in obj) obj.file_name = `${key || "file"}.${EXT[kind]}`;- if ("content_type" in obj) obj.content_type = MIME[kind];- }- return obj;- }- if (type === "array") {- const item = exampleOf(schema.items, d, key, depth + 1);- return item === undefined ? [] : [item];- }- if (type === "boolean") return false;- if (type === "integer" || type === "number") return schema.minimum ?? 1;- if (type === "string") return /url|uri/i.test(key) || schema.format === "uri" ? `https://v3b.fal.media/files/out/${key}.bin` : "text";- return undefined;-}