import {z} from 'zod' export type DeviceId = {id: string, entityType: 'DEVICE'}; export type TenantId = {id: string, entityType: 'TENANT'}; export type CustomerId = {id: string, entityType: 'CUSTOMER'}; export type DeviceProfileId = {id: string, entityType: 'DEVICE_PROFILE'}; export type OtaPackageId = {id: string, entityType: 'OTA_PACKAGE'}; export type JsonNode = unknown; export type DefaultDeviceConfiguration = {type: string}; export type CoapDeviceTransportConfiguration = {type: string, powerMode?: ('PSM' | 'DRX' | 'E_DRX') | undefined, psmActivityTimer?: number | undefined, edrxCycle?: number | undefined, pagingTransmissionWindow?: number | undefined}; export type DefaultDeviceTransportConfiguration = {type: string}; export type Lwm2mDeviceTransportConfiguration = {type: string, powerMode?: ('PSM' | 'DRX' | 'E_DRX') | undefined, psmActivityTimer?: number | undefined, edrxCycle?: number | undefined, pagingTransmissionWindow?: number | undefined}; export type MqttDeviceTransportConfiguration = {type: string}; export type SnmpDeviceTransportConfiguration = {type: string, host?: string | undefined, port?: number | undefined, protocolVersion?: ('V1' | 'V2C' | 'V3') | undefined, community?: string | undefined, username?: string | undefined, securityName?: string | undefined, contextName?: string | undefined, authenticationProtocol?: ('SHA_1' | 'SHA_224' | 'SHA_256' | 'SHA_384' | 'SHA_512' | 'MD5') | undefined, authenticationPassphrase?: string | undefined, privacyProtocol?: ('DES' | 'AES_128' | 'AES_192' | 'AES_256') | undefined, privacyPassphrase?: string | undefined, engineId?: string | undefined}; export type DeviceData = {configuration?: DefaultDeviceConfiguration | undefined, transportConfiguration?: (CoapDeviceTransportConfiguration | DefaultDeviceTransportConfiguration | Lwm2mDeviceTransportConfiguration | MqttDeviceTransportConfiguration | SnmpDeviceTransportConfiguration) | undefined}; export type Device = {id?: DeviceId | undefined, createdTime?: number | undefined, tenantId?: TenantId | undefined, customerId?: CustomerId | undefined, name: string, type?: string | undefined, label?: string | undefined, deviceProfileId: DeviceProfileId, firmwareId?: OtaPackageId | undefined, softwareId?: OtaPackageId | undefined, version?: number | undefined, additionalInfo?: JsonNode | undefined, deviceData?: DeviceData | undefined}; export type DeviceCredentialsId = {id: string}; export type DeviceCredentials = {id: DeviceCredentialsId, createdTime?: number | undefined, deviceId: DeviceId, credentialsType?: ('ACCESS_TOKEN' | 'X509_CERTIFICATE' | 'MQTT_BASIC' | 'LWM2M_CREDENTIALS') | undefined, credentialsId: string, credentialsValue?: string | undefined, version?: number | undefined}; export type SaveDeviceWithCredentialsRequest = {device: Device, credentials: DeviceCredentials}; export type CreateApiApiDeviceWithCredentialsArgs = {nameConflictPolicy?: ('FAIL' | 'UNIQUIFY') | undefined, uniquifySeparator?: string | undefined, uniquifyStrategy?: ('RANDOM' | 'INCREMENTAL') | undefined, body: SaveDeviceWithCredentialsRequest}; export type CreateApiApiDeviceWithCredentialsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const deviceId = z.object({id: z.string(), entityType: z.literal("DEVICE")}); export const tenantId = z.object({id: z.string(), entityType: z.literal("TENANT")}); export const customerId = z.object({id: z.string(), entityType: z.literal("CUSTOMER")}); export const deviceProfileId = z.object({id: z.string(), entityType: z.literal("DEVICE_PROFILE")}); export const otaPackageId = z.object({id: z.string(), entityType: z.literal("OTA_PACKAGE")}); export const jsonNode = z.unknown(); export const defaultDeviceConfiguration = z.object({type: z.string()}); export const coapDeviceTransportConfiguration = z.object({type: z.string(), powerMode: z.enum(["PSM", "DRX", "E_DRX"]).optional(), psmActivityTimer: z.number().int().optional(), edrxCycle: z.number().int().optional(), pagingTransmissionWindow: z.number().int().optional()}); export const defaultDeviceTransportConfiguration = z.object({type: z.string()}); export const lwm2mDeviceTransportConfiguration = z.object({type: z.string(), powerMode: z.enum(["PSM", "DRX", "E_DRX"]).optional(), psmActivityTimer: z.number().int().optional(), edrxCycle: z.number().int().optional(), pagingTransmissionWindow: z.number().int().optional()}); export const mqttDeviceTransportConfiguration = z.object({type: z.string()}); export const snmpDeviceTransportConfiguration = z.object({type: z.string(), host: z.string().optional(), port: z.number().int().optional(), protocolVersion: z.enum(["V1", "V2C", "V3"]).optional(), community: z.string().optional(), username: z.string().optional(), securityName: z.string().optional(), contextName: z.string().optional(), authenticationProtocol: z.enum(["SHA_1", "SHA_224", "SHA_256", "SHA_384", "SHA_512", "MD5"]).optional(), authenticationPassphrase: z.string().optional(), privacyProtocol: z.enum(["DES", "AES_128", "AES_192", "AES_256"]).optional(), privacyPassphrase: z.string().optional(), engineId: z.string().optional()}); export const deviceData = z.object({configuration: defaultDeviceConfiguration.optional(), transportConfiguration: z.union([coapDeviceTransportConfiguration, defaultDeviceTransportConfiguration, lwm2mDeviceTransportConfiguration, mqttDeviceTransportConfiguration, snmpDeviceTransportConfiguration]).optional()}); export const device = z.object({id: deviceId.optional(), createdTime: z.number().int().optional(), tenantId: tenantId.optional(), customerId: customerId.optional(), name: z.string(), type: z.string().optional(), label: z.string().optional(), deviceProfileId: deviceProfileId, firmwareId: otaPackageId.optional(), softwareId: otaPackageId.optional(), version: z.number().int().optional(), additionalInfo: jsonNode.optional(), deviceData: deviceData.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 Device (saveDevice) with credentials * * POST /api/device-with-credentials */ export const createApiApiDeviceWithCredentials = async (args: CreateApiApiDeviceWithCredentialsArgs, options?: CreateApiApiDeviceWithCredentialsOptions) => { const {baseUrl = "https://demo.thingsboard.io", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.nameConflictPolicy != null) query.append("nameConflictPolicy", String(args.nameConflictPolicy)) if (args.uniquifySeparator != null) query.append("uniquifySeparator", String(args.uniquifySeparator)) if (args.uniquifyStrategy != null) query.append("uniquifyStrategy", String(args.uniquifyStrategy)) const url = `${baseUrl.replace(/\/+$/, '')}/api/device-with-credentials${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(device, await res.json()) };