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
2,537 changes: 2,303 additions & 234 deletions contract/beatapi.openapi.yaml

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions contract/contract.lock.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"source": "https://github.com/BeatAPI/beatapi-examples",
"ref": "8f7d3cff33445ded4d3c94f0fb8ac5060d790148",
"ref": "83a139a123a3139cf53a362132b7b1d8a0066e1f",
"openapiVersion": "1.0.0-launch",
"sha256": "290100dba10bb14b040f5a826657ad7d4a01f179fc28ef69ea0bdcaa66f7dad3"
"sha256": "bcd8dfb2124e7815ea52e513c99a2522e749316fc41f02a6f70957d3e3ebe293"
}
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ function defaultCreateClient(
return new BeatAPIClient({
apiKey,
baseUrl: env.BEATAPI_BASE_URL,
allowInsecureLocalhost: env.BEATAPI_ALLOW_INSECURE_LOCALHOST === "1",
trustCustomBaseUrl: env.BEATAPI_TRUST_CUSTOM_BASE_URL === "1",
});
}

Expand Down
148 changes: 144 additions & 4 deletions packages/client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import { BeatAPIError } from "./errors.js";
import type { components, operations } from "./types.generated.js";

export type BeatAPIWorkflow = components["schemas"]["Workflow"];
export type BeatAPITextModel = components["schemas"]["TextModel"];
export type BeatAPITaskStatus = components["schemas"]["TaskStatus"];
export type BeatAPITask = components["schemas"]["Task"];
export type BeatAPIUsage = components["schemas"]["Usage"];
export type BeatAPIFile = components["schemas"]["File"];
export type BeatAPIShotMedia = components["schemas"]["ShotMedia"];
export type BeatAPIWebhook = components["schemas"]["WebhookEndpoint"];
export type BeatAPIRealtimeSession = components["schemas"]["RealtimeSession"];
export type BeatAPIGenerationModel = components["schemas"]["GenerationModel"];
export type BeatAPIEffect = components["schemas"]["Effect"];
export type BeatAPIDeleteResult = components["schemas"]["DeleteResponse"]["data"];

export type MusicVideoTaskInput =
Expand All @@ -25,6 +28,17 @@ export type UpdateWebhookInput =
operations["updateWebhookEndpoint"]["requestBody"]["content"]["application/json"];
export type CreateRealtimeSessionInput =
operations["createRealtimeSession"]["requestBody"]["content"]["application/json"];
export type TextResponseInput =
operations["createTextResponse"]["requestBody"]["content"]["application/json"];
export type TextResponseOutput = components["schemas"]["TextPassthroughResponse"];
export type VideoAnalysisTaskInput =
operations["createVideoAnalysisTask"]["requestBody"]["content"]["application/json"];
export type ImageGenerationTaskInput =
operations["createImageGenerationTask"]["requestBody"]["content"]["application/json"];
export type VideoGenerationTaskInput =
operations["createVideoGenerationTask"]["requestBody"]["content"]["application/json"];
export type CreateEffectTaskInput =
operations["createEffectTask"]["requestBody"]["content"]["application/json"];

