import {z} from 'zod' export type TenantId = string; export type TagId = number; export type CreateApi2TenantsArgs = {'icl-requestor-id': string, body: {id: TenantId, name: string, tenantAdminEmail?: string | undefined, tags?: Array | undefined}}; export type CreateApi2TenantsOptions = {baseUrl?: string | undefined, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const tenantId = z.string(); export const tagId = z.number().int().gte(1); export const timestamp = z.string(); export const tag = z.object({id: tagId, tagText: z.string(), default: z.boolean(), created: timestamp}); export const createdByType = z.enum(["Tsp", "Admin", "Va"]); export const createdBy = z.object({id: z.string(), name: z.string(), type: createdByType}); export const createApi2TenantsResponse = z.object({id: tenantId, name: z.string(), tenantCreatedConfigs: z.boolean(), emailSent: z.boolean(), keyLeasingRequired: z.boolean(), archived: z.boolean(), tags: z.array(tag), createdBy: createdBy, created: timestamp, updated: timestamp}); 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 }; /** * Tenant Create V2 * * POST /2/tenants */ export const createApi2Tenants = async (args: CreateApi2TenantsArgs, options?: CreateApi2TenantsOptions) => { const {baseUrl = "http://localhost:3000/api", fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['icl-requestor-id'] != null) headers.set("icl-requestor-id", String(args['icl-requestor-id'])) if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/2/tenants${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", 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(createApi2TenantsResponse, await res.json()) };