import {z} from 'zod' export type GetApiAyahsArgs = {surah_number: number, include_arabic_text?: boolean | undefined, translations?: Array | undefined, start_ayah_number?: number | undefined, end_ayah_number?: number | undefined}; export type GetApiAyahsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const ayah = z.object({surah_number: z.number().int().optional(), number: z.number().int().optional(), juz_number: z.number().int().optional(), hizb_number: z.number().int().optional(), rub_number: z.number().int().optional(), sajdah: z.boolean().optional(), word_count: z.number().int().optional(), arabic_text: z.string().optional(), translations: z.object({"en-saheeh-international": z.string().optional(), "ru-abu-adel": z.string().optional()}).optional()}); export const ayahs = z.array(ayah); 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 ayahs of a specific surah * * GET /ayahs */ export const getApiAyahs = async (args: GetApiAyahsArgs, options?: GetApiAyahsOptions) => { 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)) for (const item of args.translations ?? []) query.append("translations", String(item)) 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(/\/+$/, '')}/ayahs${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(ayahs, await res.json()) };