import {z} from 'zod' export type GetApiV1TiktokVideosVideoIdTranscriptArgs = {video_id: string, region?: string | undefined}; export type GetApiV1TiktokVideosVideoIdTranscriptOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const tikTokSubtitle = z.object({language: z.string().optional(), language_code: z.string().optional(), url: z.string().optional(), source: z.string().optional(), version: z.string().optional(), format: z.string().optional()}); export const transcriptResponse = z.object({video_id: z.string(), subtitles: z.array(tikTokSubtitle).optional(), voice_to_text: z.string().optional(), region: z.string()}); 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 }; /** * Get Transcript * * GET /v1/tiktok/videos/{video_id}/transcript */ export const getApiV1TiktokVideosVideoIdTranscript = async (args: GetApiV1TiktokVideosVideoIdTranscriptArgs, options?: GetApiV1TiktokVideosVideoIdTranscriptOptions) => { const {baseUrl = "https://scrapebadger.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.region != null) query.append("region", String(args.region)) if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/tiktok/videos/${encodeURIComponent(String(args.video_id))}/transcript${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(transcriptResponse, await res.json()) };