import {z} from 'zod' export type GetApiWordsArgs = {surah_number: number, include_arabic_text?: boolean | undefined, language?: string | undefined, start_ayah_number?: number | undefined, end_ayah_number?: number | undefined}; export type GetApiWordsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const word = z.object({position: z.number().int().optional(), arabic_text: z.string().optional(), translation: z.string().optional()}); export const words = z.object({surah_number: z.number().int().optional(), number: z.number().int().optional(), words: z.array(word).optional()}); export const wordsResponse = z.array(words); 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 }; /** * List words of a specific surah * * GET /words */ export const getApiWords = async (args: GetApiWordsArgs, options?: GetApiWordsOptions) => { const {baseUrl = "https://digital-quran.quranacademy.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.surah_number != null) query.append("surah_number", String(args.surah_number)) if (args.include_arabic_text != null) query.append("include_arabic_text", String(args.include_arabic_text)) if (args.language != null) query.append("language", String(args.language)) if (args.start_ayah_number != null) query.append("start_ayah_number", String(args.start_ayah_number)) if (args.end_ayah_number != null) query.append("end_ayah_number", String(args.end_ayah_number)) const url = `${baseUrl.replace(/\/+$/, '')}/words${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(wordsResponse, await res.json()) };