import {z} from 'zod' export type ResourceReference = {href: string}; export type TaskEnterMaintenance = {type: 'enter_maintenance', target: ResourceReference | string, parameters?: ({maximum_duration?: number | undefined}) | undefined}; export type TaskExitMaintenance = {type: 'exit_maintenance', target: ResourceReference | string, parameters?: Record | undefined}; export type ApplicationHref = string; export type Timestamp = string; export type TaskGenerateOriginCertificate = {type: 'generate-origin-certificate', target: ApplicationHref, parameters: {key: string, hostnames?: Array | undefined, expiry?: Timestamp | undefined}}; export type InvalidateCacheUrl = string; export type TagName = string; export type TaskInvalidateCache = {type: 'invalidate-cache', target: ResourceReference | string, parameters: {urls: Array, tags?: Array | undefined}}; export type TaskOauth2Authorize = {type: 'oauth2-authorize', parameters: {code?: string | undefined, realm_id?: string | undefined}}; export type TaskRunAction = {type: 'run-action', target: ResourceReference | string, parameters: {id?: string | undefined}}; export type TaskStart = {type: 'start', target: ResourceReference | string}; export type TaskStop = {type: 'stop', target: ResourceReference | string}; export type TaskValidateTLS = {type: 'validate_tls', parameters: {tls_configuration?: Record | undefined}}; export type SearchParameters = {type?: 'search' | undefined, parameters?: ({pattern: string, limit?: number | undefined}) | undefined}; export type PrepareForDownload = {type?: 'prepare-for-download' | undefined, parameters?: ({reference: string, from: Timestamp, to: Timestamp, retention?: number | undefined, restore_type?: ('bulk' | 'standard' | 'expedited') | undefined}) | undefined}; export type TaskPost = TaskEnterMaintenance | TaskExitMaintenance | TaskGenerateOriginCertificate | TaskInvalidateCache | TaskOauth2Authorize | TaskRunAction | TaskStart | TaskStop | TaskValidateTLS | SearchParameters | PrepareForDownload; export type CreateApiTasksArgs = {body: TaskPost}; export type CreateApiTasksOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const billingService = z.union([z.unknown(), z.object({type: z.literal("quickbooks"), quickbooks_id: z.number().int()})]); export const accountLogRetention = z.object({type: z.literal("events"), online_days: z.number().int().gte(1).optional(), archive_days: z.number().int().gte(1).optional(), online_space_allowance: z.number().int().gte(1).optional(), archive_space_allowance: z.number().int().gte(1).optional()}); export const accountHref = z.string(); export const account = z.object({billing_service: billingService.optional(), stratus_id: z.string().nullable().optional(), name: z.string().optional(), log_retention: z.array(accountLogRetention).optional(), href: accountHref, id: z.string()}); export const searchResult = z.object({matches: z.array(z.object({account: account.optional(), subject: z.object({}).optional()})).optional()}); export const task = z.object({href: z.string().optional(), type: z.string().optional(), target: z.string().optional(), parameters: z.object({}).optional(), created: z.string().optional(), started: z.string().optional(), completed: z.string().optional(), updated: z.string().optional(), state: z.enum(["pending", "running", "success", "failed"]).optional(), description: z.string().optional(), message: z.string().optional(), result: z.union([z.object({}), searchResult]).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 }; /** * Execute a task against a resource * * POST /tasks */ export const createApiTasks = async (args: CreateApiTasksArgs, options?: CreateApiTasksOptions) => { const {baseUrl = "https://api.webscale.com/v2", 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(/\/+$/, '')}/tasks${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(task, await res.json()) };