import {z} from 'zod' export type CreateApiAuthTokenArgs = {body: {grant_type: 'client_credentials', client_id: string, client_secret: string}}; export type CreateApiAuthTokenOptions = {baseUrl?: string | undefined, ServiceKeyHeader?: string | undefined, ServiceSecretHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const tokensDto = z.object({access_token: z.string(), refresh_token: z.string(), token_type: z.string().optional(), expires_in: z.number().int().nullable().optional()}); 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 }; /** * Authenticate * * POST /auth/token * * Also accepts auth: UserKeyHeader, OAuth2ClientCredentials */ export const createApiAuthToken = async (args: CreateApiAuthTokenArgs, options?: CreateApiAuthTokenOptions) => { const {baseUrl = "https://am1.portal.api.nasuni.com", fetch: fetchFn = fetch, ServiceKeyHeader, ServiceSecretHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/x-www-form-urlencoded") headers.set('accept', "application/json") if (ServiceKeyHeader !== undefined) headers.set("x-service-key", ServiceKeyHeader) if (ServiceSecretHeader !== undefined) headers.set("x-service-secret", ServiceSecretHeader) 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(tokensDto, await res.json()) };