Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/audio-binary-output.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"cf": patch
---

Prepare generated commands to preserve audio API responses

Recognize `audio/*` responses as binary data in the command generator and its
operation descriptors, including schemas without `format: binary`. Future commands
generated for audio endpoints will write the exact bytes to stdout so they can be
redirected to a file. No commands generated from the currently pinned OpenAPI
specification declare audio responses, so this change does not alter the behavior
of any currently shipped command.
5 changes: 4 additions & 1 deletion packages/cli/generator/plugin/emit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,10 @@ export function outputKind(op: OperationInfo): OutputKind {
);
}
if (
success.content.some((c) => BINARY.includes(c) || c.startsWith("image/"))
success.content.some(
(c) =>
BINARY.includes(c) || c.startsWith("image/") || c.startsWith("audio/")
Comment thread
petebacondarwin marked this conversation as resolved.
Resolved
)
) {
return "binary";
}
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/generator/plugin/operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,8 @@ function wire(method: Method, info: Omit<OperationInfo, "wire">): Wire {
ct === "application/octet-stream" ||
ct === "application/pdf" ||
ct === "application/zip" ||
ct.startsWith("image/");
ct.startsWith("image/") ||
ct.startsWith("audio/");
Comment thread
petebacondarwin marked this conversation as resolved.
Resolved
if (binary) {
noResponse = false;
responseType = "binary-response";
Expand Down
28 changes: 16 additions & 12 deletions packages/cli/src/__tests__/commands/ai-run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,12 @@ describe("cf ai run", () => {
});
}

function rawRunHandler(bytes: Uint8Array) {
function rawRunHandler(bytes: Uint8Array, contentType: string) {
return http.post(
/\/ai\/run$/,
() =>
new HttpResponse(bytes, {
headers: { "content-type": "audio/wav" },
headers: { "content-type": contentType },
})
);
}
Expand Down Expand Up @@ -168,18 +168,22 @@ describe("cf ai run", () => {
expect(stdout()).toContain("hi");
});

it("writes non-JSON model output as exact bytes", async () => {
const bytes = Uint8Array.from([82, 73, 70, 70, 0, 255, 128]);
const write = vi
.spyOn(process.stdout, "write")
.mockImplementation(() => true);
server.use(schemaHandler(), rawRunHandler(bytes));
it.each(["audio/mpeg", "audio/wav", "image/png", "application/octet-stream"])(
"writes %s model output as exact bytes",
async (contentType) => {
const bytes = Uint8Array.from([82, 73, 70, 70, 0, 255, 128]);
const write = vi
.spyOn(process.stdout, "write")
.mockImplementation(() => true);
server.use(schemaHandler(), rawRunHandler(bytes, contentType));

const { exitCode } = await run(MODEL, "--prompt", "hello");
const { exitCode } = await run(MODEL, "--prompt", "hello");

expect(exitCode).toBe(0);
expect(write).toHaveBeenCalledWith(Buffer.from(bytes));
});
expect(exitCode).toBe(0);
expect(write).toHaveBeenCalledWith(Buffer.from(bytes));
expect(stdout()).toBe("");
}
);

it("parses array and object flags as JSON values", async () => {
server.use(
Expand Down
85 changes: 44 additions & 41 deletions packages/cli/src/__tests__/generator/plugin/emit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,47 +172,50 @@ describe("bodyless raw response emission", () => {
);
});

describe("protobuf response emission", () => {
it("writes profile bytes directly while sending the JSON request body", () => {
const op = operation(
"post",
"/accounts/{account_id}/workers/workers/{worker_id}/versions/{version_id}/profile",
{
pathParams: [
param("account_id"),
param("worker_id"),
param("version_id"),
],
bodyParams: [
bodyParam("duration_ms", "number", ["duration_ms"], {
required: true,
}),
],
hasRequestBody: true,
requestContentTypes: ["application/json"],
requestBodyRequired: ["duration_ms"],
responses: [["200", { content: ["application/vnd.google.protobuf"] }]],
}
);
const ctx = context(
method("profile", "workers.versions.profile"),
"workers",
op
);
expect(ctx.outputKind).toBe("binary");
const output = handler(ctx).join("\n");
expect(output).toContain("fetchRawBytes(");
expect(output).toContain("method: 'POST'");
expect(output).toContain("body: JSON.stringify(bodyData)");
expect(output).toContain(
"body: Object.keys(bodyData).length > 0 ? bodyData : undefined"
);
expect(output).toContain("contentType: 'application/json'");
expect(output).toContain(
"writeRawOutput(argv.text === true ? __cfRawBytes.toString('utf-8') : __cfRawBytes)"
);
expect(output).not.toContain("formatOutput(");
});
describe("binary response emission", () => {
it.each(["application/vnd.google.protobuf", "audio/mpeg", "audio/wav"])(
"writes %s bytes directly while sending the JSON request body",
(contentType) => {
const op = operation(
"post",
"/accounts/{account_id}/workers/workers/{worker_id}/versions/{version_id}/profile",
{
pathParams: [
param("account_id"),
param("worker_id"),
param("version_id"),
],
bodyParams: [
bodyParam("duration_ms", "number", ["duration_ms"], {
required: true,
}),
],
hasRequestBody: true,
requestContentTypes: ["application/json"],
requestBodyRequired: ["duration_ms"],
responses: [["200", { content: [contentType] }]],
}
);
const ctx = context(
method("profile", "workers.versions.profile"),
"workers",
op
);
expect(ctx.outputKind).toBe("binary");
const output = handler(ctx).join("\n");
expect(output).toContain("fetchRawBytes(");
expect(output).toContain("method: 'POST'");
expect(output).toContain("body: JSON.stringify(bodyData)");
expect(output).toContain(
"body: Object.keys(bodyData).length > 0 ? bodyData : undefined"
);
expect(output).toContain("contentType: 'application/json'");
expect(output).toContain(
"writeRawOutput(argv.text === true ? __cfRawBytes.toString('utf-8') : __cfRawBytes)"
);
expect(output).not.toContain("formatOutput(");
}
);
});

describe("variant prompts", () => {
Expand Down
41 changes: 41 additions & 0 deletions packages/cli/src/__tests__/generator/plugin/forge-model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,47 @@ describe("the forge model", () => {
expect(code).toContain(".conflicts('id', ['name'])");
});

it.each(["audio/mpeg", "audio/wav"])(
"preserves %s responses without a binary schema format",
(contentType) => {
const files = generateFiles(
doc({
"/speech": {
post: {
"x-fern-sdk-group-name": "speech",
"x-fern-sdk-method-name": "create",
summary: "Generate speech",
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: { prompt: { type: "string" } },
},
},
},
},
responses: {
"200": {
description: "Audio bytes",
content: { [contentType]: { schema: { type: "string" } } },
},
},
},
},
})
);
const command = files.get("speech/create.ts") ?? "";
expect(command).toContain("fetchRawBytes(");
expect(command).toContain("method: 'POST'");
expect(command).toContain("writeRawOutput(");
expect(command).not.toContain("formatOutput(");
expect(operation(files, "speech/create")).toContain(
'response: "binary-response"'
);
}
);

it("describes the operation a typed call sends", () => {
const textGet = doc({
"/accounts/{account_id}/things/{thing_id}": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ describe("outputKind", () => {
["application/octet-stream", "binary"],
["application/zip", "binary"],
["image/png", "binary"],
["audio/mpeg", "binary"],
["audio/wav", "binary"],
["audio/ogg", "binary"],
["text/plain", "text"],
["text/csv", "text"],
["application/json", "json"],
Expand Down
Loading