import {z} from 'zod' export type GetApiV0TracksTrackIdDownloadArgs = {trackId: string, format?: 'mp3' | undefined, quality?: ('normal' | 'high') | undefined, expand?: 'stems' | undefined}; export type GetApiV0TracksTrackIdDownloadOptions = {baseUrl?: string | undefined, UserAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const stemDownloadResponse = z.object({type: z.enum(["drums", "bass", "melody", "instruments", "vocals", "clean_vocals"]), url: z.string()}); export const trackDownloadResponse = z.object({url: z.string(), expires: z.string(), stems: z.array(stemDownloadResponse).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Download track * * GET /v0/tracks/{trackId}/download * * Also accepts auth: EpidemicSoundConnectAuth, ApiKeyAuth */ export const getApiV0TracksTrackIdDownload = async (args: GetApiV0TracksTrackIdDownloadArgs, options?: GetApiV0TracksTrackIdDownloadOptions) => { const {baseUrl = "https://partner-content-api.epidemicsound.com", fetch: fetchFn = fetch, UserAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.format != null) query.append("format", String(args.format)) if (args.quality != null) query.append("quality", String(args.quality)) if (args.expand != null) query.append("expand", String(args.expand)) if (UserAuth !== undefined) headers.set('authorization', `Bearer ${UserAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v0/tracks/${encodeURIComponent(String(args.trackId))}/download${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(trackDownloadResponse, await res.json()) };