import {z} from 'zod' export type ApiKeyScopeRole = 'discoverer' | 'viewer' | 'editor' | 'admin' | 'owner' | 'member' | 'executor'; export type ApiKeyScope = {resource_id: string, resource_type: string, role: ApiKeyScopeRole}; export type ApiKeyScopesUpdateRequest = {scopes: Array}; export type PatchApiApiKeysApiKeyIdArgs = {api_key_id: string, body: ApiKeyScopesUpdateRequest}; export type PatchApiApiKeysApiKeyIdOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const apiKeyScopeRole = z.enum(["discoverer", "viewer", "editor", "admin", "owner", "member", "executor"]); export const apiKeyScope = z.object({resource_id: z.string(), resource_type: z.string(), role: apiKeyScopeRole}); export const apiKeyResponse = z.object({created_at: z.string().nullable().optional(), created_by: z.string(), description: z.string().nullable().optional(), id: z.string(), key_prefix: z.string(), last_used_at: z.string().nullable().optional(), name: z.string(), org_id: z.string(), revoked_at: z.string().nullable().optional(), scopes: z.array(apiKeyScope).optional(), sharing_group_ids: z.array(z.string()).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 }; /** * Update API Key Scopes * * PATCH /api_keys/{api_key_id} */ export const patchApiApiKeysApiKeyId = async (args: PatchApiApiKeysApiKeyIdArgs, options: PatchApiApiKeysApiKeyIdOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api_keys/${encodeURIComponent(String(args.api_key_id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PATCH", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(apiKeyResponse, await res.json()) };