import {z} from 'zod' export type IconImage = {url?: string | undefined}; export type SmartAppType = 'API_ONLY'; export type SmartAppPrincipalType = 'LOCATION'; export type AppClassification = 'AUTOMATION' | 'SERVICE' | 'DEVICE' | 'CONNECTED_SERVICE' | 'HIDDEN' | 'LABS'; export type CreateOrUpdateApiOnlyRequest = {targetUrl?: string | undefined, privacyPolicyUrl?: string | undefined}; export type AppOAuth = {clientName?: string | undefined, scope?: Array | undefined, redirectUris?: Array | undefined, corsDomains?: Array | undefined}; export type AppUISettings = {pluginId?: unknown | undefined, pluginUri?: string | undefined, dashboardCardsEnabled: boolean, preInstallDashboardCardsEnabled: boolean}; export type CreateSmartAppRequest = {appName: unknown, displayName: string, description: string, singleInstance?: boolean | undefined, iconImage?: IconImage | undefined, appType: SmartAppType, principalType?: SmartAppPrincipalType | undefined, classifications: Array, apiOnly?: CreateOrUpdateApiOnlyRequest | undefined, oauth?: AppOAuth | undefined, ui?: AppUISettings | undefined}; export type CreateApiSmartappsArgs = {Authorization: unknown, accountId?: string | undefined, body: CreateSmartAppRequest}; export type CreateApiSmartappsOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const smartAppType = z.literal("API_ONLY"); export const smartAppPrincipalType = z.literal("LOCATION"); export const appClassification = z.enum(["AUTOMATION", "SERVICE", "DEVICE", "CONNECTED_SERVICE", "HIDDEN", "LABS"]); export const iconImage = z.object({url: z.string().optional()}); export const owner = z.object({ownerType: z.enum(["USER", "SYSTEM", "IMPLICIT", "ACCOUNT"]), ownerId: z.string()}); export const appTargetStatus = z.enum(["PENDING", "CONFIRMED"]); export const appSubscription = z.object({targetUrl: z.string().max(2048).optional(), targetStatus: appTargetStatus.optional()}); export const apiOnly = z.object({subscription: appSubscription.optional(), privacyPolicyUrl: z.string().max(2048).optional()}); export const appUISettings = z.object({pluginId: z.string().optional(), pluginUri: z.string().optional(), dashboardCardsEnabled: z.boolean(), preInstallDashboardCardsEnabled: z.boolean()}); export const smartApp = z.object({appName: z.string().optional(), appId: z.string().optional(), appType: smartAppType.optional(), principalType: smartAppPrincipalType.optional(), classifications: z.array(appClassification).optional(), displayName: z.string().max(75).optional(), description: z.string().max(250).optional(), singleInstance: z.boolean().optional(), iconImage: iconImage.optional(), installMetadata: z.record(z.string(), z.string()).optional(), owner: owner.optional(), createdDate: z.string().optional(), lastUpdatedDate: z.string().optional(), apiOnly: apiOnly.optional(), ui: appUISettings.optional()}); export const createSmartAppResponse = z.object({app: smartApp.optional(), oauthClientId: z.string().optional(), oauthClientSecret: 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 }; /** * Create an App * * POST /smartapps */ export const createApiSmartapps = async (args: CreateApiSmartappsArgs, options?: CreateApiSmartappsOptions) => { 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.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args.accountId != null) query.append("accountId", String(args.accountId)) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/smartapps${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(createSmartAppResponse, await res.json()) };