From a92db38250a5e31e7347b6e517d60b2f164c4288 Mon Sep 17 00:00:00 2001 From: Daniel Lando Date: Wed, 18 Oct 2023 11:52:52 +0200 Subject: [PATCH] chore: bump deps (#3359) --- .eslintrc.js | 1 + SECURITY.md | 2 +- app.ts | 86 +- bin/www.ts | 2 +- docs/guide/mqtt.md | 62 +- genereteDocs.ts | 12 +- lib/BackupManager.ts | 24 +- lib/Constants.ts | 6 +- lib/CustomPlugin.ts | 2 +- lib/EventEmitter.ts | 13 +- lib/Gateway.ts | 222 +- lib/MqttClient.ts | 30 +- lib/SocketManager.ts | 2 +- lib/ZwaveClient.ts | 574 ++-- lib/jsonStore.ts | 2 +- lib/logger.ts | 10 +- lib/utils.ts | 12 +- package.json | 128 +- src/App.vue | 106 +- src/apis/ConfigApis.js | 2 +- src/components/Confirm.vue | 4 +- src/components/ValueId.vue | 6 +- src/components/custom/BgRssiChart.vue | 12 +- src/components/custom/ListInput.vue | 2 +- src/components/custom/NodePanel.vue | 28 +- src/components/custom/QrReader.vue | 6 +- src/components/custom/StatisticsCard.vue | 14 +- src/components/custom/ZwaveGraph.vue | 16 +- src/components/dialogs/DialogAssociation.vue | 6 +- src/components/dialogs/DialogGatewayValue.vue | 2 +- src/components/dialogs/DialogHealthCheck.vue | 24 +- src/components/dialogs/DialogNodesManager.vue | 20 +- .../nodes-table/AssociationGroups.vue | 10 +- src/components/nodes-table/ColumnFilter.vue | 4 +- .../nodes-table/ColumnFilterNumber.vue | 4 +- src/components/nodes-table/ExpandedNode.vue | 10 +- src/components/nodes-table/HomeAssistant.vue | 22 +- src/components/nodes-table/NodeDetails.vue | 20 +- src/components/nodes-table/NodeScheduler.vue | 18 +- src/components/nodes-table/OTAUpdates.vue | 8 +- src/components/nodes-table/SmartView.vue | 4 +- src/components/nodes-table/UserCodeTable.vue | 8 +- src/components/nodes-table/nodes-table.js | 4 +- src/mixins/InstancesMixin.js | 14 +- src/modules/ManagedItems.js | 10 +- src/modules/ManagedItems.test.js | 14 +- src/modules/NodeCollection.js | 25 +- src/modules/NodeCollection.test.js | 10 +- src/stores/base.js | 2 +- src/views/ControlPanel.vue | 62 +- src/views/Debug.vue | 4 +- src/views/Scenes.vue | 14 +- src/views/Settings.vue | 44 +- src/views/SmartStart.vue | 24 +- src/views/Store.vue | 34 +- test/lib/Constants.test.ts | 10 +- test/lib/Gateway.test.ts | 8 +- test/lib/jsonStore.test.ts | 16 +- test/lib/utils.test.ts | 2 +- yarn.lock | 2641 ++++++++--------- 60 files changed, 2134 insertions(+), 2350 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 07f85acf866..6230b98b6a6 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -61,6 +61,7 @@ module.exports = { '@typescript-eslint/no-implied-eval': 'off', '@typescript-eslint/no-misused-promises': 'off', '@typescript-eslint/no-unsafe-argument': 'off', + '@typescript-eslint/no-unsafe-enum-comparison': 'off', }, }, ], diff --git a/SECURITY.md b/SECURITY.md index bfe1709ecb5..399045654d9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,4 +2,4 @@ ## Reporting a Vulnerability -Please email daniel.sorridi+zwave-js-ui@gmail.com; chris+zwave-js-ui@cns.me.uk +Please email ; diff --git a/app.ts b/app.ts index 18dd0226223..da8ccf21aeb 100644 --- a/app.ts +++ b/app.ts @@ -61,7 +61,7 @@ declare module 'express-session' { function multerPromise( m: RequestHandler, req: Request, - res: Response + res: Response, ): Promise { return new Promise((resolve, reject) => { m(req, res, (err: any) => { @@ -139,7 +139,7 @@ const socketManager = new SocketManager() socketManager.authMiddleware = function ( socket: Socket & { user?: User }, - next: (err?) => void + next: (err?) => void, ) { if (!isAuthEnabled()) { next() @@ -151,7 +151,7 @@ socketManager.authMiddleware = function ( if (err) return next(new Error('Authentication error')) socket.user = decoded next() - } + }, ) } else { next(new Error('Authentication error')) @@ -192,16 +192,16 @@ export async function startServer(host: string, port: number | string) { cert, rejectUnauthorized: false, }, - app + app, ) } else { logger.warn( - 'HTTPS is enabled but cert or key cannot be generated. Falling back to HTTP' + 'HTTPS is enabled but cert or key cannot be generated. Falling back to HTTP', ) } } else { logger.warn( - 'HTTPS enabled but FORCE_DISABLE_SSL env var is set. Falling back to HTTP' + 'HTTPS enabled but FORCE_DISABLE_SSL env var is set. Falling back to HTTP', ) } } @@ -217,7 +217,7 @@ export async function startServer(host: string, port: number | string) { logger.info( `Listening on ${bind} host ${host} protocol ${ httpsEnabled ? 'HTTPS' : 'HTTP' - }` + }`, ) }) @@ -340,7 +340,7 @@ async function loadCertKey(): Promise<{ if (!cert || !key) { logger.info( - 'Cert and key not found in store, generating fresh new ones...' + 'Cert and key not found in store, generating fresh new ones...', ) try { @@ -375,7 +375,7 @@ async function startGateway(settings: Settings) { sessionSecret === 'DEFAULT_SESSION_SECRET_CHANGE_ME' ) { logger.error( - 'Session secret is the default one. For security reasons you should change it by using SESSION_SECRET env var' + 'Session secret is the default one. For security reasons you should change it by using SESSION_SECRET env var', ) } @@ -411,7 +411,7 @@ async function startGateway(settings: Settings) { // eslint-disable-next-line @typescript-eslint/no-var-requires require(plugin) as PluginConstructor, pluginsContext, - pluginName + pluginName, ) plugins.push(instance) @@ -438,7 +438,10 @@ async function destroyPlugins() { function setupInterceptor() { // intercept logs and redirect them to socket const interceptor = ( - write: (buffer: string | Uint8Array, cb?: (err?: Error) => void) => void + write: ( + buffer: string | Uint8Array, + cb?: (err?: Error) => void, + ) => void, ) => { return function (...args: any[]): boolean { socketManager.io.emit(socketEvents.debug, args[0]?.toString()) @@ -447,10 +450,10 @@ function setupInterceptor() { } process.stdout.write = interceptor( - process.stdout.write.bind(process.stdout) + process.stdout.write.bind(process.stdout), ) process.stderr.write = interceptor( - process.stderr.write.bind(process.stderr) + process.stderr.write.bind(process.stderr), ) } @@ -515,7 +518,7 @@ app.set('view engine', 'ejs') app.use( morgan(loggers.disableColors ? 'tiny' : 'dev', { stream: { write: (msg: string) => logger.info(msg.trimEnd()) }, - }) as RequestHandler + }) as RequestHandler, ) app.use(express.json({ limit: '50mb' }) as RequestHandler) app.use( @@ -523,7 +526,7 @@ app.use( limit: '50mb', extended: true, parameterLimit: 50000, - }) as RequestHandler + }) as RequestHandler, ) // must be placed before history middleware @@ -538,7 +541,7 @@ app.use(function (req, res, next) { app.use( history({ index: '/', - }) + }), ) // fix back compatibility with old history mode after switching to hash mode @@ -590,7 +593,7 @@ app.use( httpOnly: true, // prevents cookie to be sent by client javascript maxAge: 24 * 60 * 60 * 1000, // one day }, - }) + }), ) // Node.js CSRF protection middleware. @@ -637,7 +640,7 @@ function setupSocket(server: HttpServer) { message: 'Zwave client not connected', }) } - } + }, ) // eslint-disable-next-line @typescript-eslint/no-misused-promises @@ -707,7 +710,7 @@ function setupSocket(server: HttpServer) { res = await gw.zwave.storeDevices( data.devices, data.nodeId, - data.remove + data.remove, ) break } @@ -856,7 +859,7 @@ app.post( result.user = userData loginLimiter.resetKey(req.ip) logger.info( - `User ${user.username} logged in successfully from ${req.ip}` + `User ${user.username} logged in successfully from ${req.ip}`, ) } else { result.code = 3 @@ -864,7 +867,7 @@ app.post( logger.error( `User ${ user?.username || req.body.username - } failed to login from ${req.ip}: wrong credentials` + } failed to login from ${req.ip}: wrong credentials`, ) } @@ -879,10 +882,10 @@ app.post( logger.error( `User ${ user?.username || req.body.username - } failed to login from ${req.ip}: ${error.message}` + } failed to login from ${req.ip}: ${error.message}`, ) } - } + }, ) // logout the user @@ -948,7 +951,7 @@ app.put( }) logger.error('Error while updating password', error) } - } + }, ) app.get('/health', apisLimiter, function (req, res) { @@ -1050,7 +1053,7 @@ app.get( } res.json(data) } else res.json(data) - } + }, ) // update settings @@ -1062,7 +1065,7 @@ app.post( try { if (restarting) { throw Error( - 'Gateway is restarting, wait a moment before doing another request' + 'Gateway is restarting, wait a moment before doing another request', ) } // TODO: validate settings using calss-validator @@ -1086,7 +1089,7 @@ app.post( logger.error(error) res.json({ success: false, message: error.message }) } - } + }, ) // update settings @@ -1098,7 +1101,7 @@ app.post( try { if (restarting) { throw Error( - 'Gateway is restarting, wait a moment before doing another request' + 'Gateway is restarting, wait a moment before doing another request', ) } const { enableStatistics } = req.body @@ -1132,7 +1135,7 @@ app.post( logger.error(error) res.json({ success: false, message: error.message }) } - } + }, ) // update versions @@ -1172,7 +1175,7 @@ app.post( logger.error(error) res.json({ success: false, message: error.message }) } - } + }, ) // get config @@ -1217,7 +1220,7 @@ app.post( await gw.zwave.callApi( 'setNodeName', nodeIdNumber, - node.name || '' + node.name || '', ) } @@ -1225,7 +1228,7 @@ app.post( await gw.zwave.callApi( 'setNodeLocation', nodeIdNumber, - node.loc || '' + node.loc || '', ) } @@ -1233,7 +1236,7 @@ app.post( await gw.zwave.storeDevices( node.hassDevices, nodeIdNumber, - false + false, ) } } @@ -1246,7 +1249,7 @@ app.post( logger.error(error.message) return res.json({ success: false, message: error.message }) } - } + }, ) interface StoreFileEntry { @@ -1345,7 +1348,7 @@ app.delete( logger.error(error.message) return res.json({ success: false, message: error.message }) } - } + }, ) app.put( @@ -1363,7 +1366,7 @@ app.put( logger.error(error.message) return res.json({ success: false, message: error.message }) } - } + }, ) app.post( @@ -1411,7 +1414,7 @@ app.post( } await archive.finalize() - } + }, ) app.get( @@ -1426,7 +1429,7 @@ app.get( error: error.message, }) } - } + }, ) app.post( @@ -1462,7 +1465,7 @@ app.post( if (file && isRestore) { await rm(file.path) } - } + }, ) app.get('/api/snippet', apisLimiter, async function (req, res) { @@ -1490,7 +1493,7 @@ app.use(function (req, res, next) { // error handler app.use(function (err: HttpError, req: Request, res: Response) { logger.error( - `${req.method} ${req.url} ${err.status} - Error: ${err.message}` + `${req.method} ${req.url} ${err.status} - Error: ${err.message}`, ) // render the error page @@ -1515,7 +1518,8 @@ async function gracefuShutdown() { process.on('unhandledRejection', (reason) => { const stack = (reason as any).stack || '' logger.error( - `Unhandled Rejection, reason: ${reason}${stack ? `\n${stack}` : ''}` + // eslint-disable-next-line @typescript-eslint/no-base-to-string + `Unhandled Rejection, reason: ${reason}${stack ? `\n${stack}` : ''}`, ) }) diff --git a/bin/www.ts b/bin/www.ts index b4dcd86d8d2..2e5e62f4684 100644 --- a/bin/www.ts +++ b/bin/www.ts @@ -10,7 +10,7 @@ import * as conf from '../config/app' import app, { startServer } from '../app' console.log( - ` ______ __ __ _ _____ _ _ _____ \n |___ / \\ \\ / / | |/ ____| | | | |_ _|\n / /____\\ \\ /\\ / /_ ___ _____ | | (___ | | | | | | \n / /______\\ \\/ \\/ / _\' \\ \\ / / _ \\ _ | |\\___ \\ | | | | | | \n / /__ \\ /\\ / (_| |\\ V / __/ | |__| |____) | | |__| |_| |_ \n /_____| \\/ \\/ \\__,_| \\_/ \\___| \\____/|_____/ \\____/|_____|\n` + ` ______ __ __ _ _____ _ _ _____ \n |___ / \\ \\ / / | |/ ____| | | | |_ _|\n / /____\\ \\ /\\ / /_ ___ _____ | | (___ | | | | | | \n / /______\\ \\/ \\/ / _\' \\ \\ / / _ \\ _ | |\\___ \\ | | | | | | \n / /__ \\ /\\ / (_| |\\ V / __/ | |__| |____) | | |__| |_| |_ \n /_____| \\/ \\/ \\__,_| \\_/ \\___| \\____/|_____/ \\____/|_____|\n`, ) // jsonstore is a singleton instance that handles the json configuration files diff --git a/docs/guide/mqtt.md b/docs/guide/mqtt.md index 31c97764553..375317456e0 100644 --- a/docs/guide/mqtt.md +++ b/docs/guide/mqtt.md @@ -109,7 +109,7 @@ async getSchedules( nodeId: number, opts: { mode?: ZUIScheduleEntryLockMode; fromCache: boolean } = { fromCache: true, - } + }, ): Promise; ``` @@ -165,7 +165,7 @@ async setSchedule( | ScheduleEntryLockDailyRepeatingSchedule | ScheduleEntryLockWeekDaySchedule | ScheduleEntryLockYearDaySchedule - ) + ), ): Promise; ``` @@ -191,7 +191,7 @@ Payload: #### `setEnabledSchedule` ```ts -async setEnabledSchedule(nodeId: number, enabled: boolean, userId: number): Promise<{ status: SupervisionStatus.NoSupport | SupervisionStatus.Fail | SupervisionStatus.Success; remainingDuration?: undefined; } | ({ status: SupervisionStatus.Working; remainingDuration: Duration; } & { status: SupervisionStatus.Working | SupervisionStatus.Success; })>; +async setEnabledSchedule(nodeId: number, enabled: boolean, userId: number): Promise; ```
@@ -218,7 +218,7 @@ Payload: ```ts async getAssociations( nodeId: number, - refresh = false + refresh = false, ): Promise; ``` @@ -248,7 +248,7 @@ Payload: async addAssociations( source: AssociationAddress, groupId: number, - associations: AssociationAddress[] + associations: AssociationAddress[], ): Promise; ``` @@ -279,7 +279,7 @@ Payload: async removeAssociations( source: AssociationAddress, groupId: number, - associations: AssociationAddress[] + associations: AssociationAddress[], ): Promise; ``` @@ -439,7 +439,7 @@ Payload: async getNodeNeighbors( nodeId: number, preventThrow = false, - emitNodeUpdate = true + emitNodeUpdate = true, ): Promise; ``` @@ -572,7 +572,7 @@ Payload: ```ts setNodeDefaultSetValueOptions( nodeId: number, - props: Pick + props: Pick, ): void; ``` @@ -724,7 +724,7 @@ async _addSceneValue( sceneid: number, valueId: ZUIValueIdScene, value: any, - timeout: number + timeout: number, ): Promise; ``` @@ -1023,7 +1023,10 @@ Payload: async replaceFailedNode( nodeId: number, strategy: InclusionStrategy = InclusionStrategy.Security_S2, - options?: { qrString?: string; provisioning?: PlannedProvisioningEntry } + options?: { + qrString?: string + provisioning?: PlannedProvisioningEntry + }, ): Promise; ``` @@ -1053,7 +1056,7 @@ Payload: ```ts async getAvailableFirmwareUpdates( nodeId: number, - options?: GetFirmwareUpdatesOptions + options?: GetFirmwareUpdatesOptions, ): Promise<{ version: string; changelog: string; channel: "stable" | "beta"; files: FirmwareUpdateFileInfo[]; downgrade: boolean; normalizedVersion: string; device: { manufacturerId: number; productType: number; productId: number; firmwareVersion: string; rfRegion?: RFRegion; }; }[]>; ``` @@ -1104,7 +1107,7 @@ Payload: ```ts async setPowerlevel( powerlevel: number, - measured0dBm: number + measured0dBm: number, ): Promise; ``` @@ -1161,7 +1164,7 @@ async startInclusion( name?: string dsk?: string location?: string - } + }, ): Promise; ``` @@ -1191,7 +1194,7 @@ Payload: async startExclusion( options: ExclusionOptions = { strategy: ExclusionStrategy.DisableProvisioningEntry, - } + }, ): Promise; ``` @@ -1318,7 +1321,7 @@ async assignPriorityReturnRoute( nodeId: number, destinationNodeId: number, repeaters: number[], - routeSpeed: ZWaveDataRate + routeSpeed: ZWaveDataRate, ): Promise; ``` @@ -1375,7 +1378,7 @@ Payload: async assignPrioritySUCReturnRoute( nodeId: number, repeaters: number[], - routeSpeed: ZWaveDataRate + routeSpeed: ZWaveDataRate, ): Promise; ``` @@ -1433,7 +1436,7 @@ async assignCustomReturnRoutes( nodeId: number, destinationNodeId: number, routes: Route[], - priorityRoute?: Route + priorityRoute?: Route, ): Promise; ``` @@ -1490,7 +1493,7 @@ Payload: async assignCustomSUCReturnRoutes( nodeId: number, routes: Route[], - priorityRoute?: Route + priorityRoute?: Route, ): Promise; ``` @@ -1622,7 +1625,7 @@ Payload: async setPriorityRoute( nodeId: number, repeaters: number[], - routeSpeed: ZWaveDataRate + routeSpeed: ZWaveDataRate, ): Promise; ``` @@ -1677,7 +1680,7 @@ Payload: ```ts async checkLifelineHealth( nodeId: number, - rounds = 5 + rounds = 5, ): Promise; ``` @@ -1707,7 +1710,7 @@ Payload: async checkRouteHealth( nodeId: number, targetNodeId: number, - rounds = 5 + rounds = 5, ): Promise; ``` @@ -1837,7 +1840,7 @@ Payload: ```ts async firmwareUpdateOTW( - file: FwFile + file: FwFile, ): Promise; ``` @@ -1865,7 +1868,7 @@ Payload: ```ts updateFirmware( nodeId: number, - files: FwFile[] + files: FwFile[], ): Promise; ``` @@ -2006,7 +2009,7 @@ async sendCommand( commandClass: CommandClasses | keyof typeof CommandClasses }, command: string, - args: any[] + args: any[], ): Promise; ``` @@ -2090,8 +2093,8 @@ Payload: async writeValue( valueId: ZUIValueId, value: any, - options?: SetValueAPIOptions -): Promise<{ status: SetValueStatus.NoDeviceSupport | SetValueStatus.Fail | SetValueStatus.Success; remainingDuration?: undefined; message?: undefined; } | { status: SetValueStatus.Working; remainingDuration: Duration; message?: undefined; } | { status: SetValueStatus.SuccessUnsupervised; remainingDuration?: undefined; message?: undefined; } | ({ status: SetValueStatus.EndpointNotFound | SetValueStatus.NotImplemented | SetValueStatus.InvalidValue; remainingDuration?: undefined; message: string; } & { status: SetValueStatus.NoDeviceSupport | SetValueStatus.Fail | SetValueStatus.EndpointNotFound | SetValueStatus.NotImplemented | SetValueStatus.InvalidValue; })>; + options?: SetValueAPIOptions, +): Promise; ``` Set a value of a specific zwave valueId. @@ -2206,7 +2209,7 @@ Payload: #### `restoreNVM` ```ts -async restoreNVM(data: Buffer): Promise; +async restoreNVM(data: Buffer, useRaw = false): Promise; ```
@@ -2219,7 +2222,8 @@ Payload: ```json { "args": [ - data + data, + useRaw ] } ``` @@ -2348,7 +2352,7 @@ Payload: ```ts async updateControllerNodeProps( node?: ZUINode, - props: Array<'powerlevel' | 'RFRegion'> = ['powerlevel', 'RFRegion'] + props: Array<'powerlevel' | 'RFRegion'> = ['powerlevel', 'RFRegion'], ): Promise; ``` diff --git a/genereteDocs.ts b/genereteDocs.ts index ef2d822d18d..08b975c082f 100644 --- a/genereteDocs.ts +++ b/genereteDocs.ts @@ -6,16 +6,16 @@ import * as prettier from 'prettier' import { join } from 'path' // Make the linter happy -export function formatWithPrettier( +export async function formatWithPrettier( filename: string, - sourceText: string -): string { + sourceText: string, +): Promise { const prettierOptions = { ...require(join(__dirname, '.prettierrc.js')), // To infer the correct parser filepath: filename, } - return prettier.format(sourceText, prettierOptions) + return await prettier.format(sourceText, prettierOptions) } // Inpired by https://github.com/zwave-js/node-zwave-js/blob/master/packages/maintenance/src/generateTypedDocs.ts#L334 @@ -27,7 +27,7 @@ async function main() { const sourceFile = program.getSourceFileOrThrow(fileName) - const text = formatWithPrettier(docsFile, mqttApis(sourceFile)) + const text = await formatWithPrettier(docsFile, mqttApis(sourceFile)) const content = await readFile(docsFile, 'utf8') @@ -80,7 +80,7 @@ function mqttApis(file: SourceFile) { if (!ZwaveClientClass) throw new Error('ZwaveClient class not found') const methods = ZwaveClientClass.getInstanceMethods().filter((c) => - allowedApis.includes(c.getName() as any) + allowedApis.includes(c.getName() as any), ) let text = '' diff --git a/lib/BackupManager.ts b/lib/BackupManager.ts index fcb65c31c59..5a952f84403 100644 --- a/lib/BackupManager.ts +++ b/lib/BackupManager.ts @@ -68,13 +68,13 @@ class BackupManager { } else { this.storeJob = new Cron( this.config.storeCron, - this.backupStore.bind(this) + this.backupStore.bind(this), ) logger.info( `Backup job started with cron: ${ this.config.storeCron - }. Next run: ${this.nextRun(this.storeJob)}` + }. Next run: ${this.nextRun(this.storeJob)}`, ) } @@ -87,13 +87,13 @@ class BackupManager { } else { this.nvmJob = new Cron( this.config.nvmCron, - this.backupNvm.bind(this) + this.backupNvm.bind(this), ) logger.info( `Backup job started with cron: ${ this.config.nvmCron - }. Next run: ${this.nextRun(this.nvmJob)}` + }. Next run: ${this.nextRun(this.nvmJob)}`, ) } } @@ -111,19 +111,19 @@ class BackupManager { } // cleanup backups dir, keep last backup files const backups = (await readdir(nvmBackupsDir)).filter((f) => - f.startsWith(NVM_BACKUP_PREFIX) + f.startsWith(NVM_BACKUP_PREFIX), ) // keep last `keep` backups if (backups.length > this.config.nvmKeep) { const toDelete = backups.slice( 0, - backups.length - this.config.nvmKeep + backups.length - this.config.nvmKeep, ) await Promise.all( toDelete.map(async (file) => - unlink(joinPath(nvmBackupsDir, file)) - ) + unlink(joinPath(nvmBackupsDir, file)), + ), ) logger.info(`Deleted ${toDelete.length} old NVM backups`) @@ -146,19 +146,19 @@ class BackupManager { } // cleanup backups dir, keep last backup files const backups = (await readdir(storeBackupsDir)).filter((f) => - f.startsWith(STORE_BACKUP_PREFIX) + f.startsWith(STORE_BACKUP_PREFIX), ) // keep last `keep` backups if (backups.length > this.config.storeKeep) { const toDelete = backups.slice( 0, - backups.length - this.config.storeKeep + backups.length - this.config.storeKeep, ) await Promise.all( toDelete.map(async (file) => - unlink(joinPath(storeBackupsDir, file)) - ) + unlink(joinPath(storeBackupsDir, file)), + ), ) logger.info(`Deleted ${toDelete.length} old STORE backups`) diff --git a/lib/Constants.ts b/lib/Constants.ts index a9574334889..13c26ee3a04 100644 --- a/lib/Constants.ts +++ b/lib/Constants.ts @@ -115,12 +115,12 @@ export function productionType(index: number): Record { } export function meterType( ccSpecific: IMeterCCSpecific, - configManager: ConfigManager + configManager: ConfigManager, ): any { const meter = configManager.lookupMeter(ccSpecific.meterType) const scale = configManager.lookupMeterScale( ccSpecific.meterType, - ccSpecific.scale + ccSpecific.scale, ) const cfg = { @@ -741,7 +741,7 @@ export function genericDeviceClass(cls: number): string { } export function specificDeviceClass( genericCls: number, - specificCls: number + specificCls: number, ): string { const clsAttr = genericDeviceClassAttributes(genericCls) if (clsAttr) { diff --git a/lib/CustomPlugin.ts b/lib/CustomPlugin.ts index 0edd26fba09..be207342cf2 100644 --- a/lib/CustomPlugin.ts +++ b/lib/CustomPlugin.ts @@ -20,7 +20,7 @@ export type PluginConstructor = new (context: PluginContext) => CustomPlugin export function createPlugin( constr: T, context: PluginContext, - name: string + name: string, ): CustomPlugin { const ret = new constr(context) ret.name = name diff --git a/lib/EventEmitter.ts b/lib/EventEmitter.ts index 8709d28d678..2d0312b20c3 100644 --- a/lib/EventEmitter.ts +++ b/lib/EventEmitter.ts @@ -39,23 +39,23 @@ export type EventHandler = | ((...args: any[]) => void) export interface TypedEventEmitter< - TEvents extends Record + TEvents extends Record, > { on( event: TEvent, - callback: TEvents[TEvent] + callback: TEvents[TEvent], ): this once( event: TEvent, - callback: TEvents[TEvent] + callback: TEvents[TEvent], ): this removeListener( event: TEvent, - callback: TEvents[TEvent] + callback: TEvents[TEvent], ): this off( event: TEvent, - callback: TEvents[TEvent] + callback: TEvents[TEvent], ): this removeAllListeners(event?: keyof TEvents): this @@ -65,8 +65,9 @@ export interface TypedEventEmitter< ): boolean } +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export class TypedEventEmitter< - TEvents extends Record + TEvents extends Record, > {} // Make TypedEventEmitter inherit from EventEmitter without actually extending diff --git a/lib/Gateway.ts b/lib/Gateway.ts index 3020c10e735..a308ecbfad2 100644 --- a/lib/Gateway.ts +++ b/lib/Gateway.ts @@ -60,7 +60,7 @@ const watch = (filename: string, fn: () => void) => { watchers.get(filename).close() watch(filename, fn) } - }) + }), ) } catch { watchers.set( @@ -75,7 +75,7 @@ const watch = (filename: string, fn: () => void) => { watch(filename, fn) fn() } - }) + }), ) } } @@ -123,7 +123,7 @@ const loadCustomDevices = () => { logger.info( `Loaded ${ Object.keys(devices).length - } custom Hass devices configurations` + } custom Hass devices configurations`, ) } @@ -272,7 +272,7 @@ export default class Gateway { this._mqtt.on('broadcastRequest', this._onBroadRequest.bind(this)) this._mqtt.on( 'multicastRequest', - this._onMulticastRequest.bind(this) + this._onMulticastRequest.bind(this), ) this._mqtt.on('apiCall', this._onApiRequest.bind(this)) this._mqtt.on('hassStatus', this._onHassStatus.bind(this)) @@ -287,7 +287,7 @@ export default class Gateway { this._zwave.on('nodeStatus', this._onNodeStatus.bind(this)) this._zwave.on( 'nodeLastActive', - this._onNodeLastActive.bind(this) + this._onNodeLastActive.bind(this), ) this._zwave.on('valueChanged', this._onValueChanged.bind(this)) @@ -315,7 +315,7 @@ export default class Gateway { if (jobConfig.runOnInit) { this.runJob(jobConfig).catch((error) => { logger.error( - `Error while executing scheduled job "${jobConfig.name}": ${error.message}` + `Error while executing scheduled job "${jobConfig.name}": ${error.message}`, ) }) } @@ -324,7 +324,7 @@ export default class Gateway { try { const job = new Cron( jobConfig.cron, - this.runJob.bind(this, jobConfig) + this.runJob.bind(this, jobConfig), ) if (job?.nextRun()) { @@ -332,12 +332,12 @@ export default class Gateway { logger.info( `Scheduled job "${jobConfig.name}" will run at ${job .nextRun() - .toISOString()}` + .toISOString()}`, ) } } catch (error) { logger.error( - `Error while scheduling job "${jobConfig.name}": ${error.message}` + `Error while scheduling job "${jobConfig.name}": ${error.message}`, ) } } @@ -353,7 +353,7 @@ export default class Gateway { await this.zwave.driverFunction(jobConfig.code) } catch (error) { logger.error( - `Error executing scheduled job "${jobConfig.name}": ${error.message}` + `Error executing scheduled job "${jobConfig.name}": ${error.message}`, ) } @@ -363,7 +363,7 @@ export default class Gateway { logger.info( `Next scheduled job "${jobConfig.name}" will run at ${job .nextRun() - .toISOString()}` + .toISOString()}`, ) } } @@ -448,7 +448,7 @@ export default class Gateway { valueConf.receiveFunction, valueId, payload, - node + node, ) if (parsedVal != null) { payload = parsedVal @@ -457,7 +457,7 @@ export default class Gateway { } } catch (error) { logger.error( - `Error while parsing payload ${payload} for valueID ${valueId}` + `Error while parsing payload ${payload} for valueID ${valueId.id}`, ) } @@ -535,14 +535,14 @@ export default class Gateway { valueTopic( node: ZUINode, valueId: ZUIValueId, - returnObject = false + returnObject = false, ): string | ValueIdTopic { const topic = [] let valueConf: GatewayValue // check if this value is in configuration values array const values = this.config.values.filter( - (v: GatewayValue) => v.device === node.deviceId + (v: GatewayValue) => v.device === node.deviceId, ) if (values && values.length > 0) { const vID = this._getIdWithoutNode(valueId) @@ -562,7 +562,7 @@ export default class Gateway { targetTopic = this.valueTopic( node, targetValue, - false + false, ) as string } } @@ -573,7 +573,7 @@ export default class Gateway { switch (this.config.type) { case GATEWAY_TYPE.NAMED: topic.push( - node.name ? node.name : NODE_PREFIX + valueId.nodeId + node.name ? node.name : NODE_PREFIX + valueId.nodeId, ) topic.push(Constants.commandClass(valueId.commandClass)) @@ -589,7 +589,9 @@ export default class Gateway { topic.push(valueId.nodeId) } else { topic.push( - node.name ? node.name : NODE_PREFIX + valueId.nodeId + node.name + ? node.name + : NODE_PREFIX + valueId.nodeId, ) } topic.push(valueId.commandClass) @@ -674,12 +676,12 @@ export default class Gateway { publishDiscovery( hassDevice: HassDevice, nodeId: number, - options: { deleteDevice?: boolean; forceUpdate?: boolean } = {} + options: { deleteDevice?: boolean; forceUpdate?: boolean } = {}, ): void { try { if (!this.mqttEnabled || !this.config.hassDiscovery) { logger.debug( - 'Enable MQTT gateway and hass discovery to use this function' + 'Enable MQTT gateway and hass discovery to use this function', ) return } @@ -689,7 +691,7 @@ export default class Gateway { `${ options.deleteDevice ? 'Removing' : 'Publishing' } discovery: %o`, - hassDevice + hassDevice, ) this.setDiscovery(nodeId, hassDevice, options.deleteDevice) @@ -719,7 +721,7 @@ export default class Gateway { hassDevice.discoveryTopic, options.deleteDevice ? '' : hassDevice.discovery_payload, { qos: 0, retain: this.config.retainedDiscovery || false }, - this.config.discoveryPrefix + this.config.discoveryPrefix, ) } @@ -727,14 +729,14 @@ export default class Gateway { this._zwave.updateDevice( hassDevice, nodeId, - options.deleteDevice + options.deleteDevice, ) } } catch (error) { logger.log( 'error', `Error while publishing discovery for node ${nodeId}: ${error.message}. Hass device: %o`, - hassDevice + hassDevice, ) } } @@ -746,7 +748,7 @@ export default class Gateway { setDiscovery( nodeId: number, hassDevice: HassDevice, - deleteDevice = false + deleteDevice = false, ): void { for (let k = 0; k < hassDevice.values.length; k++) { const vId = nodeId + '-' + hassDevice.values[k] @@ -784,7 +786,7 @@ export default class Gateway { discoverDevice(node: ZUINode, hassDevice: HassDevice): void { if (!this.mqttEnabled || !this.config.hassDiscovery) { logger.info( - 'Enable MQTT gateway and hass discovery to use this function' + 'Enable MQTT gateway and hass discovery to use this function', ) return } @@ -817,10 +819,10 @@ export default class Gateway { payload.mode_state_template = this._getMappedValuesInverseTemplate( hassDevice.mode_map, - 'off' + 'off', ) payload.mode_state_topic = this._mqtt.getTopic( - this.valueTopic(node, mode) as string + this.valueTopic(node, mode) as string, ) payload.mode_command_topic = payload.mode_state_topic + '/set' @@ -834,7 +836,7 @@ export default class Gateway { const setpoint = node.values[setId] payload.temperature_state_topic = this._mqtt.getTopic( - this.valueTopic(node, setpoint) as string + this.valueTopic(node, setpoint) as string, ) payload.temperature_command_topic = payload.temperature_state_topic + '/set' @@ -842,13 +844,13 @@ export default class Gateway { const action = node.values[payload.action_topic] if (action) { payload.action_topic = this._mqtt.getTopic( - this.valueTopic(node, action) as string + this.valueTopic(node, action) as string, ) if (hassDevice.action_map) { payload.action_template = this._getMappedValuesTemplate( hassDevice.action_map, - 'idle' + 'idle', ) } } @@ -856,7 +858,7 @@ export default class Gateway { const fan = node.values[payload.fan_mode_state_topic] if (fan !== undefined) { payload.fan_mode_state_topic = this._mqtt.getTopic( - this.valueTopic(node, fan) as string + this.valueTopic(node, fan) as string, ) payload.fan_mode_command_topic = payload.fan_mode_state_topic + '/set' @@ -865,7 +867,7 @@ export default class Gateway { payload.fan_mode_state_template = this._getMappedValuesInverseTemplate( hassDevice.fan_mode_map, - 'auto' + 'auto', ) } } @@ -874,12 +876,12 @@ export default class Gateway { node.values[payload.current_temperature_topic] if (currTemp !== undefined) { payload.current_temperature_topic = this._mqtt.getTopic( - this.valueTopic(node, currTemp) as string + this.valueTopic(node, currTemp) as string, ) if (currTemp.unit) { payload.temperature_unit = currTemp.unit.includes( - 'C' + 'C', ) ? 'C' : 'F' @@ -900,8 +902,8 @@ export default class Gateway { ? this._mqtt.getTopic( this.valueTopic( node, - node.values[v] - ) as string + node.values[v], + ) as string, ) : null } @@ -922,7 +924,7 @@ export default class Gateway { if (payload) { const nodeName = this._getNodeName( node, - this.config.ignoreLoc + this.config.ignoreLoc, ) // Set device information using node info @@ -938,7 +940,7 @@ export default class Gateway { undefined, hassDevice, this.config.entityTemplate, - this.config.ignoreLoc + this.config.ignoreLoc, ) // set a unique id for the component @@ -952,7 +954,7 @@ export default class Gateway { const discoveryTopic = this._getDiscoveryTopic( hassDevice, - nodeName + nodeName, ) hassDevice.discoveryTopic = discoveryTopic @@ -969,7 +971,7 @@ export default class Gateway { } catch (error) { logger.error( `Error while discovering device ${hassID} of node ${node.id}: ${error.message}`, - error + error, ) } } @@ -1033,7 +1035,7 @@ export default class Gateway { if (setpoints.length === 0) { logger.warn( - 'Unable to discover climate device, there is no valid setpoint valueId' + 'Unable to discover climate device, there is no valid setpoint valueId', ) return } @@ -1199,7 +1201,7 @@ export default class Gateway { discoverValue(node: ZUINode, vId: string): void { if (!this.mqttEnabled || !this.config.hassDiscovery) { logger.debug( - 'Enable MQTT gateway and hass discovery to use this function' + 'Enable MQTT gateway and hass discovery to use this function', ) return } @@ -1247,7 +1249,7 @@ export default class Gateway { const specificDeviceClass = Constants.specificDeviceClass( node.deviceClass.generic, - node.deviceClass.specific + node.deviceClass.specific, ) // Use a cover_position configuration if ... if ( @@ -1316,7 +1318,7 @@ export default class Gateway { cfg.object_id = utils.joinProps( cfg.object_id, valueId.property, - valueId.propertyKey + valueId.propertyKey, ) break case CommandClasses['Binary Sensor']: { @@ -1329,7 +1331,7 @@ export default class Gateway { if (sensorTypeName) { sensorTypeName = utils.sanitizeTopic( sensorTypeName.toLocaleLowerCase(), - true + true, ) } @@ -1347,14 +1349,14 @@ export default class Gateway { case 'lock': cfg = this._getBinarySensorConfig( sensorTypeName, - true + true, ) break // moisture - normal case 'contact': case 'water': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.MOISTURE + Constants.deviceClass.sensor_binary.MOISTURE, ) break // safety - normal @@ -1362,25 +1364,26 @@ export default class Gateway { case 'co2': case 'tamper': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.SAFETY + Constants.deviceClass.sensor_binary.SAFETY, ) break // problem - normal case 'alarm': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.PROBLEM + Constants.deviceClass.sensor_binary.PROBLEM, ) break // connectivity - normal case 'router': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.CONNECTIVITY + Constants.deviceClass.sensor_binary + .CONNECTIVITY, ) break // battery - normal case 'battery_low': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.BATTERY + Constants.deviceClass.sensor_binary.BATTERY, ) break default: @@ -1404,7 +1407,7 @@ export default class Gateway { // https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/AlarmSensorCC.ts#L40 if (valueId.property === 'state') { cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.PROBLEM + Constants.deviceClass.sensor_binary.PROBLEM, ) cfg.object_id += AlarmSensorType[valueId.propertyKey] ? '_' + AlarmSensorType[valueId.propertyKey] @@ -1430,18 +1433,18 @@ export default class Gateway { switch (valueId.propertyKeyName) { case 'Access Control': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.LOCK + Constants.deviceClass.sensor_binary.LOCK, ) off = 23 // Closed state break case 'Cover status': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.OPENING + Constants.deviceClass.sensor_binary.OPENING, ) break case 'Door state (simple)': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.DOOR + Constants.deviceClass.sensor_binary.DOOR, ) off = 1 // Door closed on payload 1 break @@ -1452,22 +1455,23 @@ export default class Gateway { case 'Over-load status': case 'Hardware status': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.PROBLEM + Constants.deviceClass.sensor_binary.PROBLEM, ) break case 'Heat sensor status': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.HEAT + Constants.deviceClass.sensor_binary.HEAT, ) break case 'Motion sensor status': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.MOTION + Constants.deviceClass.sensor_binary.MOTION, ) break case 'Water Alarm': cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.MOISTURE + Constants.deviceClass.sensor_binary + .MOISTURE, ) break // sensor status has multiple Properties. therefore is good to work @@ -1477,13 +1481,13 @@ export default class Gateway { case 'Smoke Alarm': cfg = this._getBinarySensorConfig( Constants.deviceClass.sensor_binary - .SMOKE + .SMOKE, ) break case 'Water Alarm': cfg = this._getBinarySensorConfig( Constants.deviceClass.sensor_binary - .MOISTURE + .MOISTURE, ) break default: @@ -1505,7 +1509,7 @@ export default class Gateway { cfg.object_id = utils.joinProps( 'notification', valueId.property, - valueId.propertyKey + valueId.propertyKey, ) // TODO: Improve the icons for different propertyKeys! switch (valueId.propertyKey) { @@ -1518,7 +1522,7 @@ export default class Gateway { cfg.discovery_payload.value_template = this._getMappedStateTemplate( valueId.states, - valueId.default + valueId.default, ) } else { return @@ -1541,7 +1545,7 @@ export default class Gateway { // information. With this change, we target only the sensors and not the additional Properties. if (valueId.ccSpecific) { sensor = Constants.sensorType( - valueId.ccSpecific.sensorType + valueId.ccSpecific.sensorType, ) } else { return @@ -1554,7 +1558,7 @@ export default class Gateway { if (valueId.ccSpecific) { sensor = Constants.meterType( valueId.ccSpecific as IMeterCCSpecific, - this._zwave.driver.configManager + this._zwave.driver.configManager, ) sensor.objectId += '_' + valueId.property @@ -1583,7 +1587,7 @@ export default class Gateway { ) { // TODO: class not yet supported by zwavejs logger.warn( - 'Energy Production CC not supported so value cannot be discovered' + 'Energy Production CC not supported so value cannot be discovered', ) // sensor = Constants.productionType(valueId.property) return @@ -1611,7 +1615,7 @@ export default class Gateway { // use battery_low binary sensor cfg = this._getBinarySensorConfig( - Constants.deviceClass.sensor_binary.BATTERY + Constants.deviceClass.sensor_binary.BATTERY, ) // support the case a binary sensor is served under multilevel sensor CC isSensor = false @@ -1625,7 +1629,7 @@ export default class Gateway { cfg.object_id = utils.joinProps( sensor.sensor, - sensor.objectId + sensor.objectId, ) // https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/scales.json @@ -1672,7 +1676,7 @@ export default class Gateway { // payload.payload_not_available = false if ( ['binary_sensor', 'sensor', 'lock', 'climate', 'fan'].includes( - cfg.type + cfg.type, ) ) { payload.json_attributes_topic = payload.state_topic @@ -1700,7 +1704,7 @@ export default class Gateway { valueId, cfg, this.config.entityTemplate, - this.config.ignoreLoc + this.config.ignoreLoc, ) // Set a unique id for the component @@ -1735,7 +1739,7 @@ export default class Gateway { } catch (error) { logger.error( `Error while discovering value ${valueId.id} of node ${node.id}: ${error.message}`, - error + error, ) } } @@ -1748,7 +1752,7 @@ export default class Gateway { const node = this._zwave.nodes.get(nodeId) if (node) { const topics = Object.keys(this.topicValues).filter( - (k) => this.topicValues[k].nodeId === node.id + (k) => this.topicValues[k].nodeId === node.id, ) for (const t of topics) { @@ -1772,7 +1776,7 @@ export default class Gateway { const node = this._zwave.nodes.get(nodeId) if (node) { const topics = Object.keys(node.values).map( - (v) => this.valueTopic(node, node.values[v]) as string + (v) => this.valueTopic(node, node.values[v]) as string, ) for (const t of topics) { @@ -1823,7 +1827,7 @@ export default class Gateway { private _onValueChanged( valueId: ZUIValueId, node: ZUINode, - changed: boolean + changed: boolean, ): void { const isDiscovered = this.discovered[valueId.id] @@ -1860,7 +1864,7 @@ export default class Gateway { valueConf.sendFunction, valueId, tmpVal, - node + node, ) if (parsedVal != null) { tmpVal = parsedVal @@ -1886,7 +1890,7 @@ export default class Gateway { // check if the setpoint topic has changed const setpoint = node.values[setId] const setTopic = this._mqtt.getTopic( - this.valueTopic(node, setpoint) as string + this.valueTopic(node, setpoint) as string, ) if ( setTopic !== @@ -1972,7 +1976,7 @@ export default class Gateway { // prevent to send cached values if them are stateless if (isFromCache && valueId.stateless) { logger.debug( - `Skipping send of stateless value ${valueId.id}: it's from cache` + `Skipping send of stateless value ${valueId.id}: it's from cache`, ) } else { this._mqtt.publish(topic, data, mqttOptions) @@ -1985,7 +1989,7 @@ export default class Gateway { private _onNotification( node: ZUINode, valueId: ZUIValueId, - data: Record + data: Record, ): void { const topic = this.valueTopic(node, valueId) as string @@ -1999,7 +2003,7 @@ export default class Gateway { private _onNodeInited(node: ZUINode): void { // enable poll if required const values = this.config.values?.filter( - (v: GatewayValue) => v.enablePoll && v.device === node.deviceId + (v: GatewayValue) => v.enablePoll && v.device === node.deviceId, ) for (let i = 0; i < values.length; i++) { // don't edit the original object, copy it @@ -2011,7 +2015,7 @@ export default class Gateway { this._zwave.setPollInterval(valueId, values[i].pollInterval) } catch (error) { logger.error( - `Error while enabling poll interval: ${error.message}` + `Error while enabling poll interval: ${error.message}`, ) } } @@ -2153,7 +2157,7 @@ export default class Gateway { private async _onApiRequest( topic: string, apiName: AllowedApis, - payload: { args: Parameters } + payload: { args: Parameters }, ): Promise { if (this._zwave) { const args = payload.args || [] @@ -2181,26 +2185,26 @@ export default class Gateway { */ private async _onBroadRequest( parts: string[], - payload: ValueID & { value: unknown; options?: SetValueAPIOptions } + payload: ValueID & { value: unknown; options?: SetValueAPIOptions }, ): Promise { if (parts.length > 0) { // multiple writes (back compatibility mode) const topic = parts.join('/') const values = Object.keys(this.topicValues).filter((t) => - t.endsWith(topic) + t.endsWith(topic), ) if (values.length > 0) { // all values are the same type just different node,parse the Payload by using the first one payload = this.parsePayload( payload, this.topicValues[values[0]], - this.topicValues[values[0]].conf + this.topicValues[values[0]].conf, ) for (let i = 0; i < values.length; i++) { await this._zwave.writeValue( this.topicValues[values[i]], payload, - payload?.options + payload?.options, ) } } @@ -2227,7 +2231,7 @@ export default class Gateway { */ private async _onWriteRequest( parts: string[], - payload: any + payload: any, ): Promise { const valueTopic = parts.join('/') const valueId = this.topicValues[valueTopic] @@ -2241,7 +2245,7 @@ export default class Gateway { } private async _onMulticastRequest( - payload: ZUIValueId & { nodes: number[]; value: any } + payload: ZUIValueId & { nodes: number[]; value: any }, ): Promise { const nodes = payload.nodes const valueId: ValueID = { @@ -2288,7 +2292,7 @@ export default class Gateway { code: string, valueId: ZUIValueId, value: unknown, - node: ZUINode + node: ZUINode, ) { let result = null @@ -2300,12 +2304,12 @@ export default class Gateway { 'valueId', 'node', 'logger', - code + code, ) result = parseFunc(value, valueId, node, logger) } catch (error) { logger.error( - `Error eval function of value ${valueId.id} ${error.message}` + `Error eval function of value ${valueId.id} ${error.message}`, ) } @@ -2369,7 +2373,7 @@ export default class Gateway { */ private _getDiscoveryTopic( hassDevice: HassDevice, - nodeName: string + nodeName: string, ): string { return `${hassDevice.type}/${utils.sanitizeTopic(nodeName, true)}/${ hassDevice.object_id @@ -2382,7 +2386,7 @@ export default class Gateway { */ private _getMappedValuesTemplate( valueMap: { [x: string]: any }, - defaultValue: string + defaultValue: string, ): string { const map = [] // JSON.stringify converts props to strings and this breaks the template @@ -2392,7 +2396,7 @@ export default class Gateway { } return `{{ {${map.join( - ', ' + ', ', )}}[value_json.value] | default('${defaultValue}') }}` } @@ -2402,7 +2406,7 @@ export default class Gateway { */ private _getMappedValuesInverseTemplate( valueMap: { [x: string]: number }, - defaultValue: string + defaultValue: string, ): string { const map = [] // JSON.stringify converts props to strings and this breaks the template @@ -2412,7 +2416,7 @@ export default class Gateway { } return `{{ {${map.join( - ', ' + ', ', )}}[value_json.value] | default('${defaultValue}') }}` } @@ -2422,7 +2426,7 @@ export default class Gateway { */ private _getMappedStateTemplate( states: ZUIValueIdState[], - defaultValueKey: string | number + defaultValueKey: string | number, ): string { const map = [] let defaultValue = 'value_json.value' @@ -2430,7 +2434,7 @@ export default class Gateway { map.push( `${ typeof s.value === 'number' ? s.value : '"' + s.value + '"' - }: "${s.text}"` + }: "${s.text}"`, ) if (s.value === defaultValueKey) { defaultValue = `'${s.text}'` @@ -2438,7 +2442,7 @@ export default class Gateway { } return `{{ {${map.join( - ',' + ',', )}}[value_json.value] | default(${defaultValue}) }}` } @@ -2448,7 +2452,7 @@ export default class Gateway { private _setBinaryPayloadFromSensor( cfg: HassDevice, valueId: ZUIValueId, - offStateValue = 0 + offStateValue = 0, ): HassDevice { const stateKeys = valueId.states.map((s) => s.value) // Set on/off state from keys @@ -2467,7 +2471,7 @@ export default class Gateway { */ private _getBinarySensorConfig( devClass: string, - reversePayload = false + reversePayload = false, ): HassDevice { const cfg = utils.copy(hassCfg.binary_sensor) cfg.discovery_payload.device_class = devClass @@ -2484,7 +2488,7 @@ export default class Gateway { private _setDiscoveryValue( payload: any, prop: string, - node: ZUINode + node: ZUINode, ): void { if (typeof payload[prop] === 'string') { const valueId = node.values[payload[prop]] @@ -2499,14 +2503,14 @@ export default class Gateway { */ private _addRgbColorSwitch( node: ZUINode, - currentColorValue: ZUIValueId + currentColorValue: ZUIValueId, ): HassDevice { const cfg = utils.copy(hassCfg.light_rgb_dimmer) const currentColorTopics = this.valueTopic( node, currentColorValue, - true + true, ) as ValueIdTopic const endpoint = currentColorValue.endpoint @@ -2515,11 +2519,11 @@ export default class Gateway { cfg.values = [] cfg.discovery_payload.rgb_state_topic = this._mqtt.getTopic( - currentColorTopics.topic + currentColorTopics.topic, ) cfg.discovery_payload.rgb_command_topic = this._mqtt.getTopic( currentColorTopics.targetTopic, - true + true, ) // The following part of code, checks if ML or Binary works. If one exists the other @@ -2548,7 +2552,7 @@ export default class Gateway { const topics = this.valueTopic( node, valueIdState, - true + true, ) as ValueIdTopic if (!topics) { @@ -2560,7 +2564,7 @@ export default class Gateway { discoveredStateTopic = this._mqtt.getTopic(topics.topic) discoveredCommandTopic = this._mqtt.getTopic( topics.targetTopic, - true + true, ) } @@ -2602,7 +2606,7 @@ export default class Gateway { valueId: ZUIValueId, cfg: HassDevice, entityTemplate: string, - ignoreLoc: boolean + ignoreLoc: boolean, ): string { entityTemplate = entityTemplate || '%ln_%o' // when getting the entity name of a device use node props diff --git a/lib/MqttClient.ts b/lib/MqttClient.ts index 10e9a5c29b0..3185a2dd669 100644 --- a/lib/MqttClient.ts +++ b/lib/MqttClient.ts @@ -191,7 +191,7 @@ class MqttClient extends TypedEventEmitter { this.client.publish( this.getClientTopic(MqttClient.STATUS_TOPIC), JSON.stringify({ value: connected, time: Date.now() }), - { retain: this.config.retain, qos: this.config.qos } + { retain: this.config.retain, qos: this.config.qos }, ) } } @@ -204,7 +204,7 @@ class MqttClient extends TypedEventEmitter { this.client.publish( this.getClientTopic(MqttClient.VERSION_TOPIC), JSON.stringify({ value: appVersion, time: Date.now() }), - { retain: this.config.retain, qos: this.config.qos } + { retain: this.config.retain, qos: this.config.qos }, ) } } @@ -228,7 +228,7 @@ class MqttClient extends TypedEventEmitter { options: IClientSubscribeOptions & { addPrefix: boolean } = { qos: 1, addPrefix: true, - } + }, ): Promise { return new Promise((resolve, reject) => { const subOptions: IClientSubscribeOptions = { @@ -245,7 +245,7 @@ class MqttClient extends TypedEventEmitter { logger.log( 'debug', `Subscribing to ${topic} with options %o`, - subOptions + subOptions, ) this.client.subscribe(topic, subOptions, (err, granted) => { if (err) { @@ -256,7 +256,7 @@ class MqttClient extends TypedEventEmitter { for (const res of granted) { if (res.qos === 128) { logger.error( - `Error subscribing to ${topic}, client doesn't have permission to subscribe to it` + `Error subscribing to ${topic}, client doesn't have permission to subscribe to it`, ) } else { logger.info(`Subscribed to ${topic}`) @@ -268,7 +268,7 @@ class MqttClient extends TypedEventEmitter { }) } else { logger.debug( - `Client not connected yet, subscribing to ${topic} later...` + `Client not connected yet, subscribing to ${topic} later...`, ) this.toSubscribe.set(topic, options) reject(Error('Client not connected')) @@ -283,7 +283,7 @@ class MqttClient extends TypedEventEmitter { topic: string, data: any, options?: IClientPublishOptions, - prefix?: string + prefix?: string, ) { if (this.client) { const settingOptions = { @@ -301,7 +301,7 @@ class MqttClient extends TypedEventEmitter { 'Publishing to %s: %o with options %o', topic, data, - options + options, ) this.client.publish( @@ -311,10 +311,10 @@ class MqttClient extends TypedEventEmitter { function (err) { if (err) { logger.error( - `Error while publishing a value ${err.message}` + `Error while publishing a value ${err.message}`, ) } - } + }, ) } // end if client } @@ -339,7 +339,7 @@ class MqttClient extends TypedEventEmitter { } this._clientID = sanitizeTopic( - MqttClient.NAME_PREFIX + (process.env.MQTT_NAME || config.name) + MqttClient.NAME_PREFIX + (process.env.MQTT_NAME || config.name), ) const parsed = url.parse(config.host || '') @@ -421,7 +421,7 @@ class MqttClient extends TypedEventEmitter { const subscribePromises: Promise[] = [] subscribePromises.push( - this.subscribe(MqttClient.HASS_WILL, { addPrefix: false, qos: 1 }) + this.subscribe(MqttClient.HASS_WILL, { addPrefix: false, qos: 1 }), ) // subscribe to actions @@ -435,8 +435,8 @@ class MqttClient extends TypedEventEmitter { MqttClient.ACTIONS[i], '#', ].join('/'), - { addPrefix: false, qos: 1 } - ) + { addPrefix: false, qos: 1 }, + ), ) } @@ -581,7 +581,7 @@ class MqttClient extends TypedEventEmitter { if (this.toSubscribe.size > 0) { this.retrySubTimeout = setTimeout( this._retrySubscribe.bind(this), - 5000 + 5000, ) } } diff --git a/lib/SocketManager.ts b/lib/SocketManager.ts index 9f2e57009a9..069bafb5aab 100644 --- a/lib/SocketManager.ts +++ b/lib/SocketManager.ts @@ -15,7 +15,7 @@ export interface SocketManagerEventCallbacks { [inboundEvents.mqtt]: (socket: Socket, data: any) => void clients: ( event: 'connection' | 'disconnect', - sockets: Map + sockets: Map, ) => void } diff --git a/lib/ZwaveClient.ts b/lib/ZwaveClient.ts index 330dd3dcc0a..26db1f3a06f 100644 --- a/lib/ZwaveClient.ts +++ b/lib/ZwaveClient.ts @@ -136,7 +136,7 @@ const loglevels = require('triple-beam').configs.npm.levels const NEIGHBORS_LOCK_REFRESH = 60 * 1000 function validateMethods( - methods: T + methods: T, ): T { return methods } @@ -238,7 +238,7 @@ export type ZwaveNodeEvents = ZWaveNodeEvents | 'statistics updated' export type ValueIdObserver = ( this: ZwaveClient, node: ZUINode, - valueId: ZUIValueId + valueId: ZUIValueId, ) => void // Define CommandClasses and properties that should be observed @@ -274,7 +274,7 @@ const observedCCProps: { status === UserIDStatus.StatusNotAvailable ) { node.userCodes.available = node.userCodes.available.filter( - (id) => id !== userId + (id) => id !== userId, ) } else { node.userCodes.available.push(userId) @@ -284,7 +284,7 @@ const observedCCProps: { node.userCodes.enabled.push(userId) } else { node.userCodes.enabled = node.userCodes.enabled.filter( - (id) => id !== userId + (id) => id !== userId, ) } @@ -307,7 +307,7 @@ export type AllowedApis = (typeof allowedApis)[number] const ZWAVEJS_LOG_FILE = utils.joinPath( process.env.ZWAVEJS_LOGS_DIR || logsDir, - 'zwavejs_%DATE%.log' + 'zwavejs_%DATE%.log', ) export type ZUIValueIdState = { @@ -633,7 +633,7 @@ export interface ZwaveClientEventCallbacks { valueChanged: ( valueId: ZUIValueId, node: ZUINode, - changed?: boolean + changed?: boolean, ) => void valueWritten: (valueId: ZUIValueId, node: ZUINode, value: unknown) => void } @@ -813,7 +813,7 @@ class ZwaveClient extends TypedEventEmitter { logger.info( `Restarting client in ${timeout / 1000} seconds, retry ${ this.backoffRetry - }` + }`, ) this.restartTimeout = setTimeout(() => { @@ -830,7 +830,7 @@ class ZwaveClient extends TypedEventEmitter { checkIfDestroyed() { if (this.destroyed) { logger.debug( - `Client listening on '${this.cfg.port}' is destroyed, closing` + `Client listening on '${this.cfg.port}' is destroyed, closing`, ) this.close(true).catch((error) => { logger.error(`Error while closing driver: ${error.message}`) @@ -904,13 +904,16 @@ class ZwaveClient extends TypedEventEmitter { } else { // if it's called again and no timeout is set, set a timeout to call function if (!entry.timeout) { - entry.timeout = setTimeout(() => { - const oldEntry = this.throttledFunctions.get(key) - if (oldEntry?.fn) { - oldEntry.lastUpdate = Date.now() - fn() - } - }, entry.lastUpdate + wait - now) + entry.timeout = setTimeout( + () => { + const oldEntry = this.throttledFunctions.get(key) + if (oldEntry?.fn) { + oldEntry.lastUpdate = Date.now() + fn() + } + }, + entry.lastUpdate + wait - now, + ) } // discard the old function and store the new one entry.fn = fn @@ -1064,7 +1067,7 @@ class ZwaveClient extends TypedEventEmitter { async storeDevices( devices: { [key: string]: HassDevice }, nodeId: number, - remove: any + remove: any, ) { const node = this._nodes.get(nodeId) @@ -1180,19 +1183,19 @@ class ZwaveClient extends TypedEventEmitter { nodeId: number, opts: { mode?: ZUIScheduleEntryLockMode; fromCache: boolean } = { fromCache: true, - } + }, ) { const zwaveNode = this.getNode(nodeId) if (!zwaveNode?.commandClasses['Schedule Entry Lock'].isSupported()) { throw new Error( - 'Schedule Entry Lock CC not supported on node ' + nodeId + 'Schedule Entry Lock CC not supported on node ' + nodeId, ) } if (this._lockGetSchedule) { throw new Error( - 'Another request is in progress, cancel it or wait...' + 'Another request is in progress, cancel it or wait...', ) } @@ -1206,22 +1209,22 @@ class ZwaveClient extends TypedEventEmitter { const userCodes = UserCodeCC.getSupportedUsersCached( this.driver, - endpoint + endpoint, ) const numSlots = { numWeekDaySlots: ScheduleEntryLockCC.getNumWeekDaySlotsCached( this.driver, - endpoint + endpoint, ), numYearDaySlots: ScheduleEntryLockCC.getNumYearDaySlotsCached( this.driver, - endpoint + endpoint, ), numDailyRepeatingSlots: ScheduleEntryLockCC.getNumDailyRepeatingSlotsCached( this.driver, - endpoint + endpoint, ), } @@ -1262,10 +1265,10 @@ class ZwaveClient extends TypedEventEmitter { | ScheduleEntryLockWeekDaySchedule | ScheduleEntryLockYearDaySchedule | ScheduleEntryLockDailyRepeatingSchedule, - enabled: boolean + enabled: boolean, ) => { const index = arr.findIndex( - (s) => s.userId === slot.userId && s.slotId === slot.slotId + (s) => s.userId === slot.userId && s.slotId === slot.slotId, ) if (schedule) { const newSlot = { @@ -1287,7 +1290,7 @@ class ZwaveClient extends TypedEventEmitter { const status = UserCodeCC.getUserIdStatusCached( this.driver, endpoint, - i + i, ) if ( @@ -1305,7 +1308,7 @@ class ZwaveClient extends TypedEventEmitter { ScheduleEntryLockCC.getUserCodeScheduleEnabledCached( this.driver, endpoint, - i + i, ) if (enabledUserId) { @@ -1316,19 +1319,19 @@ class ZwaveClient extends TypedEventEmitter { ScheduleEntryLockCC.getUserCodeScheduleKindCached( this.driver, endpoint, - i + i, ) const getCached = ( kind: ScheduleEntryLockScheduleKind, - slotId: number + slotId: number, ) => ScheduleEntryLockCC.getScheduleCached( this.driver, endpoint, kind, i, - slotId + slotId, ) if (!mode || mode === ZUIScheduleEntryLockMode.WEEKLY) { @@ -1347,7 +1350,7 @@ class ZwaveClient extends TypedEventEmitter { ? ( getCached( ScheduleEntryLockScheduleKind.WeekDay, - s + s, ) ) : await zwaveNode.commandClasses[ @@ -1373,7 +1376,7 @@ class ZwaveClient extends TypedEventEmitter { ? ( getCached( ScheduleEntryLockScheduleKind.YearDay, - s + s, ) ) : await zwaveNode.commandClasses[ @@ -1400,7 +1403,7 @@ class ZwaveClient extends TypedEventEmitter { ? ( getCached( ScheduleEntryLockScheduleKind.DailyRepeating, - s + s, ) ) : await zwaveNode.commandClasses[ @@ -1438,13 +1441,13 @@ class ZwaveClient extends TypedEventEmitter { | ScheduleEntryLockDailyRepeatingSchedule | ScheduleEntryLockWeekDaySchedule | ScheduleEntryLockYearDaySchedule - ) + ), ) { const zwaveNode = this.getNode(nodeId) if (!zwaveNode?.commandClasses['Schedule Entry Lock'].isSupported()) { throw new Error( - 'Schedule Entry Lock CC not supported on node ' + nodeId + 'Schedule Entry Lock CC not supported on node ' + nodeId, ) } @@ -1470,21 +1473,21 @@ class ZwaveClient extends TypedEventEmitter { 'Schedule Entry Lock' ].setDailyRepeatingSchedule( slot, - schedule as ScheduleEntryLockDailyRepeatingSchedule + schedule as ScheduleEntryLockDailyRepeatingSchedule, ) } else if (type === 'weekly') { result = await zwaveNode.commandClasses[ 'Schedule Entry Lock' ].setWeekDaySchedule( slot, - schedule as ScheduleEntryLockWeekDaySchedule + schedule as ScheduleEntryLockWeekDaySchedule, ) } else if (type === 'yearly') { result = await zwaveNode.commandClasses[ 'Schedule Entry Lock' ].setYearDaySchedule( slot, - schedule as ScheduleEntryLockYearDaySchedule + schedule as ScheduleEntryLockYearDaySchedule, ) } else { throw new Error('Invalid schedule type') @@ -1497,9 +1500,10 @@ class ZwaveClient extends TypedEventEmitter { weekly: 'getWeekDaySchedule', yearly: 'getYearDaySchedule', } - const res = await zwaveNode.commandClasses['Schedule Entry Lock'][ - methods[type] - ](slot) + const res = + await zwaveNode.commandClasses['Schedule Entry Lock'][ + methods[type] + ](slot) if ( (isDelete && !res) || @@ -1524,7 +1528,7 @@ class ZwaveClient extends TypedEventEmitter { (s: ZUISlot) => ({ ...s, enabled: mode === type, - }) + }), ) } @@ -1532,7 +1536,7 @@ class ZwaveClient extends TypedEventEmitter { if (slots) { const slotIndex = slots.findIndex( - (s) => s.userId === slot.userId && s.slotId === slot.slotId + (s) => s.userId === slot.userId && s.slotId === slot.slotId, ) const newSlot = isDelete ? null @@ -1553,7 +1557,7 @@ class ZwaveClient extends TypedEventEmitter { } const isEnabledUsercode = node.userCodes?.enabled?.includes( - slot.userId + slot.userId, ) if (!isDelete && !isEnabledUsercode) { @@ -1635,7 +1639,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Error while fetching groups associations: ${error.message}` + `Error while fetching groups associations: ${error.message}`, ) } node.groups = [] @@ -1665,7 +1669,7 @@ class ZwaveClient extends TypedEventEmitter { */ async getAssociations( nodeId: number, - refresh = false + refresh = false, ): Promise { const zwaveNode = this.getNode(nodeId) const toReturn: ZUIGroupAssociation[] = [] @@ -1675,7 +1679,7 @@ class ZwaveClient extends TypedEventEmitter { if (refresh) { await zwaveNode.refreshCCValues(CommandClasses.Association) await zwaveNode.refreshCCValues( - CommandClasses['Multi Channel Association'] + CommandClasses['Multi Channel Association'], ) } // https://zwave-js.github.io/node-zwave-js/#/api/controller?id=association-interface @@ -1698,7 +1702,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Error while fetching groups associations: ${error.message}` + `Error while fetching groups associations: ${error.message}`, ) // node doesn't support groups associations } @@ -1706,7 +1710,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Error while fetching groups associations, node not found` + `Error while fetching groups associations, node not found`, ) } @@ -1719,7 +1723,7 @@ class ZwaveClient extends TypedEventEmitter { async addAssociations( source: AssociationAddress, groupId: number, - associations: AssociationAddress[] + associations: AssociationAddress[], ) { const zwaveNode = this.getNode(source.nodeId) @@ -1735,19 +1739,19 @@ class ZwaveClient extends TypedEventEmitter { this._driver.controller.isAssociationAllowed( source, groupId, - a + a, ) ) { this.logNode( zwaveNode, 'info', - `Adding Node ${a.nodeId} to Group ${groupId} of ${sourceMsg}` + `Adding Node ${a.nodeId} to Group ${groupId} of ${sourceMsg}`, ) await this._driver.controller.addAssociations( source, groupId, - [a] + [a], ) return true @@ -1755,7 +1759,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Unable to add Node ${a.nodeId} to Group ${groupId} of ${sourceMsg}` + `Unable to add Node ${a.nodeId} to Group ${groupId} of ${sourceMsg}`, ) } } @@ -1763,14 +1767,14 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Error while adding associations to ${sourceMsg}: ${error.message}` + `Error while adding associations to ${sourceMsg}: ${error.message}`, ) } } else { this.logNode( zwaveNode, 'warn', - `Error while adding associations to ${sourceMsg}, node not found` + `Error while adding associations to ${sourceMsg}, node not found`, ) } @@ -1784,7 +1788,7 @@ class ZwaveClient extends TypedEventEmitter { async removeAssociations( source: AssociationAddress, groupId: number, - associations: AssociationAddress[] + associations: AssociationAddress[], ) { const zwaveNode = this.getNode(source.nodeId) @@ -1799,26 +1803,26 @@ class ZwaveClient extends TypedEventEmitter { zwaveNode, 'info', `Removing associations from ${sourceMsg} Group ${groupId}: %o`, - associations + associations, ) await this._driver.controller.removeAssociations( source, groupId, - associations + associations, ) } catch (error) { this.logNode( zwaveNode, 'warn', - `Error while removing associations from ${sourceMsg}: ${error.message}` + `Error while removing associations from ${sourceMsg}: ${error.message}`, ) } } else { this.logNode( zwaveNode, 'warn', - `Error while removing associations from ${sourceMsg}, node not found` + `Error while removing associations from ${sourceMsg}, node not found`, ) } } @@ -1843,7 +1847,7 @@ class ZwaveClient extends TypedEventEmitter { await this._driver.controller.removeAssociations( source, groupId, - associations as AssociationAddress[] + associations as AssociationAddress[], ) this.logNode( zwaveNode, @@ -1855,7 +1859,7 @@ class ZwaveClient extends TypedEventEmitter { (source.endpoint ? ' Endpoint ' + source.endpoint : '') - } group ${groupId}` + } group ${groupId}`, ) } } @@ -1864,14 +1868,14 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Error while removing all associations from ${nodeId}: ${error.message}` + `Error while removing all associations from ${nodeId}: ${error.message}`, ) } } else { this.logNode( zwaveNode, 'warn', - `Node not found when calling 'removeAllAssociations'` + `Node not found when calling 'removeAllAssociations'`, ) } } @@ -1892,7 +1896,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - `Syncing Node ${nodeId} date and time` + `Syncing Node ${nodeId} date and time`, ) return zwaveNode.setDateAndTime(date) @@ -1900,7 +1904,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Node not found when calling 'syncNodeDateAndTime'` + `Node not found when calling 'syncNodeDateAndTime'`, ) } } @@ -1914,7 +1918,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `Node not found when calling 'manuallyIdleNotificationValue'` + `Node not found when calling 'manuallyIdleNotificationValue'`, ) } } @@ -1930,24 +1934,24 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - `Removing Node ${nodeId} from all associations` + `Removing Node ${nodeId} from all associations`, ) await this._driver.controller.removeNodeFromAllAssociations( - nodeId + nodeId, ) } catch (error) { this.logNode( zwaveNode, 'warn', - `Error while removing Node ${nodeId} from all associations: ${error.message}` + `Error while removing Node ${nodeId} from all associations: ${error.message}`, ) } } else { this.logNode( zwaveNode, 'warn', - `Node not found when calling 'removeNodeFromAllAssociations'` + `Node not found when calling 'removeNodeFromAllAssociations'`, ) } } @@ -1965,7 +1969,7 @@ class ZwaveClient extends TypedEventEmitter { // set the timeout here so if something fails later we don't keep the lock setTimeout( () => (this._lockNeighborsRefresh = false), - NEIGHBORS_LOCK_REFRESH + NEIGHBORS_LOCK_REFRESH, ) const toReturn = {} @@ -1987,16 +1991,15 @@ class ZwaveClient extends TypedEventEmitter { async getNodeNeighbors( nodeId: number, preventThrow = false, - emitNodeUpdate = true + emitNodeUpdate = true, ): Promise { try { if (!this.driverReady) { throw new DriverNotReadyError() } - const neighbors = await this._driver.controller.getNodeNeighbors( - nodeId - ) + const neighbors = + await this._driver.controller.getNodeNeighbors(nodeId) this.logNode(nodeId, 'debug', `Neighbors: ${neighbors.join(', ')}`) const node = this.nodes.get(nodeId) @@ -2014,7 +2017,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( nodeId, 'warn', - `Error while getting neighbors from ${nodeId}: ${error.message}` + `Error while getting neighbors from ${nodeId}: ${error.message}`, ) if (!preventThrow) { @@ -2033,9 +2036,8 @@ class ZwaveClient extends TypedEventEmitter { throw new DriverNotReadyError() } - const result = await this._driver.controller.discoverNodeNeighbors( - nodeId - ) + const result = + await this._driver.controller.discoverNodeNeighbors(nodeId) if (result) { // update neighbors @@ -2063,7 +2065,7 @@ class ZwaveClient extends TypedEventEmitter { const AsyncFunction = Object.getPrototypeOf( // eslint-disable-next-line @typescript-eslint/no-empty-function - async function () {} + async function () {}, ).constructor const fn = new AsyncFunction('driver', code) @@ -2212,7 +2214,7 @@ class ZwaveClient extends TypedEventEmitter { ) { zwaveOptions.securityKeys[key] = Buffer.from( this.cfg.securityKeys[key], - 'hex' + 'hex', ) } } @@ -2224,15 +2226,15 @@ class ZwaveClient extends TypedEventEmitter { this._driver.on('error', this._onDriverError.bind(this)) this._driver.once( 'driver ready', - this._onDriverReady.bind(this) + this._onDriverReady.bind(this), ) this._driver.on( 'all nodes ready', - this._onScanComplete.bind(this) + this._onScanComplete.bind(this), ) this._driver.on( 'bootloader ready', - this._onBootLoaderReady.bind(this) + this._onBootLoaderReady.bind(this), ) logger.info(`Connecting to ${this.cfg.port}`) @@ -2284,7 +2286,7 @@ class ZwaveClient extends TypedEventEmitter { this._driver.destroy().catch((err) => { logger.error( `Error while destroying driver ${err.message}`, - error + error, ) }) } @@ -2300,7 +2302,7 @@ class ZwaveClient extends TypedEventEmitter { } else { logger.error( `Invalid options for driver: ${error.message}`, - error + error, ) } } @@ -2319,7 +2321,7 @@ class ZwaveClient extends TypedEventEmitter { logger.log( level, `[Node ${utils.padNumber(nodeId, 3)}] ${message}`, - ...args + ...args, ) } @@ -2339,7 +2341,7 @@ class ZwaveClient extends TypedEventEmitter { public emitValueChanged( valueId: ZUIValueId, node: ZUINode, - changed: boolean + changed: boolean, ) { valueId.lastUpdate = this.getNode(valueId.nodeId)?.getValueTimestamp(valueId) ?? @@ -2361,7 +2363,7 @@ class ZwaveClient extends TypedEventEmitter { | 'customReturnRoute' | 'prioritySUCReturnRoute' | 'priorityReturnRoute' - > & { bgRssi?: ControllerStatistics['backgroundRSSI'] } + > & { bgRssi?: ControllerStatistics['backgroundRSSI'] }, ) { // NB: be sure that when `statistics` is defined also `lastActive` must be. // when removing props them should be set to null or false in order to be removed on ui @@ -2377,7 +2379,7 @@ class ZwaveClient extends TypedEventEmitter { public emitNodeUpdate( node: ZUINode, - changedProps?: utils.DeepPartial + changedProps?: utils.DeepPartial, ) { if (node.ready && !node.inited) { node.inited = true @@ -2398,7 +2400,7 @@ class ZwaveClient extends TypedEventEmitter { this.sendToSocket( socketEvents.nodeUpdated, changedProps ?? node, - isPartial + isPartial, ) } @@ -2411,7 +2413,7 @@ class ZwaveClient extends TypedEventEmitter { } catch (error) { logger.error( `Error while updating store nodes: ${error.message}`, - error + error, ) if (throwError) { throw error @@ -2473,7 +2475,7 @@ class ZwaveClient extends TypedEventEmitter { setNodeDefaultSetValueOptions( nodeId: number, - props: Pick + props: Pick, ) { const node = this._nodes.get(nodeId) @@ -2561,7 +2563,7 @@ class ZwaveClient extends TypedEventEmitter { sceneid: number, valueId: ZUIValueIdScene, value: any, - timeout: number + timeout: number, ) { const scene = this.scenes.find((s) => s.sceneid === sceneid) const node = this._nodes.get(valueId.nodeId) @@ -2625,10 +2627,10 @@ class ZwaveClient extends TypedEventEmitter { setTimeout( () => { this.writeValue(values[i], values[i].value).catch( - logger.error + logger.error, ) }, - values[i].timeout ? values[i].timeout * 1000 : 0 + values[i].timeout ? values[i].timeout * 1000 : 0, ) } @@ -2663,7 +2665,7 @@ class ZwaveClient extends TypedEventEmitter { } logger.warn( - 'Zwavejs driver is not ready yet, statistics will be enabled on driver initialization' + 'Zwavejs driver is not ready yet, statistics will be enabled on driver initialization', ) } @@ -2678,7 +2680,7 @@ class ZwaveClient extends TypedEventEmitter { } logger.warn( - 'Zwavejs driver is not ready yet, statistics will be disabled on driver initialization' + 'Zwavejs driver is not ready yet, statistics will be disabled on driver initialization', ) } @@ -2751,7 +2753,7 @@ class ZwaveClient extends TypedEventEmitter { this.pollIntervals[vID] = setTimeout( this._tryPoll.bind(this, valueId, interval), - interval * 1000 + interval * 1000, ) } else { throw new DriverNotReadyError() @@ -2827,7 +2829,10 @@ class ZwaveClient extends TypedEventEmitter { async replaceFailedNode( nodeId: number, strategy: InclusionStrategy = InclusionStrategy.Security_S2, - options?: { qrString?: string; provisioning?: PlannedProvisioningEntry } + options?: { + qrString?: string + provisioning?: PlannedProvisioningEntry + }, ): Promise { try { if (!this.driverReady) { @@ -2844,9 +2849,12 @@ class ZwaveClient extends TypedEventEmitter { this.commandsTimeout = null } - this.commandsTimeout = setTimeout(() => { - this.stopInclusion().catch(logger.error) - }, (this.cfg.commandsTimeout || 0) * 1000 || 30000) + this.commandsTimeout = setTimeout( + () => { + this.stopInclusion().catch(logger.error) + }, + (this.cfg.commandsTimeout || 0) * 1000 || 30000, + ) this.isReplacing = true // by default replaceFailedNode is secured, pass true to make it not secured @@ -2874,7 +2882,7 @@ class ZwaveClient extends TypedEventEmitter { } return this._driver.controller.replaceFailedNode( nodeId, - inclusionOptions + inclusionOptions, ) } else if ( strategy === InclusionStrategy.Insecure || @@ -2885,7 +2893,7 @@ class ZwaveClient extends TypedEventEmitter { }) } else { throw Error( - `Inclusion strategy not supported with replace failed node api` + `Inclusion strategy not supported with replace failed node api`, ) } } catch (error) { @@ -2896,13 +2904,13 @@ class ZwaveClient extends TypedEventEmitter { async getAvailableFirmwareUpdates( nodeId: number, - options?: GetFirmwareUpdatesOptions + options?: GetFirmwareUpdatesOptions, ) { if (this.driverReady) { const result = await this._driver.controller.getAvailableFirmwareUpdates( nodeId, - options + options, ) // return [ @@ -2970,7 +2978,7 @@ class ZwaveClient extends TypedEventEmitter { const result = await this._driver.controller.firmwareUpdateOTA( nodeId, - updateInfo + updateInfo, ) return result @@ -2981,12 +2989,12 @@ class ZwaveClient extends TypedEventEmitter { async setPowerlevel( powerlevel: number, - measured0dBm: number + measured0dBm: number, ): Promise { if (this.driverReady) { const result = await this._driver.controller.setPowerlevel( powerlevel, - measured0dBm + measured0dBm, ) await this.updateControllerNodeProps(null, ['powerlevel']) @@ -3019,7 +3027,7 @@ class ZwaveClient extends TypedEventEmitter { name?: string dsk?: string location?: string - } + }, ): Promise { if (this.driverReady) { if (backupManager.backupOnEvent) { @@ -3042,9 +3050,12 @@ class ZwaveClient extends TypedEventEmitter { this.tmpNode = undefined } - this.commandsTimeout = setTimeout(() => { - this.stopInclusion().catch(logger.error) - }, (this.cfg.commandsTimeout || 0) * 1000 || 30000) + this.commandsTimeout = setTimeout( + () => { + this.stopInclusion().catch(logger.error) + }, + (this.cfg.commandsTimeout || 0) * 1000 || 30000, + ) let inclusionOptions: InclusionOptions @@ -3055,7 +3066,7 @@ class ZwaveClient extends TypedEventEmitter { break case InclusionStrategy.SmartStart: throw Error( - 'In order to use Smart Start add you node to provisioning list' + 'In order to use Smart Start add you node to provisioning list', ) case InclusionStrategy.Default: inclusionOptions = { @@ -3114,7 +3125,7 @@ class ZwaveClient extends TypedEventEmitter { async startExclusion( options: ExclusionOptions = { strategy: ExclusionStrategy.DisableProvisioningEntry, - } + }, ): Promise { if (this.driverReady) { if (backupManager.backupOnEvent) { @@ -3127,9 +3138,12 @@ class ZwaveClient extends TypedEventEmitter { this.commandsTimeout = null } - this.commandsTimeout = setTimeout(() => { - this.stopExclusion().catch(logger.error) - }, (this.cfg.commandsTimeout || 0) * 1000 || 30000) + this.commandsTimeout = setTimeout( + () => { + this.stopExclusion().catch(logger.error) + }, + (this.cfg.commandsTimeout || 0) * 1000 || 30000, + ) return this._driver.controller.beginExclusion(options) } @@ -3176,9 +3190,8 @@ class ZwaveClient extends TypedEventEmitter { this.sendToSocket(socketEvents.rebuildRoutesProgress, [ [nodeId, status], ]) - const result = await this._driver.controller.rebuildNodeRoutes( - nodeId - ) + const result = + await this._driver.controller.rebuildNodeRoutes(nodeId) status = result ? 'done' : 'failed' this.sendToSocket(socketEvents.rebuildRoutesProgress, [ [nodeId, status], @@ -3203,7 +3216,7 @@ class ZwaveClient extends TypedEventEmitter { const result = this._driver.controller.getPriorityReturnRouteCached( nodeId, - destinationId + destinationId, ) const node = this.nodes.get(nodeId) @@ -3229,7 +3242,7 @@ class ZwaveClient extends TypedEventEmitter { nodeId: number, destinationNodeId: number, repeaters: number[], - routeSpeed: ZWaveDataRate + routeSpeed: ZWaveDataRate, ) { if (!this.driverReady) throw new DriverNotReadyError() @@ -3237,7 +3250,7 @@ class ZwaveClient extends TypedEventEmitter { nodeId, destinationNodeId, repeaters, - routeSpeed + routeSpeed, ) if (result) { @@ -3275,7 +3288,7 @@ class ZwaveClient extends TypedEventEmitter { async assignPrioritySUCReturnRoute( nodeId: number, repeaters: number[], - routeSpeed: ZWaveDataRate + routeSpeed: ZWaveDataRate, ) { if (!this.driverReady) throw new DriverNotReadyError() @@ -3283,7 +3296,7 @@ class ZwaveClient extends TypedEventEmitter { await this._driver.controller.assignPrioritySUCReturnRoute( nodeId, repeaters, - routeSpeed + routeSpeed, ) if (result) { @@ -3303,7 +3316,7 @@ class ZwaveClient extends TypedEventEmitter { const result = this._driver.controller.getCustomReturnRoutesCached( nodeId, - destinationId + destinationId, ) const node = this.nodes.get(nodeId) @@ -3329,7 +3342,7 @@ class ZwaveClient extends TypedEventEmitter { nodeId: number, destinationNodeId: number, routes: Route[], - priorityRoute?: Route + priorityRoute?: Route, ) { if (!this.driverReady) throw new DriverNotReadyError() @@ -3337,7 +3350,7 @@ class ZwaveClient extends TypedEventEmitter { nodeId, destinationNodeId, routes, - priorityRoute + priorityRoute, ) if (result) { @@ -3374,7 +3387,7 @@ class ZwaveClient extends TypedEventEmitter { async assignCustomSUCReturnRoutes( nodeId: number, routes: Route[], - priorityRoute?: Route + priorityRoute?: Route, ) { if (!this.driverReady) throw new DriverNotReadyError() @@ -3382,7 +3395,7 @@ class ZwaveClient extends TypedEventEmitter { await this._driver.controller.assignCustomSUCReturnRoutes( nodeId, routes, - priorityRoute + priorityRoute, ) if (result) { @@ -3399,9 +3412,8 @@ class ZwaveClient extends TypedEventEmitter { */ async getPriorityRoute(nodeId: number) { if (this.driverReady) { - const result = await this._driver.controller.getPriorityRoute( - nodeId - ) + const result = + await this._driver.controller.getPriorityRoute(nodeId) if (result) { const node = this.nodes.get(nodeId) @@ -3480,9 +3492,8 @@ class ZwaveClient extends TypedEventEmitter { async deleteSUCReturnRoutes(nodeId: number) { if (!this.driverReady) throw new DriverNotReadyError() - const result = await this._driver.controller.deleteSUCReturnRoutes( - nodeId - ) + const result = + await this._driver.controller.deleteSUCReturnRoutes(nodeId) if (result) { const node = this.nodes.get(nodeId) @@ -3508,7 +3519,7 @@ class ZwaveClient extends TypedEventEmitter { const result = await this._driver.controller.assignReturnRoutes( nodeId, - destinationNodeId + destinationNodeId, ) if (result) { @@ -3525,9 +3536,8 @@ class ZwaveClient extends TypedEventEmitter { async assignSUCReturnRoutes(nodeId: number) { if (!this.driverReady) throw new DriverNotReadyError() - const result = await this._driver.controller.assignSUCReturnRoutes( - nodeId - ) + const result = + await this._driver.controller.assignSUCReturnRoutes(nodeId) if (result) { this.getCustomSUCReturnRoute(nodeId) @@ -3543,13 +3553,13 @@ class ZwaveClient extends TypedEventEmitter { async setPriorityRoute( nodeId: number, repeaters: number[], - routeSpeed: ZWaveDataRate + routeSpeed: ZWaveDataRate, ): Promise { if (this.driverReady) { const result = await this._driver.controller.setPriorityRoute( nodeId, repeaters, - routeSpeed + routeSpeed, ) if (result) { @@ -3567,9 +3577,8 @@ class ZwaveClient extends TypedEventEmitter { */ async removePriorityRoute(nodeId: number) { if (this.driverReady) { - const result = await this._driver.controller.removePriorityRoute( - nodeId - ) + const result = + await this._driver.controller.removePriorityRoute(nodeId) if (result) { await this.getPriorityRoute(nodeId) @@ -3586,7 +3595,7 @@ class ZwaveClient extends TypedEventEmitter { */ async checkLifelineHealth( nodeId: number, - rounds = 5 + rounds = 5, ): Promise { if (this.driverReady) { const result = await this.getNode(nodeId).checkLifelineHealth( @@ -3594,7 +3603,7 @@ class ZwaveClient extends TypedEventEmitter { this._onHealthCheckProgress.bind(this, { nodeId, targetNodeId: this.driver.controller.ownNodeId, - }) + }), ) return { ...result, targetNodeId: this.driver.controller.ownNodeId } } @@ -3608,7 +3617,7 @@ class ZwaveClient extends TypedEventEmitter { async checkRouteHealth( nodeId: number, targetNodeId: number, - rounds = 5 + rounds = 5, ): Promise { if (this.driverReady) { const zwaveNode = this.getNode(nodeId) @@ -3618,7 +3627,7 @@ class ZwaveClient extends TypedEventEmitter { this._onHealthCheckProgress.bind(this, { nodeId, targetNodeId, - }) + }), ) return { ...result, targetNodeId } @@ -3708,7 +3717,7 @@ class ZwaveClient extends TypedEventEmitter { * Used to trigger an update of controller FW */ async firmwareUpdateOTW( - file: FwFile + file: FwFile, ): Promise { if (this._lockOTWUpdates) { throw Error('Firmware update already in progress') @@ -3727,11 +3736,11 @@ class ZwaveClient extends TypedEventEmitter { firmware = extractFirmware(file.data, format) } catch (err) { throw Error( - `Unable to extract firmware from file '${file.name}'` + `Unable to extract firmware from file '${file.name}'`, ) } const result = await this.driver.controller.firmwareUpdateOTW( - firmware.data + firmware.data, ) this._lockOTWUpdates = false return result @@ -3743,7 +3752,7 @@ class ZwaveClient extends TypedEventEmitter { updateFirmware( nodeId: number, - files: FwFile[] + files: FwFile[], ): Promise { // const result: FirmwareUpdateResult = { // status: FirmwareUpdateStatus.Error_Checksum, @@ -3781,7 +3790,7 @@ class ZwaveClient extends TypedEventEmitter { firmwares.push(firmware) } catch (e) { throw Error( - `Unable to extract firmware from file '${name}': ${e.message}` + `Unable to extract firmware from file '${name}': ${e.message}`, ) } } else { @@ -3876,7 +3885,7 @@ class ZwaveClient extends TypedEventEmitter { commandClass: CommandClasses | keyof typeof CommandClasses }, command: string, - args: any[] + args: any[], ): Promise { if (this.driverReady) { if (typeof ctx.nodeId !== 'number') { @@ -3897,7 +3906,7 @@ class ZwaveClient extends TypedEventEmitter { const endpoint = node.getEndpoint(ctx.endpoint || 0) if (!endpoint) { throw Error( - `Endpoint ${ctx.endpoint} does not exist on Node ${ctx.nodeId}!` + `Endpoint ${ctx.endpoint} does not exist on Node ${ctx.nodeId}!`, ) } @@ -3914,11 +3923,11 @@ class ZwaveClient extends TypedEventEmitter { ctx.endpoint ? ` Endpoint ${ctx.endpoint}` : '' } does not support CC ${ ctx.commandClass - } or it has not been implemented yet` + } or it has not been implemented yet`, ) } else if (!(command in api)) { throw Error( - `The command ${command} does not exist for CC ${ctx.commandClass}` + `The command ${command} does not exist for CC ${ctx.commandClass}`, ) } @@ -3996,11 +4005,12 @@ class ZwaveClient extends TypedEventEmitter { await broadcastNode.setValue(valueId, value) } catch (error) { logger.error( + // eslint-disable-next-line @typescript-eslint/no-base-to-string `Error while sending broadcast ${value} to CC ${ valueId.commandClass } ${valueId.property} ${valueId.propertyKey || ''}: ${ error.message - }` + }`, ) } } @@ -4019,11 +4029,12 @@ class ZwaveClient extends TypedEventEmitter { } catch (error) { fallback = error.code === ZWaveErrorCodes.CC_NotSupported logger.error( + // eslint-disable-next-line @typescript-eslint/no-base-to-string `Error while sending multicast ${value} to CC ${ valueId.commandClass } ${valueId.property} ${valueId.propertyKey || ''}: ${ error.message - }` + }`, ) } // try single writes requests @@ -4041,7 +4052,7 @@ class ZwaveClient extends TypedEventEmitter { async writeValue( valueId: ZUIValueId, value: any, - options?: SetValueAPIOptions + options?: SetValueAPIOptions, ) { let result: SetValueResult = { status: SetValueStatus.Fail, @@ -4123,7 +4134,7 @@ class ZwaveClient extends TypedEventEmitter { logger.log( 'error', `Error while writing %o on ${vID}: ${error.message}`, - value + value, ) } // https://zwave-js.github.io/node-zwave-js/#/api/node?id=setvalue @@ -4133,7 +4144,7 @@ class ZwaveClient extends TypedEventEmitter { `Unable to write %o on ${vID}: %s`, value, result.message || - getEnumMemberName(SetValueStatus, result.status) + getEnumMemberName(SetValueStatus, result.status), ) } } @@ -4177,24 +4188,24 @@ class ZwaveClient extends TypedEventEmitter { .on('node removed', this._onNodeRemoved.bind(this)) .on( 'rebuild routes progress', - this._onRebuildRoutesProgress.bind(this) + this._onRebuildRoutesProgress.bind(this), ) .on('rebuild routes done', this._onRebuildRoutesDone.bind(this)) .on( 'statistics updated', - this._onControllerStatisticsUpdated.bind(this) + this._onControllerStatisticsUpdated.bind(this), ) .on( 'firmware update progress', - this._onControllerFirmwareUpdateProgress.bind(this) + this._onControllerFirmwareUpdateProgress.bind(this), ) .on( 'firmware update finished', - this._onControllerFirmwareUpdateFinished.bind(this) + this._onControllerFirmwareUpdateFinished.bind(this), ) .on( 'status changed', - this._onControllerStatusChanged.bind(this) + this._onControllerStatusChanged.bind(this), ) } catch (error) { // Fixes freak error in "driver ready" handler #1309 @@ -4235,7 +4246,7 @@ class ZwaveClient extends TypedEventEmitter { }) .catch((error) => { logger.error( - `Failed to start zwave-js server: ${error.message}` + `Failed to start zwave-js server: ${error.message}`, ) }) } @@ -4267,7 +4278,7 @@ class ZwaveClient extends TypedEventEmitter { } private _onControllerFirmwareUpdateProgress( - progress: ControllerFirmwareUpdateProgress + progress: ControllerFirmwareUpdateProgress, ) { const nodeId = this.driver.controller.ownNodeId const node = this.nodes.get(nodeId) @@ -4286,7 +4297,7 @@ class ZwaveClient extends TypedEventEmitter { this.emitNodeUpdate.bind(this, node, { firmwareUpdate: node.firmwareUpdate, } as utils.DeepPartial), - 250 + 250, ) } @@ -4295,12 +4306,12 @@ class ZwaveClient extends TypedEventEmitter { EventSource.CONTROLLER, 'controller firmware update progress', this.zwaveNodeToJSON(this.driver.controller.nodes.get(nodeId)), - progress + progress, ) } private _onControllerFirmwareUpdateFinished( - result: ControllerFirmwareUpdateResult + result: ControllerFirmwareUpdateResult, ) { const nodeId = this.driver.controller.ownNodeId const node = this.nodes.get(nodeId) @@ -4315,7 +4326,7 @@ class ZwaveClient extends TypedEventEmitter { success: result.success, status: getEnumMemberName( ControllerFirmwareUpdateStatus, - result.status + result.status, ), }, } as any) @@ -4326,8 +4337,8 @@ class ZwaveClient extends TypedEventEmitter { result.success ? 'successfully' : 'with error' }.\n Status: ${getEnumMemberName( ControllerFirmwareUpdateStatus, - result.status - )}. Result: ${result}.` + result.status, + )}. Result: ${JSON.stringify(result)}.`, ) this.emit( @@ -4335,7 +4346,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.CONTROLLER, 'controller firmware update finished', this.zwaveNodeToJSON(zwaveNode), - result + result, ) } @@ -4407,7 +4418,7 @@ class ZwaveClient extends TypedEventEmitter { } else { message = `Controller is ${getEnumMemberName( ControllerStatus, - status + status, )}` this._error = undefined } @@ -4532,7 +4543,7 @@ class ZwaveClient extends TypedEventEmitter { if (zwaveNode.dsk) { const entry = this.driver.controller.getProvisioningEntry( - dskToString(zwaveNode.dsk) + dskToString(zwaveNode.dsk), ) if (entry) { @@ -4559,7 +4570,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.CONTROLLER, 'node added', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -4576,7 +4587,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.CONTROLLER, 'node removed', this.zwaveNodeToJSON(zwaveNode), - reason + reason, ) this._removeNode(zwaveNode.id) @@ -4586,7 +4597,7 @@ class ZwaveClient extends TypedEventEmitter { * Triggered on each progress of rebuild routes process */ private _onRebuildRoutesProgress( - progress: ReadonlyMap + progress: ReadonlyMap, ) { const toRebuild = [...progress.values()] const rebuiltNodes = toRebuild.filter((v) => v !== 'pending') @@ -4608,7 +4619,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.CONTROLLER, 'rebuild routes progress', - progress + progress, ) } @@ -4620,7 +4631,7 @@ class ZwaveClient extends TypedEventEmitter { round: number, totalRounds: number, lastRating: number, - lastResult: RouteHealthCheckResult | LifelineHealthCheckResult + lastResult: RouteHealthCheckResult | LifelineHealthCheckResult, ) { const message = `Health check ${request.nodeId}-->${request.targetNodeId}: ${round}/${totalRounds} done, last rating ${lastRating}` this._updateControllerStatus(message) @@ -4639,7 +4650,7 @@ class ZwaveClient extends TypedEventEmitter { } private _onGrantSecurityClasses( - requested: InclusionGrant + requested: InclusionGrant, ): Promise { logger.log('info', `Grant security classes: %o`, requested) this.sendToSocket(socketEvents.grantSecurityClasses, requested) @@ -4648,7 +4659,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.CONTROLLER, 'grant security classes', - requested + requested, ) return new Promise((resolve) => { @@ -4718,7 +4729,7 @@ class ZwaveClient extends TypedEventEmitter { this.nvmEvent = null const data = await this.driver.controller.backupNVMRaw( - this._onBackupNVMProgress.bind(this) + this._onBackupNVMProgress.bind(this), ) const fileName = `${NVM_BACKUP_PREFIX}${utils.fileDate()}${event}` @@ -4743,13 +4754,13 @@ class ZwaveClient extends TypedEventEmitter { if (useRaw) { await this.driver.controller.restoreNVMRaw( data, - this._onRestoreNVMProgress.bind(this) + this._onRestoreNVMProgress.bind(this), ) } else { await this.driver.controller.restoreNVM( data, this._onConvertNVMProgress.bind(this), - this._onRestoreNVMProgress.bind(this) + this._onRestoreNVMProgress.bind(this), ) } } @@ -4784,7 +4795,7 @@ class ZwaveClient extends TypedEventEmitter { entry.manufacturerId, entry.productType, entry.productId, - entry.applicationVersion + entry.applicationVersion, ) if (device) { entry.manufacturer = device.manufacturer @@ -4894,7 +4905,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'error', - `Received status update but node doesn't exists` + `Received status update but node doesn't exists`, ) } } @@ -4940,7 +4951,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'error', - `Ready event called but node doesn't exists` + `Ready event called but node doesn't exists`, ) return @@ -4963,7 +4974,7 @@ class ZwaveClient extends TypedEventEmitter { zwaveNode, zwaveValue, existingValues, - true + true, ) if (!res) continue @@ -4974,7 +4985,7 @@ class ZwaveClient extends TypedEventEmitter { // value change event in order to subscribe mqtt topics if (updated || valueId.writeable) { delayedUpdates.push( - this.emitValueChanged.bind(this, valueId, node, true) + this.emitValueChanged.bind(this, valueId, node, true), ) } @@ -5015,7 +5026,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'error', - `Failed to get controller node ${node.id} properties: ${error.message}` + `Failed to get controller node ${node.id} properties: ${error.message}`, ) }) } @@ -5035,7 +5046,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node ready', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) this.logNode( @@ -5043,7 +5054,7 @@ class ZwaveClient extends TypedEventEmitter { 'info', `Ready: ${node.manufacturer} - ${node.productLabel} (${ node.productDescription || 'Unknown' - })` + })`, ) if (zwaveNode.commandClasses['Schedule Entry Lock'].isSupported()) { @@ -5054,9 +5065,9 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'error', - `Failed to get schedules for node ${node.id}: ${error.message}` + `Failed to get schedules for node ${node.id}: ${error.message}`, ) - } + }, ) } @@ -5065,7 +5076,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'error', - `Failed to get priority route for node ${node.id}: ${error.message}` + `Failed to get priority route for node ${node.id}: ${error.message}`, ) }) @@ -5085,7 +5096,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node interview started', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5095,12 +5106,12 @@ class ZwaveClient extends TypedEventEmitter { */ private _onNodeInterviewStageCompleted( zwaveNode: ZWaveNode, - stageName: string + stageName: string, ) { this.logNode( zwaveNode, 'info', - `Interview stage ${stageName.toUpperCase()} completed` + `Interview stage ${stageName.toUpperCase()} completed`, ) this._onNodeStatus(zwaveNode, true) @@ -5109,7 +5120,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node interview stage completed', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5128,7 +5139,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - 'Interview COMPLETED, all values are updated' + 'Interview COMPLETED, all values are updated', ) this._onNodeStatus(zwaveNode, true) @@ -5137,7 +5148,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node interview completed', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5147,12 +5158,12 @@ class ZwaveClient extends TypedEventEmitter { */ private _onNodeInterviewFailed( zwaveNode: ZWaveNode, - args: NodeInterviewFailedEventArgs + args: NodeInterviewFailedEventArgs, ) { this.logNode( zwaveNode, 'error', - `Interview FAILED: ${args.errorMessage}` + `Interview FAILED: ${args.errorMessage}`, ) this._onNodeStatus(zwaveNode, true) @@ -5161,7 +5172,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node interview failed', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5173,7 +5184,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - `Is ${oldStatus === NodeStatus.Unknown ? '' : 'now '}awake` + `Is ${oldStatus === NodeStatus.Unknown ? '' : 'now '}awake`, ) this._onNodeStatus(zwaveNode, true) @@ -5181,7 +5192,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node wakeup', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5193,7 +5204,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - `Is ${oldStatus === NodeStatus.Unknown ? '' : 'now '}asleep` + `Is ${oldStatus === NodeStatus.Unknown ? '' : 'now '}asleep`, ) this._onNodeStatus(zwaveNode, true) @@ -5201,7 +5212,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node sleep', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5221,7 +5232,7 @@ class ZwaveClient extends TypedEventEmitter { 'event', EventSource.NODE, 'node alive', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5234,14 +5245,14 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - `Is ${oldStatus === NodeStatus.Unknown ? '' : 'now '}dead` + `Is ${oldStatus === NodeStatus.Unknown ? '' : 'now '}dead`, ) this.emit( 'event', EventSource.NODE, 'node dead', - this.zwaveNodeToJSON(zwaveNode) + this.zwaveNodeToJSON(zwaveNode), ) } @@ -5251,14 +5262,15 @@ class ZwaveClient extends TypedEventEmitter { */ private _onNodeValueAdded( zwaveNode: ZWaveNode, - args: ZWaveNodeValueAddedArgs + args: ZWaveNodeValueAddedArgs, ) { this.logNode( zwaveNode, 'info', `Value added: ${this._getValueID( - args as unknown as ZUIValueId - )} => ${args.newValue}` + args as unknown as ZUIValueId, + // eslint-disable-next-line @typescript-eslint/no-base-to-string + )} => ${args.newValue}`, ) // handle node values added 'on fly' @@ -5276,7 +5288,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.NODE, 'node value added', this.zwaveNodeToJSON(zwaveNode), - args + args, ) } @@ -5289,7 +5301,7 @@ class ZwaveClient extends TypedEventEmitter { args: ZWaveNodeValueNotificationArgs & { newValue?: any stateless: boolean - } + }, ) { // notification hasn't `newValue` args.newValue = args.value @@ -5309,7 +5321,7 @@ class ZwaveClient extends TypedEventEmitter { prevValue?: any newValue?: any stateless: boolean - } + }, ) { this._updateValue(zwaveNode, args) @@ -5322,7 +5334,7 @@ class ZwaveClient extends TypedEventEmitter { args.stateless ? args.newValue : `${args.prevValue} => ${args.newValue}` - }` + }`, ) this.emit( @@ -5330,7 +5342,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.NODE, 'node value updated', this.zwaveNodeToJSON(zwaveNode), - args + args, ) } @@ -5340,21 +5352,21 @@ class ZwaveClient extends TypedEventEmitter { */ private _onNodeValueRemoved( zwaveNode: ZWaveNode, - args: ZWaveNodeValueRemovedArgs + args: ZWaveNodeValueRemovedArgs, ) { this._removeValue(zwaveNode, args) this.logNode( zwaveNode, 'info', - `Value removed: ${this._getValueID(args)}` + `Value removed: ${this._getValueID(args)}`, ) this.emit( 'event', EventSource.NODE, 'node value removed', this.zwaveNodeToJSON(zwaveNode), - args + args, ) } @@ -5364,7 +5376,7 @@ class ZwaveClient extends TypedEventEmitter { */ private _onNodeMetadataUpdated( zwaveNode: ZWaveNode, - args: ZWaveNodeMetadataUpdatedArgs + args: ZWaveNodeMetadataUpdatedArgs, ) { const value = this._parseValue(zwaveNode, args, args.metadata) @@ -5374,15 +5386,15 @@ class ZwaveClient extends TypedEventEmitter { zwaveNode, 'info', `Metadata updated: ${this._getValueID( - args as unknown as ZUIValueId - )}` + args as unknown as ZUIValueId, + )}`, ) this.emit( 'event', EventSource.NODE, 'node metadata updated', this.zwaveNodeToJSON(zwaveNode), - args + args, ) } @@ -5399,7 +5411,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( endpoint.nodeId, 'error', - `Notification received but node doesn't exists` + `Notification received but node doesn't exists`, ) return @@ -5430,7 +5442,7 @@ class ZwaveClient extends TypedEventEmitter { } else if (ccId === CommandClasses['Multilevel Switch']) { valueId.property = getEnumMemberName( MultilevelSwitchCommand, - args.eventType as number + args.eventType as number, ) data = args.direction } else if (ccId === CommandClasses.Powerlevel) { @@ -5442,7 +5454,7 @@ class ZwaveClient extends TypedEventEmitter { 'error', 'Unknown notification received CC %s: %o', valueId.commandClassName, - args + args, ) return @@ -5456,7 +5468,7 @@ class ZwaveClient extends TypedEventEmitter { 'info', `CC %s notification %o`, valueId.commandClassName, - args + args, ) const node = this._nodes.get(zwaveNode.id) @@ -5469,13 +5481,13 @@ class ZwaveClient extends TypedEventEmitter { 'node notification', this.zwaveNodeToJSON(zwaveNode), ccId, - args + args, ) } private _onNodeStatisticsUpdated( zwaveNode: ZWaveNode, - stats: NodeStatistics + stats: NodeStatistics, ) { const node = this.nodes.get(zwaveNode.id) @@ -5500,7 +5512,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.NODE, 'statistics updated', this.zwaveNodeToJSON(zwaveNode), - stats + stats, ) } @@ -5512,7 +5524,7 @@ class ZwaveClient extends TypedEventEmitter { function _onNodeFirmwareUpdateProgress( this: ZwaveClient, zwaveNode: ZWaveNode, - progress: FirmwareUpdateProgress + progress: FirmwareUpdateProgress, ) { const node = this.nodes.get(zwaveNode.id) if (node) { @@ -5523,7 +5535,7 @@ class ZwaveClient extends TypedEventEmitter { this.emitNodeUpdate.bind(this, node, { firmwareUpdate: progress, } as utils.DeepPartial), - 250 + 250, ) } @@ -5532,7 +5544,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.NODE, 'node firmware update progress', this.zwaveNodeToJSON(zwaveNode), - progress + progress, ) } @@ -5544,7 +5556,7 @@ class ZwaveClient extends TypedEventEmitter { function _onNodeFirmwareUpdateFinished( this: ZwaveClient, zwaveNode: ZWaveNode, - result: FirmwareUpdateResult + result: FirmwareUpdateResult, ) { const node = this.nodes.get(zwaveNode.id) if (node) { @@ -5562,10 +5574,10 @@ class ZwaveClient extends TypedEventEmitter { result.success ? 'successfully' : 'with error' }.\n Status: ${getEnumMemberName( FirmwareUpdateStatus, - result.status + result.status, )}.\n Wait before interacting: ${ result.waitTime !== undefined ? `${result.waitTime}s` : 'No' - }.\n Result: ${result}.` + }.\n Result: ${JSON.stringify(result)}.`, ) if (result.reInterview) { @@ -5577,7 +5589,7 @@ class ZwaveClient extends TypedEventEmitter { EventSource.NODE, 'node firmware update finished', this.zwaveNodeToJSON(zwaveNode), - result + result, ) } @@ -5596,11 +5608,11 @@ class ZwaveClient extends TypedEventEmitter { .on('interview started', this._onNodeInterviewStarted.bind(this)) .on( 'interview stage completed', - this._onNodeInterviewStageCompleted.bind(this) + this._onNodeInterviewStageCompleted.bind(this), ) .on( 'interview completed', - this._onNodeInterviewCompleted.bind(this) + this._onNodeInterviewCompleted.bind(this), ) .on('interview failed', this._onNodeInterviewFailed.bind(this)) .on('wake up', this._onNodeWakeUp.bind(this)) @@ -5615,11 +5627,11 @@ class ZwaveClient extends TypedEventEmitter { .on('notification', this._onNodeNotification.bind(this)) .on( 'firmware update progress', - this._onNodeFirmwareUpdateProgress.bind(this) + this._onNodeFirmwareUpdateProgress.bind(this), ) .on( 'firmware update finished', - this._onNodeFirmwareUpdateFinished.bind(this) + this._onNodeFirmwareUpdateFinished.bind(this), ) .on('statistics updated', this._onNodeStatisticsUpdated.bind(this)) @@ -5733,7 +5745,7 @@ class ZwaveClient extends TypedEventEmitter { if (existingNode && existingNode.ready) { logger.error( 'Error while adding node ' + nodeId, - Error('node has been added twice') + Error('node has been added twice'), ) return existingNode } @@ -5773,7 +5785,7 @@ class ZwaveClient extends TypedEventEmitter { description: hexIds[2], manufacturer: this.driver.configManager.lookupManufacturer( - zwaveNode.manufacturerId + zwaveNode.manufacturerId, ) || `Unknown manufacturer ${hexIds[0]}`, } @@ -5839,7 +5851,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'debug', - `Setting node name to '${node.name}'` + `Setting node name to '${node.name}'`, ) zwaveNode.name = node.name } @@ -5847,7 +5859,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'debug', - `Setting node location to '${node.loc}'` + `Setting node location to '${node.loc}'`, ) zwaveNode.location = node.loc } @@ -5861,13 +5873,13 @@ class ZwaveClient extends TypedEventEmitter { async updateControllerNodeProps( node?: ZUINode, - props: Array<'powerlevel' | 'RFRegion'> = ['powerlevel', 'RFRegion'] + props: Array<'powerlevel' | 'RFRegion'> = ['powerlevel', 'RFRegion'], ) { node = node || this.nodes.get(this._driver.controller.ownNodeId) if (props.includes('powerlevel')) { if ( this._driver.controller.isSerialAPISetupCommandSupported( - SerialAPISetupCommand.GetPowerlevel + SerialAPISetupCommand.GetPowerlevel, ) ) { const { powerlevel, measured0dBm } = @@ -5882,7 +5894,7 @@ class ZwaveClient extends TypedEventEmitter { if (props.includes('RFRegion')) { if ( this._driver.controller.isSerialAPISetupCommandSupported( - SerialAPISetupCommand.GetRFRegion + SerialAPISetupCommand.GetRFRegion, ) ) { node.RFRegion = await this._driver.controller.getRFRegion() @@ -5905,7 +5917,7 @@ class ZwaveClient extends TypedEventEmitter { private _updateValueMetadata( zwaveNode: ZWaveNode, zwaveValue: TranslatedValueID & { [x: string]: any }, - zwaveValueMeta: ValueMetadata + zwaveValueMeta: ValueMetadata, ): ZUIValueId { zwaveValue.nodeId = zwaveNode.id @@ -5939,7 +5951,7 @@ class ZwaveClient extends TypedEventEmitter { const endpoint = zwaveNode.getEndpoint(zwaveValue.endpoint) valueId.commandClassVersion = (endpoint ?? zwaveNode).getCCVersion( - zwaveValue.commandClass + zwaveValue.commandClass, ) } @@ -5996,7 +6008,7 @@ class ZwaveClient extends TypedEventEmitter { oldValues?: { [key: string]: ZUIValueId }, - skipUpdate = false + skipUpdate = false, ) { const node = this._nodes.get(zwaveNode.id) @@ -6008,7 +6020,7 @@ class ZwaveClient extends TypedEventEmitter { const valueId = this._parseValue( zwaveNode, zwaveValue, - zwaveValueMeta + zwaveValueMeta, ) const vID = this._getValueID(valueId) @@ -6022,7 +6034,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'info', - `Value added ${valueId.id} => ${valueId.value}` + `Value added ${valueId.id} => ${valueId.value}`, ) if (!skipUpdate && updated) { @@ -6045,13 +6057,13 @@ class ZwaveClient extends TypedEventEmitter { private _parseValue( zwaveNode: ZWaveNode, zwaveValue: TranslatedValueID & { [x: string]: any }, - zwaveValueMeta: ValueMetadata + zwaveValueMeta: ValueMetadata, ) { const node = this._nodes.get(zwaveNode.id) const valueId = this._updateValueMetadata( zwaveNode, zwaveValue, - zwaveValueMeta + zwaveValueMeta, ) const vID = this._getValueID(valueId) @@ -6077,7 +6089,7 @@ class ZwaveClient extends TypedEventEmitter { valueId.isCurrentValue = true const targetValue = this._findTargetValue( valueId, - zwaveNode.getDefinedValueIDs() + zwaveNode.getDefinedValueIDs(), ) if (targetValue) { valueId.targetValue = this._getValueID(targetValue) @@ -6095,7 +6107,7 @@ class ZwaveClient extends TypedEventEmitter { */ private _updateValue( zwaveNode: ZWaveNode, - args: TranslatedValueID & { [x: string]: any } + args: TranslatedValueID & { [x: string]: any }, ) { const node = this._nodes.get(zwaveNode.id) @@ -6173,7 +6185,7 @@ class ZwaveClient extends TypedEventEmitter { */ private _removeValue( zwaveNode: ZWaveNode, - args: ZWaveNodeValueRemovedArgs + args: ZWaveNodeValueRemovedArgs, ) { const node = this._nodes.get(zwaveNode.id) const vID = this._getValueID(args) @@ -6187,7 +6199,7 @@ class ZwaveClient extends TypedEventEmitter { this.logNode( zwaveNode, 'warn', - `ValueId ${vID} removed: no such node` + `ValueId ${vID} removed: no such node`, ) } } @@ -6226,19 +6238,19 @@ class ZwaveClient extends TypedEventEmitter { */ private _findTargetValue( zwaveValue: TranslatedValueID, - definedValueIds: TranslatedValueID[] + definedValueIds: TranslatedValueID[], ) { return definedValueIds.find( (v) => v.commandClass === zwaveValue.commandClass && v.endpoint === zwaveValue.endpoint && v.propertyKey === zwaveValue.propertyKey && - /target/i.test(v.property.toString()) + /target/i.test(v.property.toString()), ) } private zwaveNodeToJSON( - node: ZWaveNode + node: ZWaveNode, ): Partial< ZWaveNode & Pick< @@ -6317,7 +6329,7 @@ class ZwaveClient extends TypedEventEmitter { this.updatesCheckTimeout = setTimeout( this._scheduledConfigCheck.bind(this), - waitMillis > 0 ? waitMillis : 1000 + waitMillis > 0 ? waitMillis : 1000, ) } @@ -6332,8 +6344,8 @@ class ZwaveClient extends TypedEventEmitter { logger.error( `Error while polling value ${this._getValueID( valueId, - true - )}: ${error.message}` + true, + )}: ${error.message}`, ) } @@ -6363,7 +6375,7 @@ class ZwaveClient extends TypedEventEmitter { private emulateFwUpdate( nodeId: number, totalFiles = 3, - fragmentsPerFile = 100 + fragmentsPerFile = 100, ) { const interval = setInterval(() => { const totalFilesFragments = totalFiles * fragmentsPerFile @@ -6399,7 +6411,7 @@ class ZwaveClient extends TypedEventEmitter { status: FirmwareUpdateStatus.OK_NoRestart, success: true, waitTime: 1000, - } + }, ) } @@ -6421,7 +6433,7 @@ class ZwaveClient extends TypedEventEmitter { (100 * (fragmentsPerFile * (progress.currentFile - 1) + progress.sentFragments)) / - totalFilesFragments + totalFilesFragments, ) if (this.nodes.get(nodeId)?.isControllerNode) { @@ -6446,7 +6458,7 @@ class ZwaveClient extends TypedEventEmitter { }) this._onNodeFirmwareUpdateProgress( this.driver.controller.nodes.get(nodeId), - progress + progress, ) } }, 1000) diff --git a/lib/jsonStore.ts b/lib/jsonStore.ts index 7e16d00a297..92100a55122 100644 --- a/lib/jsonStore.ts +++ b/lib/jsonStore.ts @@ -45,7 +45,7 @@ export class StorageHelper { await mkdirp(storeBackupsDir) const fileStream = createWriteStream( - utils.joinPath(storeBackupsDir, backupFile) + utils.joinPath(storeBackupsDir, backupFile), ) return new Promise((resolve, reject) => { diff --git a/lib/logger.ts b/lib/logger.ts index 22fa5dd67f2..ce2a158f022 100644 --- a/lib/logger.ts +++ b/lib/logger.ts @@ -45,7 +45,7 @@ interface LoggerConfig { */ export function sanitizedConfig( module: string, - config: DeepPartial | undefined + config: DeepPartial | undefined, ): LoggerConfig { config = config || ({} as LoggerConfig) const filePath = joinPath(logsDir, config.logFileName || defaultLogFile) @@ -64,7 +64,7 @@ export function sanitizedConfig( */ export function customFormat( config: LoggerConfig, - noColor = false + noColor = false, ): winston.Logform.Format { noColor = noColor || disableColors const formats: winston.Logform.Format[] = [ @@ -91,7 +91,7 @@ export function customFormat( return `${info.timestamp} ${info.level} ${info.label}: ${ info.message }${info.stack ? '\n' + info.stack : ''}` - }) + }), ) return combine(...formats) @@ -108,7 +108,7 @@ export function customTransports(config: LoggerConfig): winston.transport[] { format: customFormat(config), level: config.level, stderrLevels: ['error'], - }) + }), ) } @@ -148,7 +148,7 @@ export function customTransports(config: LoggerConfig): winston.transport[] { export function setupLogger( container: winston.Container, module: string, - config?: DeepPartial + config?: DeepPartial, ): ModuleLogger { const sanitized = sanitizedConfig(module, config) // Winston automatically reuses an existing module logger diff --git a/lib/utils.ts b/lib/utils.ts index 885ff1b52d4..e6dace95ab7 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -35,7 +35,7 @@ export type Constructor = new (...args: any[]) => T export function applyMixin( target: Constructor, mixin: Constructor, - includeConstructor = false + includeConstructor = false, ): void { // Figure out the inheritance chain of the mixin const inheritanceChain: Constructor[] = [mixin] @@ -57,7 +57,7 @@ export function applyMixin( target.prototype, prop, Object.getOwnPropertyDescriptor(ctor.prototype, prop) ?? - Object.create(null) + Object.create(null), ) } } @@ -182,7 +182,7 @@ export function getVersion(): string { */ export function sanitizeTopic( str: string | number, - sanitizeSlash = false + sanitizeSlash = false, ): string { if (typeof str === 'number' || !str) return str.toString() @@ -243,7 +243,7 @@ export async function hashPsw(password: crypto.BinaryLike): Promise { export async function verifyPsw( password: crypto.BinaryLike, - hash: string + hash: string, ): Promise { return new Promise((resolve, reject) => { const [salt, key] = hash.split(':') @@ -280,8 +280,8 @@ export function allSettled(promises: Promise[]): Promise { const wrappedPromises = promises.map((p) => Promise.resolve(p).then( (val) => ({ status: 'fulfilled', value: val }), - (err) => ({ status: 'rejected', reason: err }) - ) + (err) => ({ status: 'rejected', reason: err }), + ), ) return Promise.all(wrappedPromises) } diff --git a/package.json b/package.json index 1a69bf80d90..d0797926145 100644 --- a/package.json +++ b/package.json @@ -91,120 +91,120 @@ } }, "optionalDependencies": { - "@release-it/conventional-changelog": "^5.1.1", - "@types/node": "^18.15.3", - "c8": "^7.13.0", - "chai": "^4.3.7", + "@release-it/conventional-changelog": "^7.0.2", + "@types/node": "^20.8.6", + "c8": "^8.0.1", + "chai": "^4.3.10", "chai-as-promised": "^7.1.1", - "conventional-changelog-cli": "^2.2.2", - "docsify": "^4.13.0", + "conventional-changelog-cli": "^4.1.0", + "docsify": "^4.13.1", "docsify-cli": "^4.4.4", - "eslint": "^8.36.0", + "eslint": "^8.51.0", "eslint-plugin-babel": "^5.3.1", - "eslint-plugin-import": "^2.27.5", + "eslint-plugin-import": "^2.28.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^6.1.1", - "eslint-plugin-vue": "^9.9.0", + "eslint-plugin-vue": "^9.17.0", "mocha": "^10.2.0", "npm-run-all": "^4.1.5", - "pkg": "^5.8.1", "proxyquire": "^2.1.3", - "release-it": "^15.9.0", - "sinon": "^15.0.2", + "release-it": "^16.2.1", + "sinon": "^16.1.0", "sinon-chai": "^3.7.0" }, "dependencies": { "@jamescoyle/vue-icon": "^0.1.2", "@kvaster/zwavejs-prom": "^0.0.2", - "@mdi/js": "7.2.96", - "@zwave-js/server": "^1.32.1", + "@mdi/js": "7.3.67", + "@zwave-js/server": "^1.32.2", "@zwave-js/winston-daily-rotate-file": "^4.5.6-1", - "ansi_up": "^5.1.0", + "ansi_up": "^6.0.2", "app-root-path": "^3.1.0", - "archiver": "^5.3.1", - "axios": "^0.27.2", + "archiver": "^6.0.1", + "axios": "^1.5.1", "axios-progress-bar": "^1.2.0", "connect-history-api-fallback": "2.0.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", - "croner": "^6.0.2", - "cronstrue": "^2.23.0", + "croner": "^7.0.3", + "cronstrue": "^2.32.0", "csurf": "^1.11.0", - "dotenv": "^16.0.3", + "dotenv": "^16.3.1", "express": "^4.18.2", - "express-rate-limit": "^6.11.0", + "express-rate-limit": "^7.1.1", "express-session": "^1.17.3", "extract-zip": "^2.0.1", - "fs-extra": "^11.1.0", + "fs-extra": "^11.1.1", "js-logger": "^1.6.1", "jsonfile": "^6.1.0", - "jsonwebtoken": "^9.0.0", + "jsonwebtoken": "^9.0.2", "markdown-it": "^13.0.2", "merge": "^2.1.1", "morgan": "~1.10.0", - "mqtt": "^5.0.5", + "mqtt": "^5.1.2", "mqtt-jsonl-store": "^0.2.0", "multer": "^1.4.5-lts.1", "native-url": "^0.3.4", - "pinia": "^2.0.33", + "pinia": "^2.1.7", "prismjs": "^1.29.0", "qr-scanner": "^1.4.2", "selfsigned": "^2.1.1", "session-file-store": "^1.5.0", - "socket.io": "^4.6.1", - "socket.io-client": "^4.6.1", - "uplot": "^1.6.24", + "socket.io": "^4.7.2", + "socket.io-client": "^4.7.2", + "uplot": "^1.6.26", "v-snackbars": "^3.2.8", - "vis-data": "^7.1.6", - "vis-network": "^9.1.6", + "vis-data": "^7.1.7", + "vis-network": "^9.1.8", "vue": "^2.7.14", "vue-prism-editor": "^1.3.0", "vue-router": "^3.6.5", "vuedraggable": "^2.24.3", - "vuetify": "^2.6.14", - "winston": "^3.8.2", + "vuetify": "^2.7.1", + "winston": "^3.11.0", "zwave-js": "^12.2.0" }, "devDependencies": { - "@actions/github": "^5.1.1", + "@actions/github": "^6.0.0", "@babel/register": "^7.22.15", - "@tsconfig/node18": "^18.2.1", - "@types/app-root-path": "^1.2.4", - "@types/archiver": "^5.3.2", - "@types/chai": "^4.3.4", - "@types/chai-as-promised": "^7.1.5", - "@types/connect-history-api-fallback": "^1.3.5", - "@types/csurf": "^1.11.2", - "@types/express": "^4.17.17", + "@tsconfig/node18": "^18.2.2", + "@types/app-root-path": "^1.2.7", + "@types/archiver": "^5.3.4", + "@types/chai": "^4.3.9", + "@types/chai-as-promised": "^7.1.7", + "@types/connect-history-api-fallback": "^1.5.2", + "@types/csurf": "^1.11.4", + "@types/express": "^4.17.20", "@types/express-rate-limit": "^5.1.3", - "@types/express-session": "1.17.7", + "@types/express-session": "1.17.9", "@types/extract-zip": "^2.0.1", - "@types/fs-extra": "^11.0.1", - "@types/jsonfile": "^6.1.1", - "@types/jsonwebtoken": "^9.0.1", - "@types/mocha": "^10.0.1", - "@types/morgan": "^1.9.4", - "@types/multer": "^1.4.7", - "@types/proxyquire": "^1.3.28", - "@types/sinon-chai": "^3.2.9", - "@typescript-eslint/eslint-plugin": "^5.55.0", - "@typescript-eslint/parser": "^5.55.0", + "@types/fs-extra": "^11.0.2", + "@types/jsonfile": "^6.1.2", + "@types/jsonwebtoken": "^9.0.4", + "@types/mocha": "^10.0.2", + "@types/morgan": "^1.9.6", + "@types/multer": "^1.4.8", + "@types/proxyquire": "^1.3.29", + "@types/sinon-chai": "^3.2.10", + "@typescript-eslint/eslint-plugin": "^6.8.0", + "@typescript-eslint/parser": "^6.8.0", "@vitejs/plugin-vue2": "^2.2.0", - "esbuild-register": "^3.4.2", - "eslint-config-prettier": "^8.7.0", - "eslint-plugin-prettier": "^4.2.1", - "markdownlint-cli": "^0.33.0", + "@yao-pkg/pkg": "^5.9.2", + "esbuild-register": "^3.5.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-prettier": "^5.0.1", + "markdownlint-cli": "^0.37.0", "material-design-icons-iconfont": "^6.7.0", "nodemon": "^3.0.1", - "prettier": "^2.8.5", - "rimraf": "^4.4.0", - "sass": "1.54.5", - "semver": "^7.3.8", - "ts-morph": "^17.0.1", + "prettier": "^3.0.3", + "rimraf": "^5.0.5", + "sass": "1.69.4", + "semver": "^7.5.4", + "ts-morph": "^20.0.0", "ts-node": "^10.9.1", - "typescript": "^5.0.2", - "vite": "^4.4.9", - "vite-plugin-pwa": "^0.16.4", + "typescript": "^5.2.2", + "vite": "^4.4.11", + "vite-plugin-pwa": "^0.16.5", "vue-template-compiler": "^2.7.14" }, "engines": { diff --git a/src/App.vue b/src/App.vue index 7f5e4070f1c..4533bfd492b 100644 --- a/src/App.vue +++ b/src/App.vue @@ -451,7 +451,7 @@ export default { id: node.id, firmwareUpdateResult: false, }, - true + true, ) this.loaderText = `check_circle

Node ${node.id} added with security "${node.security || 'None'} ${ - result.lowSecurityReason - ? ` (${getEnumMemberName( - SecurityBootstrapFailure, - result.lowSecurityReason - )})` - : '' - }" + result.lowSecurityReason + ? ` (${getEnumMemberName( + SecurityBootstrapFailure, + result.lowSecurityReason, + )})` + : '' + }"

`, 'info', @@ -601,7 +601,7 @@ export default { width: 500, confirmText: 'Close', cancelText: '', - } + }, ) } }, @@ -642,13 +642,13 @@ export default { apiRequest( apiName, args = [], - options = { infoSnack: true, errorSnack: true } + options = { infoSnack: true, errorSnack: true }, ) { return new Promise((resolve) => { if (this.socket.connected) { log.debug( `Sending API request: ${apiName} with args:`, - args + args, ) if (options.infoSnack) { this.showSnackbar(`API ${apiName} called`, 'info') @@ -662,12 +662,12 @@ export default { if (!response.success) { log.error( `Error while calling ${apiName}:`, - response + response, ) if (options.errorSnack) { this.showSnackbar( `Error while calling ${apiName}: ${response.message}`, - 'error' + 'error', ) } } @@ -676,7 +676,7 @@ export default { } else { log.debug( `Socket disconnected, queueing API request: ${apiName} with args:`, - args + args, ) socketQueue.push({ apiName, @@ -709,7 +709,7 @@ export default { width: 500, cancelText: 'Close', confirmText: newVersion ? 'Install' : 'Check', - } + }, ) if (result) { @@ -717,29 +717,29 @@ export default { newVersion ? 'installConfigUpdate' : 'checkForConfigUpdates', - [] + [], ) this.showSnackbar( - newVersion ? 'Installation started' : 'Check requested' + newVersion ? 'Installation started' : 'Check requested', ) } }, changeThemeColor: function () { const metaThemeColor = document.querySelector( - 'meta[name=theme-color]' + 'meta[name=theme-color]', ) const metaThemeColor2 = document.querySelector( - 'meta[name=msapplication-TileColor]' + 'meta[name=msapplication-TileColor]', ) metaThemeColor.setAttribute( 'content', - this.darkMode ? '#000' : '#fff' + this.darkMode ? '#000' : '#fff', ) metaThemeColor2.setAttribute( 'content', - this.darkMode ? '#000' : '#fff' + this.darkMode ? '#000' : '#fff', ) }, importFile: function (ext) { @@ -773,7 +773,7 @@ export default { } catch (e) { self.showSnackbar( 'Error while parsing input file, check console for more info', - 'error' + 'error', ) console.error(e) err = e @@ -785,7 +785,7 @@ export default { } else { resolve({ data, file }) } - } + }, ) if (ext === 'buffer') { @@ -831,7 +831,7 @@ export default { if (!data.success) { this.showSnackbar( 'Error while retrieving configuration, check console', - 'error' + 'error', ) } else { this.init(data) @@ -849,7 +849,7 @@ export default { noCancel: true, confirmText: 'Got it', persistent: true, - } + }, ) } @@ -877,7 +877,7 @@ export default { cancelText: 'No 😢', confirmText: 'Ok 😍', persistent: true, - } + }, ) const data = await ConfigApis.updateStats(result) @@ -886,7 +886,7 @@ export default { this.showSnackbar( `Statistics are ${ data.enabled ? 'enabled' : 'disabled' - }` + }`, ) } else { throw Error(data.message) @@ -940,7 +940,7 @@ export default { this.socket.emit( socketActions.init, true, - this.onInit.bind(this) + this.onInit.bind(this), ) if (socketQueue.length > 0) { @@ -948,7 +948,7 @@ export default { this.apiRequest( item.apiName, item.args, - item.options + item.options, ).then(item.resolve) }) socketQueue = [] @@ -989,7 +989,7 @@ export default { this.socket.on(socketEvents.connected, this.setAppInfo.bind(this)) this.socket.on( socketEvents.controller, - this.setControllerStatus.bind(this) + this.setControllerStatus.bind(this), ) this.socket.on(socketEvents.nodeUpdated, this.updateNode.bind(this)) @@ -998,28 +998,28 @@ export default { this.socket.on( socketEvents.valueRemoved, - this.removeValue.bind(this) + this.removeValue.bind(this), ) this.socket.on( socketEvents.valueUpdated, - this.updateValue.bind(this) + this.updateValue.bind(this), ) this.socket.on( socketEvents.metadataUpdated, - this.setValue.bind(this) + this.setValue.bind(this), ) this.socket.on( socketEvents.statistics, - this.setStatistics.bind(this) + this.setStatistics.bind(this), ) this.socket.on(socketEvents.nodeEvent, this.addNodeEvent.bind(this)) this.socket.on( socketEvents.grantSecurityClasses, - this.onGrantSecurityClasses.bind(this) + this.onGrantSecurityClasses.bind(this), ) // don't await this, will cause a loop of calls this.getConfig() @@ -1054,7 +1054,7 @@ export default { const data = await ConfigApis.isAuthEnabled() if (!data.success) { throw Error( - data.message || 'Error while checking authorizations' + data.message || 'Error while checking authorizations', ) } else { const newAuth = data.data === true @@ -1068,7 +1068,7 @@ export default { if (!newAuth && this.$route.path === Routes.login) { this.$router.push( - localStorage.getItem('nextUrl') || Routes.main + localStorage.getItem('nextUrl') || Routes.main, ) localStorage.removeItem('nextUrl') } @@ -1084,7 +1084,7 @@ export default { const response = await fetch( `https://api.github.com/repos/zwave-js/${project}/releases/${ version === 'latest' ? 'latest' : 'tags/' + version - }` + }`, ) const data = await response.json() return data @@ -1097,7 +1097,7 @@ export default { try { const response = await fetch( - `https://api.github.com/repos/zwave-js/${project}/releases` + `https://api.github.com/repos/zwave-js/${project}/releases`, ) const data = await response.json() @@ -1149,7 +1149,7 @@ export default { this.showSnackbar( `New version available: ${latest.tag_name}`, 'info', - 15000 + 15000, ) } @@ -1167,15 +1167,15 @@ export default { new RegExp( `#+ \\[${release.tag_name.replace( 'v', - '' + '', )}\\]\\([^\\)]+\\)`, - 'g' + 'g', ), `${i === 0 ? '# UI\n---\n' : ''}## [${ release.tag_name }](https://github.com/zwave-js/zwave-js-ui/releases/tag/${ release.tag_name - })` + })`, ) let changelog = md() @@ -1185,12 +1185,12 @@ export default { if (i === 0) { changelog = changelog.replace( '

', - '

' + '

', ) } return changelog - } + }, ) let changelog = appChangelogs.join('
') @@ -1205,7 +1205,7 @@ export default { .render(release.body) .replace( /#(\d+)/g, - '#$1' + '#$1', ) return `${ @@ -1217,7 +1217,7 @@ export default { }">${ release.tag_name }


${changelog}
` - } + }, ) changelog += driverChangelogs.join('') @@ -1233,11 +1233,11 @@ export default { .render(release.body) .replace( "

What's Changed

", - '

Changes

' + '

Changes

', ) .replace( /#(\d+)/g, - '#$1' + '#$1', ) return `${ @@ -1249,7 +1249,7 @@ export default { }">v${ release.tag_name }
${changelog}
` - } + }, ) changelog += serverChangelogs.join('') @@ -1273,7 +1273,7 @@ export default { hint: 'Enable this to never show changelogs on next updates', }, ], - } + }, ) await ConfigApis.updateVersions(result?.dontShowAgain) diff --git a/src/apis/ConfigApis.js b/src/apis/ConfigApis.js index d5f17dadc00..c9ad4d7d313 100644 --- a/src/apis/ConfigApis.js +++ b/src/apis/ConfigApis.js @@ -100,7 +100,7 @@ export default { { content, }, - { params: query } + { params: query }, ) return response.data }, diff --git a/src/components/Confirm.vue b/src/components/Confirm.vue index 5eb2a84396f..93694985036 100644 --- a/src/components/Confirm.vue +++ b/src/components/Confirm.vue @@ -326,7 +326,7 @@ export default { this.$set( this.values, input.key, - values[input.key] ?? input.default + values[input.key] ?? input.default, ) } @@ -342,7 +342,7 @@ export default { if (input.rules) { this.inputProps[input.key].rules = input.rules.map( - (r) => wrapFunc(r, this.values) + (r) => wrapFunc(r, this.values), ) } else { this.inputProps[input.key].rules = [] diff --git a/src/components/ValueId.vue b/src/components/ValueId.vue index e3b5c017cc3..a2c559974af 100644 --- a/src/components/ValueId.vue +++ b/src/components/ValueId.vue @@ -435,7 +435,7 @@ export default { this.value.newValue !== undefined ) { return this.itemText( - this.selectedItem || this.value.newValue + this.selectedItem || this.value.newValue, ) } else if (this.value === null) { return '(unknown)' @@ -502,13 +502,13 @@ export default { { infoSnack: false, errorSnack: true, - } + }, ) if (response.success) { useBaseStore().showSnackbar( 'Notification manually idled', - 'success' + 'success', ) } }, diff --git a/src/components/custom/BgRssiChart.vue b/src/components/custom/BgRssiChart.vue index b4afda9e91f..43daccf8e86 100644 --- a/src/components/custom/BgRssiChart.vue +++ b/src/components/custom/BgRssiChart.vue @@ -172,15 +172,15 @@ export default { this.node.bgRSSIPoints.forEach((point) => { timestamps.push(point.timestamp / 1000) channel0[0].push( - this.checkRssiError(point.channel0.current) + this.checkRssiError(point.channel0.current), ) channel0[1].push(point.channel0.average) channel1[0].push( - this.checkRssiError(point.channel1.current) + this.checkRssiError(point.channel1.current), ) channel1[1].push(point.channel1.average) channel2[0].push( - this.checkRssiError(point.channel2?.current) + this.checkRssiError(point.channel2?.current), ) channel2[1].push(point.channel2?.average) }) @@ -318,7 +318,7 @@ export default { stroke: '#7a5195', fill: 'rgba(122, 81, 149, 0.35)', }, - 3 + 3, ), ...this.createSerie( { @@ -326,7 +326,7 @@ export default { stroke: '#bc5090', fill: 'rgba(188, 80, 144, 0.35)', }, - 2 + 2, ), ...this.createSerie( { @@ -334,7 +334,7 @@ export default { stroke: '#ffa600', fill: 'rgba(255, 166, 0, 0.35)', }, - 1 + 1, ), ], } diff --git a/src/components/custom/ListInput.vue b/src/components/custom/ListInput.vue index 5c40abcc210..b2b012ea748 100644 --- a/src/components/custom/ListInput.vue +++ b/src/components/custom/ListInput.vue @@ -160,7 +160,7 @@ export default { this.items.push(this.item) this.inputItems.splice( this.inputItems.indexOf(this.getItem(this.item)), - 1 + 1, ) await this.$nextTick() this.item = null diff --git a/src/components/custom/NodePanel.vue b/src/components/custom/NodePanel.vue index 3cb1fa3f40e..d511ee31a1d 100644 --- a/src/components/custom/NodePanel.vue +++ b/src/components/custom/NodePanel.vue @@ -218,7 +218,7 @@ {{ zwaveDataRateToString( - r.routeSpeed + r.routeSpeed, ) }} @@ -515,7 +515,7 @@ export default { repRSSI[i] && !isRssiError(repRSSI[i]) ? ` (${rssiToString(repRSSI[i])})` : '' - }` + }`, ) .join(', ') : 'None, direct connection' @@ -571,7 +571,7 @@ export default { const newwindow = window.open( Routes.controllerChart + '#no-topbar', 'BG-RSSI-Chart', - 'height=800,width=1200,status=no,toolbar:no,scrollbars:no,menubar:no' // check https://www.w3schools.com/jsref/met_win_open.asp for all available specs + 'height=800,width=1200,status=no,toolbar:no,scrollbars:no,menubar:no', // check https://www.w3schools.com/jsref/met_win_open.asp for all available specs ) if (window.focus) { newwindow.focus() @@ -601,7 +601,7 @@ export default { await this.app.confirm( 'Delete', 'Are you sure you want to delete this route?', - 'alert' + 'alert', ) ) { const response = await this.app.apiRequest(api, [this.node.id]) @@ -612,7 +612,7 @@ export default { } else { this.showSnackbar( `Failed delete route for node "${this.node._name}"`, - 'error' + 'error', ) } } @@ -622,7 +622,7 @@ export default { this.discoverLoading = true const response = await this.app.apiRequest( 'discoverNodeNeighbors', - [this.node.id] + [this.node.id], ) this.discoverLoading = false @@ -633,7 +633,7 @@ export default { } else { this.showSnackbar( `Failed to discover neighbors of node "${this.node._name}"`, - 'error' + 'error', ) } } @@ -686,7 +686,7 @@ export default { (n) => !n.isControllerNode && n.isListening && - n.id !== this.node.id + n.id !== this.node.id, ), }, { @@ -736,7 +736,7 @@ export default { const res = await this.promptRoute( `Node "${this.node._name}"`, 'Controller', - true + true, ) if (!res) return @@ -747,7 +747,7 @@ export default { if (isPriority) { const existingPriorityRoute = this.returnRoutes.find( - (r) => r.isPriority + (r) => r.isPriority, ) const newRoute = { @@ -761,7 +761,7 @@ export default { const res = await this.app.confirm( 'Priority route', 'You already have a priority route set. Do you want to replace it?', - 'info' + 'info', ) if (!res) return @@ -769,7 +769,7 @@ export default { this.returnRoutes.splice( this.returnRoutes.indexOf(existingPriorityRoute), 1, - newRoute + newRoute, ) } else { if (newRoute.isPriority) { @@ -873,11 +873,11 @@ export default { if (response.result) { this.showSnackbar( `New route set for node "${this.node._name}"`, - 'success' + 'success', ) } else { this.showSnackbar( - `Failed to set route for node "${this.node._name}"` + `Failed to set route for node "${this.node._name}"`, ) } } diff --git a/src/components/custom/QrReader.vue b/src/components/custom/QrReader.vue index fdb62634668..9417a0d1b6b 100644 --- a/src/components/custom/QrReader.vue +++ b/src/components/custom/QrReader.vue @@ -240,7 +240,7 @@ export default { return this.smallQrCodeRegion(v) } : null, - } + }, ) await this.qrReader.start() @@ -280,11 +280,11 @@ export default { onScanSuccess(result) { log.log( 'QR-Code scanned: ', - typeof result === 'string' ? result : result.data + typeof result === 'string' ? result : result.data, ) this.$emit( 'result', - typeof result === 'string' ? result : result.data + typeof result === 'string' ? result : result.data, ) }, onDrop(e) { diff --git a/src/components/custom/StatisticsCard.vue b/src/components/custom/StatisticsCard.vue index 6033f4a366c..91ef4569557 100644 --- a/src/components/custom/StatisticsCard.vue +++ b/src/components/custom/StatisticsCard.vue @@ -75,7 +75,7 @@ export default { commandsRX: 0, commandsDroppedTX: 0, commandsDroppedRX: 0, - } + }, ) }, stats() { @@ -102,12 +102,12 @@ export default { ...this.createStat( 'timeoutResponse', 'Timeout Response', - 'red' + 'red', ), ...this.createStat( 'timeoutCallback', 'Timeout Callback', - 'red' + 'red', ), }, cols: 6, @@ -121,12 +121,12 @@ export default { ...this.createStat( 'commandsDroppedTX', 'Dropped TX', - 'red' + 'red', ), ...this.createStat( 'commandsDroppedRX', 'Dropped RX', - 'red' + 'red', ), }, cols: 3, @@ -143,12 +143,12 @@ export default { ...this.createStat( 'messagesDroppedTX', 'Dropped TX', - 'red' + 'red', ), ...this.createStat( 'messagesDroppedRX', 'Dropped RX', - 'red' + 'red', ), }, cols: 3, diff --git a/src/components/custom/ZwaveGraph.vue b/src/components/custom/ZwaveGraph.vue index 7565c97674a..1add0ff80b3 100644 --- a/src/components/custom/ZwaveGraph.vue +++ b/src/components/custom/ZwaveGraph.vue @@ -465,7 +465,7 @@ export default { color: '#3F51B5', textColor: '#3F51B5', text: protocolDataRateToString( - ProtocolDataRate.LongRange_100k + ProtocolDataRate.LongRange_100k, ), }, { @@ -555,7 +555,7 @@ export default { this.updateTimeout = setTimeout( this.onNodeUpdate.bind(this, args[0]), - 1000 + 1000, ) } else { this.shouldReload = true @@ -660,7 +660,7 @@ export default { (prev, curr) => prev.protocolDataRate > curr.protocolDataRate ? prev - : curr + : curr, ) } } @@ -1177,7 +1177,7 @@ export default { hubNode, entity, node.applicationRoute, - RouteKind.Application + RouteKind.Application, ) // parse node LWR (last working route) https://zwave-js.github.io/node-zwave-js/#/api/node?id=quotstatistics-updatedquot @@ -1186,7 +1186,7 @@ export default { hubNode, entity, node.statistics?.lwr, - RouteKind.LWR + RouteKind.LWR, ) // parse node NLWR (next last working route) @@ -1195,7 +1195,7 @@ export default { hubNode, entity, node.statistics?.nlwr, - RouteKind.NLWR + RouteKind.NLWR, ) if (node.customSUCReturnRoutes) { @@ -1205,7 +1205,7 @@ export default { hubNode, entity, r, - ReturnRouteKind.CUSTOM + ReturnRouteKind.CUSTOM, ) } } @@ -1216,7 +1216,7 @@ export default { hubNode, entity, node.prioritySUCReturnRoute, - ReturnRouteKind.PRIORITY + ReturnRouteKind.PRIORITY, ) } } diff --git a/src/components/dialogs/DialogAssociation.vue b/src/components/dialogs/DialogAssociation.vue index 98895af6795..6ee64458dd6 100644 --- a/src/components/dialogs/DialogAssociation.vue +++ b/src/components/dialogs/DialogAssociation.vue @@ -46,7 +46,7 @@ item.endpoint >= 0 ? getEndpointLabel( node, - item.endpoint + item.endpoint, ) : 'No Endpoint' }} @@ -149,7 +149,7 @@ export default { ? this.associations.filter( (a) => a.groupId === this.group.group.value && - a.endpoint === this.group.endpoint + a.endpoint === this.group.endpoint, ).length : 0 }, @@ -163,7 +163,7 @@ export default { g.endpoint === endpoint || (endpoint === null && g.endpoint === 0 && - !g.multiChannel) + !g.multiChannel), ) // eslint-disable-next-line no-empty } catch (error) {} diff --git a/src/components/dialogs/DialogGatewayValue.vue b/src/components/dialogs/DialogGatewayValue.vue index adc171181e4..f44c8e1ffe6 100644 --- a/src/components/dialogs/DialogGatewayValue.vue +++ b/src/components/dialogs/DialogGatewayValue.vue @@ -271,7 +271,7 @@ export default { ...mapState(useBaseStore, ['gateway', 'mqtt']), deviceValues() { const device = this.devices.find( - (d) => d.value == this.editedValue.device + (d) => d.value == this.editedValue.device, ) // eslint-disable-line eqeqeq return device ? device.values : [] }, diff --git a/src/components/dialogs/DialogHealthCheck.vue b/src/components/dialogs/DialogHealthCheck.vue index 5f8db306d70..36986f31c48 100644 --- a/src/components/dialogs/DialogHealthCheck.vue +++ b/src/components/dialogs/DialogHealthCheck.vue @@ -294,7 +294,7 @@ {{ item.failedPingsNode }}/10{{ item.failedPingsController }}/10{{ item.failedPingsToSource }}/10{{ item.failedPingsToTarget }}/10{{ @@ -376,7 +376,7 @@ {{ @@ -560,7 +560,7 @@ export default { this.app.exportConfiguration( this.results, `healthCheck_${this.activeNode.id}-${this.resultsTargetNode}`, - 'json' + 'json', ) }, getNeighborsColor(value) { @@ -627,14 +627,14 @@ export default { this.rounds = 5 this.activeNode = copy(this.node) this.targetNode = this.filteredNodes.find( - (n) => n.isControllerNode + (n) => n.isControllerNode, ) this.selectedNode = this.filteredNodes[0] ? this.filteredNodes[0].id : null this.bindEvent( 'healthCheckProgress', - this.onHealthCheckProgress.bind(this) + this.onHealthCheckProgress.bind(this), ) } else if (open === false) { this.unbindEvents() @@ -706,7 +706,7 @@ export default { { infoSnack: true, errorSnack: false, - } + }, ) this.loading = false @@ -718,7 +718,7 @@ export default { this.averages = res this.averages.numNeighbors = Math.max( - ...this.results.map((n) => n.numNeighbors) + ...this.results.map((n) => n.numNeighbors), ) this.resultsTargetNode = res.targetNodeId @@ -726,7 +726,7 @@ export default { this.results.pop() this.showSnackbar( response.message || 'Health check failed', - 'error' + 'error', ) } }, diff --git a/src/components/dialogs/DialogNodesManager.vue b/src/components/dialogs/DialogNodesManager.vue index a9801351d7c..1b523fcdc9e 100644 --- a/src/components/dialogs/DialogNodesManager.vue +++ b/src/components/dialogs/DialogNodesManager.vue @@ -140,7 +140,7 @@ v-model="s.values.replaceId" :items=" nodes.filter( - (n) => !n.isControllerNode + (n) => !n.isControllerNode, ) " return-object @@ -857,7 +857,7 @@ export default { // inclusion/exclusion started, start the countdown timer if (status.indexOf('started') > 0) { this.commandEndDate = new Date( - new Date().getTime() + this.timeoutMs + new Date().getTime() + this.timeoutMs, ) this.nodeFound = null this.state = 'start' @@ -879,7 +879,7 @@ export default { // fixes issue #2746 this.waitTimeout = setTimeout( () => this.showResults(), - timeout + timeout, ) // add additional discovery time } } else { @@ -938,7 +938,7 @@ export default { // for some reason using @keydown.enter on buttons isn't working // this trick is used to dispatch the enter event to the button const button = this.$refs.content[0].$el.querySelector( - '.next-btn:not([disabled])' + '.next-btn:not([disabled])', ) if (button) { @@ -976,7 +976,7 @@ export default { const mode = 4 // s2 only const replaceStep = this.steps.find( - (s) => s.key === 'replaceFailed' + (s) => s.key === 'replaceFailed', ) let replaceId @@ -1027,7 +1027,7 @@ export default { if (!replaceStep) { const response = await this.app.apiRequest( 'provisionSmartStartNode', - [provisioning] + [provisioning], ) if (response.success) { @@ -1133,7 +1133,7 @@ export default { tryParseDsk: true, canceltext: 'Close', width: 500, - } + }, ) if (!qrString) { return @@ -1144,7 +1144,7 @@ export default { if (!dsk) { const response = await this.app.apiRequest( 'parseQRCodeString', - [qrString] + [qrString], ) this.onParseQrCode(response) @@ -1159,7 +1159,7 @@ export default { this.aborted = false this.loading = true const replaceStep = this.steps.find( - (s) => s.key === 'replaceFailed' + (s) => s.key === 'replaceFailed', ) if (replaceStep) { @@ -1244,7 +1244,7 @@ export default { if (bind) { this.bindEvent( 'grantSecurityClasses', - this.onGrantSecurityCC.bind(this) + this.onGrantSecurityCC.bind(this), ) this.bindEvent('validateDSK', this.onValidateDSK.bind(this)) this.bindEvent('nodeRemoved', this.onNodeRemoved.bind(this)) diff --git a/src/components/nodes-table/AssociationGroups.vue b/src/components/nodes-table/AssociationGroups.vue index 7bedf143743..5655ab57c4d 100644 --- a/src/components/nodes-table/AssociationGroups.vue +++ b/src/components/nodes-table/AssociationGroups.vue @@ -35,7 +35,7 @@ node.groups.find( (g) => g.value === item.groupId && - g.endpoint === item.endpoint + g.endpoint === item.endpoint, ).text }} @@ -142,7 +142,7 @@ export default { ? '' : ' This node is Asleep, so you should wake it up first.' }`, - 'info' + 'info', ) } const response = await this.app.apiRequest('getAssociations', [ @@ -206,7 +206,7 @@ export default { const response = await this.app.apiRequest( 'removeAssociations', - args + args, ) if (response.success) { @@ -221,7 +221,7 @@ export default { !(await this.$listeners.showConfirm( 'Attention', `Are you sure you want to remove all associations from this node? This will also remove lifeline association if it exists.`, - 'alert' + 'alert', )) ) { return @@ -229,7 +229,7 @@ export default { const response = await this.app.apiRequest( 'removeAllAssociations', - args + args, ) if (response.success) { diff --git a/src/components/nodes-table/ColumnFilter.vue b/src/components/nodes-table/ColumnFilter.vue index 4dc51b5686e..06f89f4058d 100644 --- a/src/components/nodes-table/ColumnFilter.vue +++ b/src/components/nodes-table/ColumnFilter.vue @@ -103,7 +103,7 @@ export default { Object.keys(obj).some( (k) => (!!obj[k] && !!Object.keys(obj[k]).length) || - typeof obj[k] === 'boolean' + typeof obj[k] === 'boolean', ) ) }, @@ -119,7 +119,7 @@ export default { // Emit minimal storable filter spec (with empty default values removed): this.$emit( 'change', - ColumnFilterHelper.filterSpec(this.column.type, value) + ColumnFilterHelper.filterSpec(this.column.type, value), ) } }, diff --git a/src/components/nodes-table/ColumnFilterNumber.vue b/src/components/nodes-table/ColumnFilterNumber.vue index 953cf135e19..a7e519ec561 100644 --- a/src/components/nodes-table/ColumnFilterNumber.vue +++ b/src/components/nodes-table/ColumnFilterNumber.vue @@ -61,13 +61,13 @@ export default { values: { get() { const undefinedPlaceholder = this.items.find( - (i) => typeof i === 'string' + (i) => typeof i === 'string', ) if (undefinedPlaceholder) { return ( this.value.values?.map((v) => - v === undefined ? undefinedPlaceholder : v + v === undefined ? undefinedPlaceholder : v, ) ?? [] ) } else { diff --git a/src/components/nodes-table/ExpandedNode.vue b/src/components/nodes-table/ExpandedNode.vue index 9cf76ce2f7d..f334dcf0211 100644 --- a/src/components/nodes-table/ExpandedNode.vue +++ b/src/components/nodes-table/ExpandedNode.vue @@ -610,7 +610,7 @@ export default { this.showSnackbar( 'Value update failed' + (reason ? ': ' + reason : ''), - 'error' + 'error', ) } } else { @@ -618,7 +618,7 @@ export default { `Error updating value${ response.message ? ': ' + response.message : '' }`, - 'error' + 'error', ) } } @@ -662,7 +662,7 @@ export default { 'info', { confirmText: 'Ok', - } + }, ) } @@ -677,12 +677,12 @@ export default { if (response.success) { this.showSnackbar( `Node ${this.node.id}: ${action} successfully sent `, - 'success' + 'success', ) } else { this.showSnackbar( `Error sending ${action} to node ${this.node.id}: ${response.message}`, - 'error' + 'error', ) } }) diff --git a/src/components/nodes-table/HomeAssistant.vue b/src/components/nodes-table/HomeAssistant.vue index 40c7184e9e8..51cbad61eb9 100644 --- a/src/components/nodes-table/HomeAssistant.vue +++ b/src/components/nodes-table/HomeAssistant.vue @@ -212,7 +212,7 @@ export default { if (this.node && this.node.hassDevices) { for (const id in this.node.hassDevices) { const d = JSON.parse( - JSON.stringify(this.node.hassDevices[id]) + JSON.stringify(this.node.hassDevices[id]), ) d.id = id devices.push(d) @@ -240,7 +240,7 @@ export default { if (!response.success) { this.showSnackbar( `Error while calling ${data.apiName}: ${response.message}`, - 'error' + 'error', ) } resolve(response) @@ -279,7 +279,7 @@ export default { (await this.$listeners.showConfirm( 'Attention', 'Are you sure you want to delete selected device?', - 'alert' + 'alert', )) ) { const response = await this.sendAction({ @@ -298,7 +298,7 @@ export default { this.node && (await this.$listeners.showConfirm( 'Rediscover node', - 'Are you sure you want to disable discovery of all values? In order to make this persistent remember to click on Store' + 'Are you sure you want to disable discovery of all values? In order to make this persistent remember to click on Store', )) ) { const response = await this.sendAction({ @@ -309,7 +309,7 @@ export default { if (response.success) { this.showSnackbar( `Discovery disabled for node ${this.node.id}`, - 'success' + 'success', ) } } @@ -320,7 +320,7 @@ export default { device && (await this.$listeners.showConfirm( 'Rediscover Device', - 'Are you sure you want to re-discover selected device?' + 'Are you sure you want to re-discover selected device?', )) ) { const response = await this.sendAction({ @@ -332,7 +332,7 @@ export default { if (response.success) { this.showSnackbar( `Device ${device.id} re-discovered`, - 'success' + 'success', ) } } @@ -342,7 +342,7 @@ export default { this.node && (await this.$listeners.showConfirm( 'Rediscover node', - 'Are you sure you want to re-discover all node values?' + 'Are you sure you want to re-discover all node values?', )) ) { const response = await this.sendAction({ @@ -353,7 +353,7 @@ export default { if (response.success) { this.showSnackbar( `Node ${this.node.id} re-discovered`, - 'success' + 'success', ) } } @@ -369,7 +369,7 @@ export default { if (response.success) { this.showSnackbar( `Devices stored for node ${this.node.id}`, - 'success' + 'success', ) } }, @@ -379,7 +379,7 @@ export default { this.$set( this.node.hassDevices, this.selectedDevice.id, - updated + updated, ) const response = await this.sendAction({ apiName: 'update', diff --git a/src/components/nodes-table/NodeDetails.vue b/src/components/nodes-table/NodeDetails.vue index 9ebaa272740..448dcadcaa7 100644 --- a/src/components/nodes-table/NodeDetails.vue +++ b/src/components/nodes-table/NodeDetails.vue @@ -223,7 +223,7 @@ class="mb-1" @click.stop=" refreshCCValues( - group[0].commandClass + group[0].commandClass, ) " color="primary" @@ -455,20 +455,20 @@ export default { const response = await this.app.apiRequest( 'setNodeDefaultSetValueOptions', - [this.node.id, { [defaultProp]: this.options[prop] }] + [this.node.id, { [defaultProp]: this.options[prop] }], ) if (response.success) { this.showSnackbar( `Default node ${prop} updated successffully`, - 'success' + 'success', ) } }, async updateControllerNodeProp(prop) { const response = await this.app.apiRequest( 'updateControllerNodeProps', - [null, [prop]] + [null, [prop]], ) if (response.success) { @@ -487,7 +487,7 @@ export default { await this.app.confirm( 'Attention', 'Are you sure you want to reset all configurations to default?', - 'alert' + 'alert', ) ) { const response = await this.app.apiRequest('sendCommand', [ @@ -517,7 +517,7 @@ export default { if (response.success) { this.showSnackbar( `Parameter ${this.configCC.parameter}: resetted`, - 'success' + 'success', ) } }, @@ -544,7 +544,7 @@ export default { if (response.success) { this.showSnackbar( `Parameter ${this.configCC.parameter}: ${response.result}`, - 'success' + 'success', ) } }, @@ -569,12 +569,12 @@ export default { if (isUnsupervisedOrSucceeded(response.result)) { this.showSnackbar( `Parameter ${this.configCC.parameter} set successfully`, - 'success' + 'success', ) } else { this.showSnackbar( `Parameter ${this.configCC.parameter} set failed`, - 'error' + 'error', ) } } @@ -601,7 +601,7 @@ export default { const args = [this.node.powerlevel, this.node.measured0dBm] const response = await this.app.apiRequest( 'setPowerlevel', - args + args, ) if (response.success) { diff --git a/src/components/nodes-table/NodeScheduler.vue b/src/components/nodes-table/NodeScheduler.vue index caca6c4623f..76afce379a5 100644 --- a/src/components/nodes-table/NodeScheduler.vue +++ b/src/components/nodes-table/NodeScheduler.vue @@ -210,27 +210,27 @@ export default { switch (this.mode) { case 'daily': item.weekdays = s.weekdays.map((w) => - getEnumMemberName(ScheduleEntryLockWeekday, w) + getEnumMemberName(ScheduleEntryLockWeekday, w), ) item.start = `${padNumber(s.startHour, 2)}:${padNumber( s.startMinute, - 2 + 2, )}` item.duration = `${s.durationHour}h ${s.durationMinute}m` break case 'weekly': item.weekday = getEnumMemberName( ScheduleEntryLockWeekday, - s.weekday + s.weekday, ) item.start = `${padNumber(s.startHour, 2)}:${padNumber( s.startMinute, - 2 + 2, )}` item.stop = `${padNumber(s.stopHour, 2)}:${padNumber( s.stopMinute, - 2 + 2, )}` break case 'yearly': @@ -239,7 +239,7 @@ export default { s.startMonth - 1, s.startDay, s.startHour, - s.startMinute + s.startMinute, ).toLocaleString() item.stop = new Date( @@ -247,7 +247,7 @@ export default { s.stopMonth - 1, s.stopDay, s.stopHour, - s.stopMinute + s.stopMinute, ).toLocaleString() break @@ -320,7 +320,7 @@ export default { { confirmText: 'Query', cancelText: 'Cache', - } + }, ) this.loading = true @@ -545,7 +545,7 @@ export default { inputs: this.getInputs(slot), confirmText: slot ? 'Edit' : 'Add', values, - } + }, ) if (Object.keys(res).length === 0) { diff --git a/src/components/nodes-table/OTAUpdates.vue b/src/components/nodes-table/OTAUpdates.vue index dbb24902b02..14472ae67e7 100644 --- a/src/components/nodes-table/OTAUpdates.vue +++ b/src/components/nodes-table/OTAUpdates.vue @@ -160,7 +160,7 @@ export default { computed: { filteredUpdates() { return this.fwUpdates.filter( - (u) => !u.downgrade || (u.downgrade && this.showDowngrades) + (u) => !u.downgrade || (u.downgrade && this.showDowngrades), ) }, }, @@ -179,7 +179,7 @@ export default { { includePrereleases: this.includePrereleases, }, - ] + ], ) this.loading = false @@ -188,7 +188,7 @@ export default { } else { this.showSnackbar( `Failed to check for firmware updates: ${response.message}`, - 'error' + 'error', ) } }, @@ -213,7 +213,7 @@ export default { confirmText: 'Update', cancelText: 'Cancel', width: '500px', - } + }, ) ) { this.app.apiRequest('firmwareUpdateOTA', [this.node.id, update]) diff --git a/src/components/nodes-table/SmartView.vue b/src/components/nodes-table/SmartView.vue index ff22107fd79..b8bf6ac2e5a 100644 --- a/src/components/nodes-table/SmartView.vue +++ b/src/components/nodes-table/SmartView.vue @@ -151,7 +151,7 @@ @@ -366,7 +366,7 @@ export default { ? Math.round( (node.firmwareUpdate.sentFragments / node.firmwareUpdate.totalFragments) * - 100 + 100, ) : null }, diff --git a/src/components/nodes-table/UserCodeTable.vue b/src/components/nodes-table/UserCodeTable.vue index dbc1824ca84..f7a8e8822af 100644 --- a/src/components/nodes-table/UserCodeTable.vue +++ b/src/components/nodes-table/UserCodeTable.vue @@ -58,7 +58,7 @@ Slots: {{ item.schedule.slots.filter( - (s) => s.type === item.schedule.type + (s) => s.type === item.schedule.type, ).length }} @@ -160,7 +160,7 @@ export default { if (!response.success) { this.showSnackbar( `User ID ${user.id} ${enabled ? 'enabled' : 'disabled'}`, - 'success' + 'success', ) } }, @@ -173,7 +173,7 @@ export default { allSlots.push( ...this.node.schedule[type].slots .filter((s) => s.userId === id) - .map((s) => ({ ...s, type })) + .map((s) => ({ ...s, type })), ) } @@ -195,7 +195,7 @@ export default { }, getValueId(id, prop) { return this.values.find( - (v) => v.propertyKey === id && v.property === prop + (v) => v.propertyKey === id && v.property === prop, ) }, async setUserCode(item) { diff --git a/src/components/nodes-table/nodes-table.js b/src/components/nodes-table/nodes-table.js index aa5a5386103..7ea170ef03e 100644 --- a/src/components/nodes-table/nodes-table.js +++ b/src/components/nodes-table/nodes-table.js @@ -210,7 +210,7 @@ export default { ? Math.round( (node.firmwareUpdate.sentFragments / node.firmwareUpdate.totalFragments) * - 100 + 100, ) : null }, @@ -322,7 +322,7 @@ export default { this.nodes, this.nodesProps, localStorage, - 'nodes_' + 'nodes_', ) }, } diff --git a/src/mixins/InstancesMixin.js b/src/mixins/InstancesMixin.js index c8b7b3b9a36..4f799bd20c4 100644 --- a/src/mixins/InstancesMixin.js +++ b/src/mixins/InstancesMixin.js @@ -21,7 +21,7 @@ export default { for (const event in this.bindedSocketEvents) { this.socket.off( socketEvents[event], - this.bindedSocketEvents[event] + this.bindedSocketEvents[event], ) } @@ -36,7 +36,7 @@ export default { if (response.success && response.result) { this.showSnackbar( `Ping of node ${node.id} successful`, - 'success' + 'success', ) } else { this.showSnackbar( @@ -45,7 +45,7 @@ export default { ? response.message : 'no response to ping' }`, - 'error' + 'error', ) } }, @@ -62,7 +62,7 @@ export default { 'warning', { width: 600, - } + }, ) if (!confirmed) { @@ -75,13 +75,13 @@ export default { { infoSnack: true, errorSnack: false, - } + }, ) if (response.success && response.result) { this.showSnackbar( `Routes of node ${node.id} has been rebuilt successfully`, - 'success' + 'success', ) } else { this.showSnackbar( @@ -90,7 +90,7 @@ export default { ? response.message : 'failed to rebuild node routes' }`, - 'error' + 'error', ) } }, diff --git a/src/modules/ManagedItems.js b/src/modules/ManagedItems.js index f56400eda9a..ce2b80ec252 100644 --- a/src/modules/ManagedItems.js +++ b/src/modules/ManagedItems.js @@ -55,7 +55,7 @@ export class ManagedItems { } this.tableColumns = this.tableColumns.filter( - (t) => !!this.propDefs[t.name] + (t) => !!this.propDefs[t.name], ) } @@ -141,7 +141,7 @@ export class ManagedItems { return ColumnFilterHelper.filterByFilterSpec( new NodeCollection(this.items, this.propDefs), this.allTableHeaders, - this.filters + this.filters, ).nodes // TODO: nodes should be items } @@ -299,7 +299,7 @@ export class ManagedItems { // when undeginedPlaceholder is set, we need to replace the filter value with undefined if (undefinedPlaceholder && filterDef?.values) { filterDef.values = filterDef.values.map((f) => - f === undefinedPlaceholder ? undefined : f + f === undefinedPlaceholder ? undefined : f, ) } @@ -419,7 +419,7 @@ export class ManagedItems { ) { formattedGroup = this.propDefs[this.groupBy[0]].customGroupValue( group, - this.groupBy + this.groupBy, ) } return this.groupByTitle + ': ' + formattedGroup @@ -450,7 +450,7 @@ export class ManagedItems { sortBy, sortDesc, a, - b + b, ) } else { // Standard sort for every other column diff --git a/src/modules/ManagedItems.test.js b/src/modules/ManagedItems.test.js index cf7e5e2b66f..e0bf58365b6 100644 --- a/src/modules/ManagedItems.test.js +++ b/src/modules/ManagedItems.test.js @@ -51,7 +51,7 @@ function getNewManagedTestItems() { testItems, testPropDefs, new LocalStorageMock(), - 'test_' + 'test_', ) } @@ -114,7 +114,7 @@ describe('ManagedItems', () => { // Ensure pre-conditions: expect(managedItems.selected).to.be.eql([]) expect(managedItems.filteredItems.length).to.be.eql( - managedItems.items.length + managedItems.items.length, ) const itemsToBeSelected = [{ id: 1 }, { id: 3 }] managedItems.selected = itemsToBeSelected @@ -123,13 +123,13 @@ describe('ManagedItems', () => { managedItems.setFilterToSelected() // Ensure post-conditions: expect(managedItems.filteredItems.length).to.eql( - itemsToBeSelected.length + itemsToBeSelected.length, ) expect(managedItems.filteredItems[0].id).to.eql( - itemsToBeSelected[0].id + itemsToBeSelected[0].id, ) expect(managedItems.filteredItems[1].id).to.eql( - itemsToBeSelected[1].id + itemsToBeSelected[1].id, ) }) }) @@ -173,7 +173,7 @@ describe('ManagedItems', () => { testItems, { id: {} }, new LocalStorageMock(), - 'test_' + 'test_', ) expect(managedItems.allTableHeaders).to.be.eql([ { text: 'id', type: 'string', value: 'id', groupable: true }, @@ -209,7 +209,7 @@ describe('ManagedItems', () => { testItems, { id: {} }, new LocalStorageMock(), - 'test_' + 'test_', ) managedItems.groupBy = ['value'] expect(managedItems.groupByTitle).to.eql('value') diff --git a/src/modules/NodeCollection.js b/src/modules/NodeCollection.js index 4ce2a0f8051..2a9b5aeda0f 100644 --- a/src/modules/NodeCollection.js +++ b/src/modules/NodeCollection.js @@ -39,21 +39,21 @@ export class NodeCollection { _filterByProps(node, properties, filter) { const mergedProps = [properties].reduce( (merged, prop) => merged.concat(prop), - [] + [], ) return mergedProps.find((prop) => filter( this.propDefs && typeof this.propDefs[prop].customValue === 'function' ? this.propDefs[prop].customValue(node) - : node[prop] - ) + : node[prop], + ), ) } filter(properties, filter) { const filtered = this.nodes.filter((node) => - this._filterByProps(node, properties, filter) + this._filterByProps(node, properties, filter), ) return new NodeCollection(filtered, this.propDefs) } @@ -61,21 +61,21 @@ export class NodeCollection { contains(properties, value, caseSensitive = false) { return this.filter( properties, - this._createStringFilter(value, caseSensitive) + this._createStringFilter(value, caseSensitive), ) } matches(properties, value, caseSensitive = false) { return this.filter( properties, - this._createRegexFilter(value, caseSensitive) + this._createRegexFilter(value, caseSensitive), ) } equals(properties, value) { return this.filter( properties, - (nodeValue) => this._isUndefined(value) || value === nodeValue + (nodeValue) => this._isUndefined(value) || value === nodeValue, ) } @@ -83,14 +83,14 @@ export class NodeCollection { return this.betweenNumber( col, filter ? filter.min : null, - filter ? filter.max : null + filter ? filter.max : null, ).equalsAny(col, filter ? (filter.values ? filter.values : []) : []) } filterStringCol(col, filter) { return this.matches([col], filter ? filter.match : '').equalsAny( col, - filter ? (filter.values ? filter.values : []) : [] + filter ? (filter.values ? filter.values : []) : [], ) } @@ -102,7 +102,7 @@ export class NodeCollection { return this.betweenDate( col, filter ? filter.from : null, - filter ? filter.to : null + filter ? filter.to : null, ) } @@ -111,7 +111,7 @@ export class NodeCollection { properties, (nodeValue) => (this._isUndefined(minValue) || minValue <= nodeValue) && - (this._isUndefined(maxValue) || maxValue >= nodeValue) + (this._isUndefined(maxValue) || maxValue >= nodeValue), ) } @@ -130,7 +130,8 @@ export class NodeCollection { equalsAny(properties, values) { return this.filter( properties, - (nodeValue) => values.length === 0 || values.indexOf(nodeValue) >= 0 + (nodeValue) => + values.length === 0 || values.indexOf(nodeValue) >= 0, ) } } diff --git a/src/modules/NodeCollection.test.js b/src/modules/NodeCollection.test.js index 61334792561..7bd2b9a464d 100644 --- a/src/modules/NodeCollection.test.js +++ b/src/modules/NodeCollection.test.js @@ -152,7 +152,7 @@ describe('NodeCollection', () => { const filtered = collection.betweenNumber( 'id', undefined, - undefined + undefined, ) expect(filtered.nodes).to.eql([ { id: 10, sample: 10 }, @@ -217,7 +217,7 @@ describe('NodeCollection', () => { const filtered = collection.betweenDate( 'lastActive', undefined, - undefined + undefined, ) expect(filtered.nodes).to.eql([ { id: 10, lastActive: new Date(2020, 11, 9, 0, 0) }, @@ -247,7 +247,7 @@ describe('NodeCollection', () => { const filtered = collection.betweenDate( 'lastActive', new Date(2020, 11, 10, 0, 0), - null + null, ) expect(filtered.nodes).to.eql([ { id: 20, lastActive: new Date(2020, 11, 10, 0, 0) }, @@ -263,7 +263,7 @@ describe('NodeCollection', () => { const filtered = collection.betweenDate( 'lastActive', null, - new Date(2020, 11, 10, 0, 0) + new Date(2020, 11, 10, 0, 0), ) expect(filtered.nodes).to.eql([ { id: 10, lastActive: new Date(2020, 11, 9, 0, 0) }, @@ -279,7 +279,7 @@ describe('NodeCollection', () => { const filtered = collection.betweenDate( 'lastActive', new Date(2020, 11, 9, 12, 0), - new Date(2020, 11, 10, 12, 0) + new Date(2020, 11, 10, 12, 0), ) expect(filtered.nodes).to.eql([ { id: 20, lastActive: new Date(2020, 11, 10, 0, 0) }, diff --git a/src/stores/base.js b/src/stores/base.js index 6bdc651f6a7..1846b1bd2d8 100644 --- a/src/stores/base.js +++ b/src/stores/base.js @@ -194,7 +194,7 @@ const useBaseStore = defineStore('base', { if (isPartial && index === undefined) { log.warn( 'Received partial node info about an unknown node, skipping...', - n + n, ) return } diff --git a/src/views/ControlPanel.vue b/src/views/ControlPanel.vue index 0a0cd58d09e..58f5e838047 100644 --- a/src/views/ControlPanel.vue +++ b/src/views/ControlPanel.vue @@ -418,7 +418,7 @@ export default { await this.$listeners.showConfirm( 'Attention', 'This will override all existing nodes names and locations', - 'alert' + 'alert', ) ) { try { @@ -428,7 +428,7 @@ export default { }) this.showSnackbar( response.message, - response.success ? 'success' : 'error' + response.success ? 'success' : 'error', ) } catch (error) { log.error(error) @@ -440,7 +440,7 @@ export default { const data = await ConfigApis.exportConfig() this.showSnackbar( data.message, - data.success ? 'success' : 'error' + data.success ? 'success' : 'error', ) if (data.success) { this.$listeners.export(data.data, 'nodes', 'json') @@ -454,7 +454,7 @@ export default { }, async sendAction( action, - { nodeId, broadcast, confirm, confirmLevel, nodes } + { nodeId, broadcast, confirm, confirmLevel, nodes }, ) { if (action) { if (confirm) { @@ -466,7 +466,7 @@ export default { cancelText: 'cancel', confirmText: 'ok', width: 900, - } + }, ) if (!ok) { @@ -476,13 +476,13 @@ export default { if (nodes?.length > 0) { const requests = nodes.map((node) => - this.app.apiRequest(action, [node.id]) + this.app.apiRequest(action, [node.id]), ) await Promise.allSettled(requests) this.showSnackbar( `Action ${action} sent to all nodes`, - 'success' + 'success', ) return } @@ -493,7 +493,7 @@ export default { if (isNaN(nodeId)) { this.showSnackbar( 'Node ID must be an integer value', - 'error' + 'error', ) return } @@ -508,7 +508,7 @@ export default { 'info', { cancelText: 'No', - } + }, ) args.push(secure) } else if (action === 'hardReset') { @@ -527,7 +527,7 @@ export default { hint: 'Type "yes" and press OK to confirm', }, ], - } + }, ) if (!confirm || confirm !== 'yes') { return @@ -548,7 +548,7 @@ export default { default: false, }, ], - } + }, ) if (includeSleeping === undefined) { return @@ -573,7 +573,7 @@ export default { accept: '.hex,.gbl,.otz,.ota', }, ], - } + }, ) const file = result?.file @@ -615,12 +615,12 @@ export default { progress: 0, }, }, - true + true, ) } catch (error) { this.showSnackbar( 'Error reading file: ' + error.message, - 'error' + 'error', ) return } @@ -675,7 +675,7 @@ export default { confirmText: 'Ok', width: 500, inputs, - } + }, ) if (!result) { @@ -753,13 +753,13 @@ export default { if (response.success) { this.showSnackbar( 'Function executed successfully, check console for result', - 'success' + 'success', ) } log.info( 'Driver function result:', - response.result + response.result, ) }, }, @@ -772,7 +772,7 @@ export default { driver. The function is async.`, }, ], - } + }, ) return @@ -783,7 +783,7 @@ export default { 'alert', { confirmText: 'Ok', - } + }, ) if (!confirm) { return @@ -810,7 +810,7 @@ export default { key: 'useRaw', }, ], - } + }, ) if (!result?.file) { return @@ -840,7 +840,7 @@ export default { label: 'Reset security classes', }, ], - } + }, ) if (!options || Object.keys(options).length === 0) { @@ -872,15 +872,15 @@ export default { if (response.success) { this.showSnackbar( `Node ${nodeid} api request success`, - 'success' + 'success', ) } else { this.showSnackbar( `Node ${nodeid} error: ${response.error}`, - 'error' + 'error', ) } - }) + }), ) } @@ -893,26 +893,26 @@ export default { case 'getDriverStatistics': this.$listeners.showConfirm( 'Driver statistics', - this.jsonToList(response.result) + this.jsonToList(response.result), ) break case 'getNodeStatistics': this.$listeners.showConfirm( 'Node statistics', - this.jsonToList(response.result) + this.jsonToList(response.result), ) break case 'backupNVMRaw': { this.showSnackbar( 'NVM Backup DONE. You can find your file NVM_.bin in store directory', - 'success' + 'success', ) const { result } = response this.$listeners.export( result.data, result.fileName, - 'bin' + 'bin', ) } break @@ -1021,7 +1021,7 @@ export default { default: this.showSnackbar( `API ${response.api} ended successfully`, - 'success' + 'success', ) } } else { @@ -1038,7 +1038,7 @@ export default { status: response.message, }, }, - true + true, ) } } @@ -1053,7 +1053,7 @@ export default { mounted() { this.bindEvent( 'rebuildRoutesProgress', - this.setRebuildRoutesProgress.bind(this) + this.setRebuildRoutesProgress.bind(this), ) }, beforeDestroy() { diff --git a/src/views/Debug.vue b/src/views/Debug.vue index 5668e192770..23fd0138b19 100644 --- a/src/views/Debug.vue +++ b/src/views/Debug.vue @@ -76,7 +76,7 @@