type FetchLike = (
input: string | URL | Request,
Expand All @@ -40,6 +54,8 @@ export interface RetryOptions {
export interface BeatAPIClientOptions {
apiKey?: string | undefined;
baseUrl?: string | undefined;
allowInsecureLocalhost?: boolean | undefined;
trustCustomBaseUrl?: boolean | undefined;
fetch?: FetchLike | undefined;
sleep?: ((milliseconds: number) => Promise<void>) | undefined;
random?: (() => number) | undefined;
Expand All @@ -50,6 +66,7 @@ interface RequestOptions {
body?: unknown | undefined;
headers?: HeadersInit | undefined;
authenticated?: boolean | undefined;
responseShape?: "beatapi" | "raw" | undefined;
retry?: RetryOptions | undefined;
}

Expand Down Expand Up @@ -84,6 +101,47 @@ const ACTIONABLE_OR_TERMINAL_STATUSES = new Set<BeatAPITaskStatus>([

const RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);

function validatedBaseUrl(
value: string,
options: Pick<
BeatAPIClientOptions,
"allowInsecureLocalhost" | "trustCustomBaseUrl"
>,
): string {
let parsed: URL;
try {
parsed = new URL(value);
} catch {
throw new TypeError("BeatAPI base URL must be an exact HTTPS origin.");
}
const isLoopback = ["localhost", "127.0.0.1", "[::1]"].includes(
parsed.hostname,
);
const insecureTestOrigin = options.allowInsecureLocalhost === true && isLoopback;
if (
(parsed.protocol !== "https:" && !insecureTestOrigin) ||
parsed.username ||
parsed.password ||
parsed.pathname !== "/" ||
parsed.search ||
parsed.hash
) {
throw new TypeError(
"BeatAPI base URL must be an exact HTTPS origin without credentials, path, query, or fragment.",
);
}
if (
parsed.origin !== "https://api.beatapi.io" &&
!insecureTestOrigin &&
options.trustCustomBaseUrl !== true
) {
throw new TypeError(
"A custom BeatAPI HTTPS origin requires an explicit trusted operator setting.",
);
}
return parsed.origin;
}

function assertPositiveInteger(value: number, label: string): void {
if (!Number.isInteger(value) || value <= 0) {
throw new TypeError(`${label} must be a positive integer.`);
Expand Down Expand Up @@ -164,9 +222,9 @@ export class BeatAPIClient {

constructor(options: BeatAPIClientOptions = {}) {
this.apiKey = options.apiKey;
this.baseUrl = (options.baseUrl || "https://api.beatapi.io").replace(
/\/+$/,
"",
this.baseUrl = validatedBaseUrl(
options.baseUrl || "https://api.beatapi.io",
options,
);
const fetchImpl = options.fetch ?? globalThis.fetch;
if (typeof fetchImpl !== "function") {
Expand Down Expand Up @@ -223,7 +281,11 @@ export class BeatAPIClient {
});
const payload = await readPayload(response);

if (response.ok) return unwrapData<T>(payload);
if (response.ok) {
return options.responseShape === "raw"
? (payload as T)
: unwrapData<T>(payload);
}

const error = errorFromResponse(response, payload);
if (
Expand Down Expand Up @@ -276,6 +338,84 @@ export class BeatAPIClient {
).then((result) => result.data);
}

listTextModels(): Promise<BeatAPITextModel[]> {
return this.request<{ object: "list"; data: BeatAPITextModel[] }>(
"/v1/models",
{ responseShape: "raw" },
).then((result) => result.data);
}

listGenerationModels(): Promise<BeatAPIGenerationModel[]> {
return this.request<{ object: "list"; data: BeatAPIGenerationModel[] }>(
"/v1/media/models",
{ authenticated: false },
).then((result) => result.data);
}

createImageTask(input: ImageGenerationTaskInput): Promise<BeatAPITask> {
return this.request("/v1/images/tasks", { method: "POST", body: input });
}

createVideoTask(input: VideoGenerationTaskInput): Promise<BeatAPITask> {
return this.request("/v1/videos/tasks", { method: "POST", body: input });
}

listEffects(
filters: { outputType?: "image" | "video"; category?: string } = {},
): Promise<BeatAPIEffect[]> {
const query = new URLSearchParams();
if (filters.outputType) query.set("output_type", filters.outputType);
if (filters.category) query.set("category", filters.category);
const suffix = query.size > 0 ? `?${query.toString()}` : "";
return this.request<{ object: "list"; data: BeatAPIEffect[] }>(
`/v1/effects${suffix}`,
{ authenticated: false },
).then((result) => result.data);
}

getEffect(effectId: string): Promise<BeatAPIEffect> {
return this.request(`/v1/effects/${encodePathSegment(effectId)}`, {
authenticated: false,
});
}

createEffectTask(
input: CreateEffectTaskInput,
options: { idempotencyKey: string },
): Promise<BeatAPITask> {
const idempotencyKey = options.idempotencyKey.trim();
if (!idempotencyKey) {
throw new TypeError("idempotencyKey must not be empty.");
}
return this.request("/v1/effects/tasks", {
method: "POST",
body: input,
headers: { "idempotency-key": idempotencyKey },
});
}

createTextResponse(input: TextResponseInput): Promise<TextResponseOutput> {
return this.request("/v1/responses", {
method: "POST",
body: input,
responseShape: "raw",
});
}

createVideoAnalysisTask(
input: VideoAnalysisTaskInput,
options: { idempotencyKey?: string } = {},
): Promise<BeatAPITask> {
const idempotencyKey = options.idempotencyKey?.trim();
return this.request("/v1/video-analysis/tasks", {
method: "POST",
body: input,
...(idempotencyKey
? { headers: { "idempotency-key": idempotencyKey } }
: {}),
});
}

getUsage(): Promise<BeatAPIUsage> {
return this.request("/v1/usage");
}
Expand Down
9 changes: 9 additions & 0 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,32 @@ export {
BeatAPIClient,
type BeatAPIClientOptions,
type BeatAPIDeleteResult,
type BeatAPIEffect,
type BeatAPIFile,
type BeatAPIGenerationModel,
type BeatAPIRealtimeSession,
type BeatAPIShotMedia,
type BeatAPITextModel,
type BeatAPITask,
type BeatAPITaskStatus,
type BeatAPIUsage,
type BeatAPIWebhook,
type BeatAPIWorkflow,
type CreateWebhookInput,
type CreateRealtimeSessionInput,
type CreateEffectTaskInput,
type EcommerceVideoTaskInput,
type ImageGenerationTaskInput,
type MusicVideoComposeInput,
type MusicVideoShotEditInput,
type MusicVideoTaskInput,
type RetryOptions,
type TextResponseInput,
type TextResponseOutput,
type UpdateWebhookInput,
type UploadFileOptions,
type VideoAnalysisTaskInput,
type VideoGenerationTaskInput,
type WaitForTaskOptions,
} from "./client.js";
export { BeatAPIError, type BeatAPIErrorOptions } from "./errors.js";
Expand Down
Loading
Loading