import {z} from 'zod' export type NameString = string; export type GetApiSourcesArgs = {name?: string | undefined, size?: number | undefined, country?: NameString | undefined, region?: NameString | undefined, subregion?: NameString | undefined}; export type GetApiSourcesOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const resourceId = z.string(); export const source = z.object({id: resourceId, name: z.string(), country: z.string().optional(), subregion: z.string().optional(), region: z.string().optional()}); export const sourcesResponse = z.object({sources: z.array(source)}); 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 }; /** * Search publication sources * * GET /sources */ export const getApiSources = async (args: GetApiSourcesArgs, options?: GetApiSourcesOptions) => { const {baseUrl = "https://api.signal-ai.com", fetch: fetchFn = fetch, OAuth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.name != null) query.append("name", String(args.name)) if (args.size != null) query.append("size", String(args.size)) if (args.country != null) query.append("country", String(args.country)) if (args.region != null) query.append("region", String(args.region)) if (args.subregion != null) query.append("subregion", String(args.subregion)) if (OAuth2 !== undefined) headers.set('authorization', `Bearer ${OAuth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/sources${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(sourcesResponse, await res.json()) };