import {z} from 'zod' export type GetApiV1ProfilesMeOptions = {baseUrl?: string | undefined, APIKey?: string | undefined, fetch?: typeof fetch | undefined}; export const userProfileSubscription = z.object({status: z.string(), plan: z.string(), period_start: z.string().nullable().optional(), period_end: z.string().nullable().optional()}); export const userProfileOrganization = z.object({id: z.string(), role: z.string()}); export const userProfile = z.object({identity_type: z.literal("user").optional(), id: z.string(), subscription: userProfileSubscription, organization: userProfileOrganization.nullable().optional(), suspended: z.boolean().optional()}); export const organizationProfileSubscription = z.object({status: z.string(), plan: z.string(), period_start: z.string().nullable().optional(), period_end: z.string().nullable().optional()}); export const organizationProfile = z.object({identity_type: z.literal("organization").optional(), id: z.string(), subscription: organizationProfileSubscription}); export const profileResponse = z.object({profile: z.discriminatedUnion("identity_type", [userProfile, organizationProfile])}); 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 the current user's profile * * GET /v1/profiles/me */ export const getApiV1ProfilesMe = async (options?: GetApiV1ProfilesMeOptions) => { const {baseUrl = "https://api.asknews.app", fetch: fetchFn = fetch, APIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (APIKey !== undefined) headers.set("Authorization", APIKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/profiles/me${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(profileResponse, await res.json()) };