import {z} from 'zod' export type BodyAuthLogin = {grant_type?: (string | null) | undefined, username: string, password: string, scope?: string | undefined, client_id?: (string | null) | undefined, client_secret?: (string | null) | undefined}; export type CreateApiAuthTokenArgs = {'user-agent'?: (string | null) | undefined, 'x-real-ip'?: (string | null) | undefined, 'x-forwarded-for'?: (string | null) | undefined, 'x-client-ip'?: (string | null) | undefined, session_id?: (number | null) | undefined, body: BodyAuthLogin}; export type CreateApiAuthTokenOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const tokenOut = z.object({access_token: z.string(), token_type: 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 }; /** * Log in * * POST /auth/token */ export const createApiAuthToken = async (args: CreateApiAuthTokenArgs, options?: CreateApiAuthTokenOptions) => { const {baseUrl = "https://api.your-domain.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() const cookies: string[] = [] headers.set('content-type', "application/x-www-form-urlencoded") headers.set('accept', "application/json") if (args['user-agent'] != null) headers.set("user-agent", String(args['user-agent'])) if (args['x-real-ip'] != null) headers.set("x-real-ip", String(args['x-real-ip'])) if (args['x-forwarded-for'] != null) headers.set("x-forwarded-for", String(args['x-forwarded-for'])) if (args['x-client-ip'] != null) headers.set("x-client-ip", String(args['x-client-ip'])) if (args.session_id != null) cookies.push("session_id=" + encodeURIComponent(String(args.session_id))) if (cookies.length > 0) headers.set('cookie', cookies.join('; ')) const url = `${baseUrl.replace(/\/+$/, '')}/auth/token${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: new URLSearchParams(Object.entries(args.body).flatMap(([key, value]) => (value == null ? [] : [[key, String(value)]])))}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(tokenOut, await res.json()) };