import {z} from 'zod' export type GetApiTracksTrackUrnStreamsArgs = {track_urn: string, secret_token?: string | undefined}; export type GetApiTracksTrackUrnStreamsOptions = {baseUrl?: string | undefined, AuthHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const streams = z.object({hls_aac_160_url: z.string().optional(), hls_mp3_128_url: z.string().optional(), preview_mp3_128_url: z.string().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 }; /** * Returns a track's streamable URLs (needs to keep using authentication) * * GET /tracks/{track_urn}/streams * * Also accepts auth: oAuth2_1 */ export const getApiTracksTrackUrnStreams = async (args: GetApiTracksTrackUrnStreamsArgs, options?: GetApiTracksTrackUrnStreamsOptions) => { const {baseUrl = "https://api.soundcloud.com", fetch: fetchFn = fetch, AuthHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json; charset=utf-8") if (args.secret_token != null) query.append("secret_token", String(args.secret_token)) if (AuthHeader !== undefined) headers.set("Authorization", AuthHeader) const url = `${baseUrl.replace(/\/+$/, '')}/tracks/${encodeURIComponent(String(args.track_urn))}/streams${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(streams, await res.json()) };