import {z} from 'zod' export type AttributeProperties = {value: {type?: string | undefined, enum?: Array | undefined} | {[key: string]: Record}, unit?: ({type?: 'string' | undefined, enum?: Array | undefined, default?: string | undefined}) | undefined, data?: ({type: 'object', additionalProperties?: boolean | undefined, required?: Array | undefined, properties?: Record | undefined}) | undefined}; export type AttributeSchema = {title?: string | undefined, type?: 'object' | undefined, properties: AttributeProperties, sensitive?: boolean | undefined, additionalProperties?: false | undefined, required?: (Array<'value' | 'unit' | 'data'>) | undefined}; export type CapabilityAttribute = {schema?: AttributeSchema | undefined, setter?: string | undefined, enumCommands?: Array<{command: string, value: string}> | undefined}; export type Argument = {name: string, optional?: boolean | undefined, schema: Record}; export type CapabilityCommand = {name: string, arguments?: Array | undefined, sensitive?: boolean | undefined}; export type CreateCapabilityRequest = {name: string, ephemeral?: boolean | undefined, attributes?: {[key: string]: CapabilityAttribute} | undefined, commands?: {[key: string]: CapabilityCommand} | undefined}; export type CreateApiCapabilitiesArgs = {'X-ST-Organization'?: unknown | undefined, namespace?: string | undefined, body: CreateCapabilityRequest}; export type CreateApiCapabilitiesOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const attributeProperties = z.object({value: z.object({type: z.string().optional(), enum: z.array(z.string()).optional()}).and(z.record(z.string(), z.object({}))), unit: z.object({type: z.literal("string").optional(), enum: z.array(z.string()).optional(), default: z.string().optional()}).optional(), data: z.object({type: z.literal("object"), additionalProperties: z.boolean().optional(), required: z.array(z.string()).optional(), properties: z.object({}).optional()}).optional()}); export const attributeSchema = z.object({title: z.string().optional(), type: z.literal("object").optional(), properties: attributeProperties, sensitive: z.boolean().optional(), additionalProperties: z.literal(false).optional(), required: z.array(z.enum(["value", "unit", "data"])).optional()}); export const capabilityAttribute = z.object({schema: attributeSchema.optional(), setter: z.string().optional(), enumCommands: z.array(z.object({command: z.string(), value: z.string()})).optional()}); export const argument = z.object({name: z.string(), optional: z.boolean().optional(), schema: z.object({})}); export const capabilityCommand = z.object({name: z.string(), arguments: z.array(argument).optional(), sensitive: z.boolean().optional()}); export const capability = z.object({id: z.string(), version: z.number().int(), status: z.enum(["proposed", "live", "deprecated", "dead"]), name: z.string(), ephemeral: z.boolean().optional(), attributes: z.record(z.string(), capabilityAttribute).optional(), commands: z.record(z.string(), capabilityCommand).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 }; /** * Create a Capability * * POST /capabilities */ export const createApiCapabilities = async (args: CreateApiCapabilitiesArgs, options?: CreateApiCapabilitiesOptions) => { const {baseUrl = "https://api.smartthings.com/v1", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-ST-Organization'] != null) headers.set("X-ST-Organization", String(args['X-ST-Organization'])) if (args.namespace != null) query.append("namespace", String(args.namespace)) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/capabilities${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(capability, await res.json()) };