Skip to content

Commit 0fc78c4

Browse files
committed
Working on typescript
1 parent db00c1d commit 0fc78c4

33 files changed

+5215
-4742
lines changed

eslint.config.mjs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,23 @@ export default [
66
languageOptions: {
77
parserOptions: {
88
projectService: {
9-
allowDefaultProject: ['eslint.config.mjs'],
9+
allowDefaultProject: ['*.mjs'],
1010
},
1111
tsconfigRootDir: import.meta.dirname,
12+
project: './tsconfig.json',
1213
},
1314
},
1415
},
1516
{
16-
ignores: ['src-admin/**/*', 'src/**/*', 'admin/**/*'],
17+
ignores: [
18+
'src-admin/**/*',
19+
'admin/**/*',
20+
'admin-config/**/*',
21+
'detection/*',
22+
'lib/**/*',
23+
'node_modules/**/*',
24+
'test/**/*',
25+
],
1726
},
1827
{
1928
// disable temporary the rule 'jsdoc/require-param' and enable 'jsdoc/require-jsdoc'

install/installTypings.js

Lines changed: 34 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
// The adapter includes typings for the lowest supported NodeJS version.
3+
// The adapter includes typings for the lowest supported Node.js version.
44
// This script updates them to the installed version
55

66
const { spawn } = require('node:child_process');
@@ -16,29 +16,6 @@ function fail(reason) {
1616

1717
// Find the latest version on npm
1818
console.log('Installing NodeJS typings...');
19-
npmCommand('view', ['@types/node', 'version'], {stdout: 'pipe', stderr: 'pipe'})
20-
.then(cmdResult => {
21-
if (cmdResult.exitCode !== 0) {
22-
return fail(cmdResult.stderr);
23-
}
24-
const latestVersion = semver.coerce(cmdResult.stdout).major;
25-
console.log(`latest @types: ${latestVersion}, installed node: ${installedNodeVersion}`);
26-
return semver.gt(`${installedNodeVersion}.0.0`, `${latestVersion}.0.0`)
27-
? 'latest' // The installed version is too new, install latest
28-
: installedNodeVersion.toString()
29-
;
30-
})
31-
.then(targetVersion => {
32-
// Install the desired version
33-
return npmCommand('i', [`@types/node@${targetVersion}`], {stdout: 'ignore', stderr: 'pipe'});
34-
})
35-
.then(cmdResult => {
36-
if (cmdResult.exitCode !== 0) {
37-
return fail(cmdResult.stderr);
38-
} else {
39-
process.exit(0);
40-
}
41-
});
4219

4320
// TODO: the following code is copied from a js-controller fork
4421
// It should be moved to the core and referenced from there in a future version
@@ -60,7 +37,7 @@ npmCommand('view', ['@types/node', 'version'], {stdout: 'pipe', stderr: 'pipe'})
6037
*/
6138

6239
/**
63-
* Executes an npm command (e.g. install) and returns the exit code and (if requested) the stdout
40+
* Executes a npm command (e.g., install) and returns the exit code and (if requested) the stdout
6441
* @param {string} command The npm command to execute
6542
* @param {string[]} [npmArgs] The command line arguments for the npm command
6643
* @param {Partial<NpmCommandOptions>} [options] (optional) Some options for the command execution
@@ -78,50 +55,39 @@ function npmCommand(command, npmArgs, options) {
7855
const npmBinary = /^win/.test(process.platform) ? 'npm.cmd' : 'npm';
7956
/** @type {import("child_process").SpawnOptions} */
8057
const spawnOptions = {
81-
stdio: [
82-
options.stdin || process.stdin,
83-
options.stdout || process.stdout,
84-
options.stderr || process.stderr,
85-
],
58+
stdio: [options.stdin || process.stdin, options.stdout || process.stdout, options.stderr || process.stderr],
8659
// @ts-ignore This option exists starting with NodeJS 8
8760
windowsHide: true,
8861
};
8962
if (options.cwd != null) spawnOptions.cwd = options.cwd;
9063

9164
// Now execute the npm process and avoid throwing errors
92-
return new Promise((resolve) => {
65+
return new Promise(resolve => {
9366
try {
9467
/** @type {string} */
9568
let bufferedStdout;
9669
/** @type {string} */
9770
let bufferedStderr;
98-
const cmd = spawn(npmBinary, [command].concat(npmArgs), spawnOptions)
99-
.on('close', (code, signal) => {
100-
resolve({
101-
exitCode: code,
102-
signal,
103-
stdout: bufferedStdout,
104-
stderr: bufferedStderr
105-
});
71+
const cmd = spawn(npmBinary, [command].concat(npmArgs), spawnOptions).on('close', (code, signal) => {
72+
resolve({
73+
exitCode: code,
74+
signal,
75+
stdout: bufferedStdout,
76+
stderr: bufferedStderr,
10677
});
78+
});
10779
// Capture stdout/stderr if requested
10880
if (options.stdout === 'pipe') {
10981
bufferedStdout = '';
11082
cmd.stdout.on('data', chunk => {
111-
const buffer = Buffer.isBuffer(chunk)
112-
? chunk
113-
: new Buffer(chunk, 'utf8')
114-
;
83+
const buffer = Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk, 'utf8');
11584
bufferedStdout += buffer;
11685
});
11786
}
11887
if (options.stderr === 'pipe') {
11988
bufferedStderr = '';
12089
cmd.stderr.on('data', chunk => {
121-
const buffer = Buffer.isBuffer(chunk)
122-
? chunk
123-
: new Buffer(chunk, 'utf8')
124-
;
90+
const buffer = Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk, 'utf8');
12591
bufferedStderr += buffer;
12692
});
12793
}
@@ -130,3 +96,24 @@ function npmCommand(command, npmArgs, options) {
13096
}
13197
});
13298
}
99+
100+
npmCommand('view', ['@types/node', 'version'], { stdout: 'pipe', stderr: 'pipe' })
101+
.then(cmdResult => {
102+
if (cmdResult.exitCode !== 0) {
103+
return fail(cmdResult.stderr);
104+
}
105+
const latestVersion = semver.coerce(cmdResult.stdout).major;
106+
console.log(`latest @types: ${latestVersion}, installed node: ${installedNodeVersion}`);
107+
return semver.gt(`${installedNodeVersion}.0.0`, `${latestVersion}.0.0`)
108+
? 'latest' // The installed version is too new, install latest
109+
: installedNodeVersion.toString();
110+
})
111+
// Install the desired version
112+
.then(targetVersion => npmCommand('i', [`@types/node@${targetVersion}`], { stdout: 'ignore', stderr: 'pipe' }))
113+
.then(cmdResult => {
114+
if (cmdResult.exitCode !== 0) {
115+
fail(cmdResult.stderr);
116+
} else {
117+
process.exit(0);
118+
}
119+
});

src/lib/consts.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,21 @@ export const monthShort: Record<ioBroker.Languages, string[]> = {
327327
'zh-cn': ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
328328
};
329329

330-
export type AstroEvent = 'sunrise' | 'sunset' | 'sunriseEnd' | 'sunsetStart' | 'dawn' | 'dusk' | 'nauticalDawn' | 'nauticalDusk' | 'nadir' | 'nightEnd' | 'night' | 'goldenHourEnd' | 'goldenHour' | 'solarNoon';
330+
export type AstroEvent =
331+
| 'sunrise'
332+
| 'sunset'
333+
| 'sunriseEnd'
334+
| 'sunsetStart'
335+
| 'dawn'
336+
| 'dusk'
337+
| 'nauticalDawn'
338+
| 'nauticalDusk'
339+
| 'nadir'
340+
| 'nightEnd'
341+
| 'night'
342+
| 'goldenHourEnd'
343+
| 'goldenHour'
344+
| 'solarNoon';
331345

332346
export const astroList: AstroEvent[] = [
333347
'sunrise',

src/lib/convert.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// controller uses this file when build uploads
2-
export function stringify(data: { data: ioBroker.ScriptObject | ioBroker.ChannelObject, id: string }): { id: string; data: string | undefined } {
3-
let obj = data.data;
2+
export function stringify(data: { data: ioBroker.ScriptObject | ioBroker.ChannelObject; id: string }): {
3+
id: string;
4+
data: string | undefined;
5+
} {
6+
const obj = data.data;
47
let id = data.id;
58
let result: string | undefined;
69
if (data.data.type === 'channel') {
@@ -39,7 +42,10 @@ export function stringify(data: { data: ioBroker.ScriptObject | ioBroker.Channel
3942
return { id, data: result };
4043
}
4144

42-
export function parse(data: { data: string, id: string }): { id: string; data: ioBroker.ScriptObject; error: string | undefined } | null {
45+
export function parse(data: {
46+
data: string;
47+
id: string;
48+
}): { id: string; data: ioBroker.ScriptObject; error: string | undefined } | null {
4349
let obj: string = data.data;
4450
let id = data.id;
4551
let error: string | undefined;
@@ -58,8 +64,8 @@ export function parse(data: { data: string, id: string }): { id: string; data: i
5864

5965
try {
6066
result = JSON.parse(obj);
61-
} catch (e) {
62-
error = `Cannot parse object "${name}": ${e}`;
67+
} catch (err: unknown) {
68+
error = `Cannot parse object "${name}": ${err as Error}`;
6369
result = {
6470
common: {
6571
name: name.split('.').pop() || name,
@@ -92,8 +98,8 @@ export function parse(data: { data: string, id: string }): { id: string; data: i
9298
result = {} as ioBroker.Object;
9399
result.common = JSON.parse(stringObj);
94100
result.common.source = source;
95-
} catch (e) {
96-
error = `Cannot parse object "${id}": ${e}`;
101+
} catch (err: unknown) {
102+
error = `Cannot parse object "${id}": ${err as Error}`;
97103
}
98104
} else {
99105
source = obj;

src/lib/debug.ts

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { fork, type ForkOptions } from 'node:child_process';
2+
import type { DebugState } from '../types';
23

34
const adapter = {
45
log: {
@@ -7,7 +8,7 @@ const adapter = {
78
warn: (text: string) => console.warn(text),
89
debug: (text: string) => console.log(text),
910
},
10-
setState: (id:string, val: any): void => {
11+
setState: (id: string, val: any): void => {
1112
try {
1213
val = JSON.parse(val);
1314
} catch (e) {
@@ -18,56 +19,54 @@ const adapter = {
1819
extendForeignObjectAsync: (id: string, obj: Partial<ioBroker.ScriptObject>) => {
1920
console.log(`EXTEND: ${id} ${JSON.stringify(obj)}`);
2021
return Promise.resolve();
21-
}
22+
},
2223
};
2324
const context: {
2425
objects: Record<string, ioBroker.Object>;
2526
} = {
2627
objects: {},
2728
};
2829

29-
const debugState: {
30-
scriptName: string;
31-
child: any;
32-
promiseOnEnd: any;
33-
paused: boolean;
34-
endTimeout: NodeJS.Timeout | null;
35-
running: boolean;
36-
breakOnStart: boolean;
37-
} = {
30+
const debugState: DebugState = {
3831
scriptName: '',
3932
child: null,
4033
promiseOnEnd: null,
4134
paused: false,
4235
endTimeout: null,
4336
running: false,
4437
breakOnStart: false,
38+
started: 0,
4539
};
4640

47-
function stopDebug() {
41+
function stopDebug(): Promise<void> {
4842
if (debugState.child) {
4943
sendToInspector({ cmd: 'end' });
5044
debugState.endTimeout = setTimeout(() => {
5145
debugState.endTimeout = null;
52-
debugState.child.kill('SIGTERM');
46+
debugState.child?.kill('SIGTERM');
5347
});
48+
debugState.promiseOnEnd = debugState.promiseOnEnd || Promise.resolve(0);
5449
} else {
55-
debugState.promiseOnEnd = Promise.resolve();
50+
debugState.promiseOnEnd = Promise.resolve(0);
5651
}
5752

5853
return debugState.promiseOnEnd.then(() => {
5954
debugState.child = null;
6055
debugState.running = false;
6156
debugState.scriptName = '';
62-
debugState.endTimeout && clearTimeout(debugState.endTimeout);
63-
debugState.endTimeout = null;
57+
if (debugState.endTimeout) {
58+
clearTimeout(debugState.endTimeout);
59+
debugState.endTimeout = null;
60+
}
6461
});
6562
}
6663

67-
function disableScript(id) {
64+
function disableScript(id: string): Promise<void> {
6865
const obj = context.objects[id];
6966
if (obj?.common?.enabled) {
70-
return adapter.extendForeignObjectAsync(obj._id, { common: { enabled: false } } as Partial<ioBroker.ScriptObject>);
67+
return adapter.extendForeignObjectAsync(obj._id, {
68+
common: { enabled: false },
69+
} as Partial<ioBroker.ScriptObject>);
7170
}
7271
return Promise.resolve();
7372
}
@@ -76,8 +75,8 @@ function sendToInspector(message: string | Record<string, any>): void {
7675
if (typeof message === 'string') {
7776
try {
7877
message = JSON.parse(message);
79-
} catch (e) {
80-
adapter.log.error(`Cannot parse message to inspector: ${message}`);
78+
} catch {
79+
adapter.log.error(`Cannot parse message to inspector: ${JSON.stringify(message)}`);
8180
return adapter.setState('debug.from', JSON.stringify({ error: 'Cannot parse message to inspector' }));
8281
}
8382
}
@@ -89,7 +88,7 @@ function sendToInspector(message: string | Record<string, any>): void {
8988
return adapter.setState('debug.from', JSON.stringify({ error: `Cannot send command to terminated inspector` }));
9089
}
9190
}
92-
91+
/*
9392
function childPrint(text: string): void {
9493
console.log(
9594
text
@@ -100,8 +99,9 @@ function childPrint(text: string): void {
10099
.join('\n'),
101100
);
102101
}
102+
*/
103103

104-
function debugScript(data): Promise<void> {
104+
function debugScript(data: { breakOnStart?: boolean; scriptName: string }): Promise<void> {
105105
// stop a script if it is running
106106

107107
return disableScript(data.scriptName)
@@ -133,15 +133,15 @@ function debugScript(data): Promise<void> {
133133
};
134134
try {
135135
debugMessage = JSON.parse(message);
136-
} catch (e) {
136+
} catch {
137137
return adapter.log.error(`Cannot parse message from inspector: ${message}`);
138138
}
139139

140140
adapter.setState('debug.from', JSON.stringify(debugMessage));
141141

142142
switch (debugMessage.cmd) {
143143
case 'ready': {
144-
debugState.child.send(JSON.stringify({ cmd: 'start', scriptName: debugState.scriptName }));
144+
debugState.child?.send(JSON.stringify({ cmd: 'start', scriptName: debugState.scriptName }));
145145
break;
146146
}
147147

@@ -168,7 +168,9 @@ function debugScript(data): Promise<void> {
168168
}
169169

170170
case 'readyToDebug': {
171-
console.log(`readyToDebug (set breakpoints): [${debugMessage.scriptId}] ${debugMessage.script}`);
171+
console.log(
172+
`readyToDebug (set breakpoints): [${debugMessage.scriptId}] ${debugMessage.script}`,
173+
);
172174
break;
173175
}
174176
}

0 commit comments

Comments
 (0)