@iobroker/js-controller-common-db 7.2.3 → 8.0.0-alpha.2-20260923-99da17fcc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/build/cjs/index.js +3 -3
  2. package/build/cjs/lib/common/aliasProcessing.js +6 -0
  3. package/build/cjs/lib/common/aliasProcessing.js.map +2 -2
  4. package/build/cjs/lib/common/interview.js +2 -0
  5. package/build/cjs/lib/common/interview.js.map +1 -1
  6. package/build/cjs/lib/common/logger.d.ts +34 -1
  7. package/build/cjs/lib/common/logger.js +37 -37
  8. package/build/cjs/lib/common/logger.js.map +2 -2
  9. package/build/cjs/lib/common/maybeCallback.js +4 -0
  10. package/build/cjs/lib/common/maybeCallback.js.map +1 -1
  11. package/build/cjs/lib/common/password.d.ts +9 -0
  12. package/build/cjs/lib/common/password.js +8 -6
  13. package/build/cjs/lib/common/password.js.map +2 -2
  14. package/build/cjs/lib/common/session.js +10 -5
  15. package/build/cjs/lib/common/session.js.map +2 -2
  16. package/build/cjs/lib/common/tools.d.ts +187 -59
  17. package/build/cjs/lib/common/tools.js +522 -476
  18. package/build/cjs/lib/common/tools.js.map +3 -3
  19. package/build/esm/lib/common/aliasProcessing.d.ts.map +1 -1
  20. package/build/esm/lib/common/aliasProcessing.js +5 -0
  21. package/build/esm/lib/common/aliasProcessing.js.map +1 -1
  22. package/build/esm/lib/common/logger.d.ts +34 -1
  23. package/build/esm/lib/common/logger.d.ts.map +1 -1
  24. package/build/esm/lib/common/logger.js +45 -49
  25. package/build/esm/lib/common/logger.js.map +1 -1
  26. package/build/esm/lib/common/password.d.ts +9 -0
  27. package/build/esm/lib/common/password.d.ts.map +1 -1
  28. package/build/esm/lib/common/password.js +5 -0
  29. package/build/esm/lib/common/password.js.map +1 -1
  30. package/build/esm/lib/common/session.d.ts.map +1 -1
  31. package/build/esm/lib/common/session.js +6 -6
  32. package/build/esm/lib/common/session.js.map +1 -1
  33. package/build/esm/lib/common/tools.d.ts +187 -59
  34. package/build/esm/lib/common/tools.d.ts.map +1 -1
  35. package/build/esm/lib/common/tools.js +580 -586
  36. package/build/esm/lib/common/tools.js.map +1 -1
  37. package/build/tsconfig.build.tsbuildinfo +1 -1
  38. package/package.json +18 -18
@@ -5,6 +5,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
9
  var __export = (target, all) => {
9
10
  for (var name in all)
10
11
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -45,6 +46,7 @@ __export(tools_exports, {
45
46
  encrypt: () => encrypt,
46
47
  ensureDNSOrder: () => ensureDNSOrder,
47
48
  execAsync: () => execAsync,
49
+ execFileAsync: () => execFileAsync,
48
50
  findIPs: () => findIPs,
49
51
  formatAliasValue: () => formatAliasValue,
50
52
  generateDefaultCertificates: () => generateDefaultCertificates,
@@ -78,6 +80,7 @@ __export(tools_exports, {
78
80
  getRepositoryFile: () => getRepositoryFile,
79
81
  getRepositoryFileAsync: () => getRepositoryFileAsync,
80
82
  getRootDir: () => getRootDir,
83
+ hasRegisteredResourceShape: () => hasRegisteredResourceShape,
81
84
  installNodeModule: () => installNodeModule,
82
85
  isAdapterEsmModule: () => isAdapterEsmModule,
83
86
  isArray: () => isArray,
@@ -85,6 +88,7 @@ __export(tools_exports, {
85
88
  isDevInstallation: () => isDevInstallation,
86
89
  isDevServerInstallation: () => isDevServerInstallation,
87
90
  isDocker: () => isDocker,
91
+ isForeignProcess: () => isForeignProcess,
88
92
  isGithubPathname: () => isGithubPathname,
89
93
  isHostRunning: () => isHostRunning,
90
94
  isIoBrokerInstalledAsSystemd: () => isIoBrokerInstalledAsSystemd,
@@ -92,9 +96,11 @@ __export(tools_exports, {
92
96
  isLocalAddress: () => isLocalAddress,
93
97
  isLogLevel: () => isLogLevel,
94
98
  isObject: () => isObject,
99
+ isProcessRunning: () => isProcessRunning,
95
100
  isShortGithubUrl: () => isShortGithubUrl,
96
101
  isSingleHost: () => isSingleHost,
97
102
  isValidPattern: () => isValidPattern,
103
+ isValidUsedResourceType: () => isValidUsedResourceType,
98
104
  maybeArrayToString: () => maybeArrayToString,
99
105
  measureEventLoopLag: () => measureEventLoopLag,
100
106
  parseDependencies: () => parseDependencies,
@@ -119,33 +125,32 @@ __export(tools_exports, {
119
125
  });
120
126
  module.exports = __toCommonJS(tools_exports);
121
127
  var __import_meta_url = typeof document === "undefined" ? new (require("url".replace("", ""))).URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
122
- var import_fs_extra = __toESM(require("fs-extra"), 1);
123
128
  var import_node_path = __toESM(require("node:path"), 1);
124
129
  var import_semver = __toESM(require("semver"), 1);
125
130
  var import_node_os = __toESM(require("node:os"), 1);
126
- var import_node_forge = __toESM(require("node-forge"), 1);
127
- var import_deep_clone = __toESM(require("deep-clone"), 1);
128
- var import_promisify_child_process = require("promisify-child-process");
131
+ var import_node_crypto = __toESM(require("node:crypto"), 1);
129
132
  var import_node_readline = require("node:readline");
130
133
  var import_node_stream = require("node:stream");
131
- var import_pak = require("@alcalzone/pak");
132
- var import_exitCodes = require("../../lib/common/exitCodes.js");
133
134
  var import_node_zlib = __toESM(require("node:zlib"), 1);
134
- var import_password = require("../../lib/common/password.js");
135
- var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1);
136
- var import_axios = __toESM(require("axios"), 1);
137
- var import_node_crypto = __toESM(require("node:crypto"), 1);
138
135
  var import_node_child_process = require("node:child_process");
139
136
  var import_node_url = require("node:url");
140
137
  var import_node_events = __toESM(require("node:events"), 1);
141
- var import_maybeCallback = require("../../lib/common/maybeCallback.js");
142
- var import_node = __toESM(require("node.extend"), 1);
143
138
  var import_node_dns = require("node:dns");
144
- var import_aliasProcessing = require("../../lib/common/aliasProcessing.js");
145
139
  var url = __toESM(require("node:url"), 1);
146
140
  var import_node_module = require("node:module");
141
+ var import_node_forge = __toESM(require("node-forge"), 1);
142
+ var import_fs_extra = __toESM(require("fs-extra"), 1);
143
+ var import_deep_clone = __toESM(require("deep-clone"), 1);
144
+ var import_pak = require("@alcalzone/pak");
145
+ var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1);
146
+ var import_axios = __toESM(require("axios"), 1);
147
+ var import_node = __toESM(require("node.extend"), 1);
148
+ var import_exitCodes = require("../../lib/common/exitCodes.js");
149
+ var import_password = require("../../lib/common/password.js");
150
+ var import_aliasProcessing = require("../../lib/common/aliasProcessing.js");
147
151
  var import_constants = require("../../lib/common/constants.js");
148
152
  __reExport(tools_exports, require("../../lib/common/maybeCallback.js"), module.exports);
153
+ const HASH_TEXT = "hash";
149
154
  const thisDir = url.fileURLToPath(new URL(".", __import_meta_url || `file://${__filename}`));
150
155
  const require2 = (0, import_node_module.createRequire)(__import_meta_url || `file://${__filename}`);
151
156
  var ERRORS;
@@ -189,6 +194,7 @@ function copyAttributes(oldObj, newObj, originalObj, isNonEdit) {
189
194
  }
190
195
  }
191
196
  }
197
+ __name(copyAttributes, "copyAttributes");
192
198
  function checkNonEditable(oldObject, newObject) {
193
199
  if (!oldObject) {
194
200
  return true;
@@ -237,31 +243,51 @@ function checkNonEditable(oldObject, newObject) {
237
243
  }
238
244
  return true;
239
245
  }
246
+ __name(checkNonEditable, "checkNonEditable");
240
247
  function upToDate(repoVersion, installedVersion) {
241
248
  return import_semver.default.gte(installedVersion, repoVersion);
242
249
  }
243
- function decryptPhrase(password2, data, callback) {
244
- const decipher = import_node_crypto.default.createDecipher("aes192", password2);
245
- try {
246
- let decrypted = "";
247
- decipher.on("readable", () => {
248
- const data2 = decipher.read();
249
- if (data2) {
250
- decrypted += data2.toString("utf8");
251
- }
252
- });
253
- decipher.on("error", (error) => {
254
- console.error(`Cannot decode secret: ${error.message}`);
255
- callback(null);
256
- });
257
- decipher.on("end", () => callback(decrypted));
258
- decipher.write(data, "hex");
259
- decipher.end();
260
- } catch (e) {
261
- console.error(`Cannot decode secret: ${e.message}`);
262
- callback(null);
250
+ __name(upToDate, "upToDate");
251
+ function evpBytesToKeyMD5(password2, keyLen, ivLen) {
252
+ const passwordBuffer = Buffer.from(password2, "utf8");
253
+ let material = Buffer.alloc(0);
254
+ let block = Buffer.alloc(0);
255
+ while (material.length < keyLen + ivLen) {
256
+ block = import_node_crypto.default.createHash("md5").update(Buffer.concat([block, passwordBuffer])).digest();
257
+ material = Buffer.concat([material, block]);
263
258
  }
259
+ return {
260
+ key: material.subarray(0, keyLen),
261
+ iv: material.subarray(keyLen, keyLen + ivLen)
262
+ };
263
+ }
264
+ __name(evpBytesToKeyMD5, "evpBytesToKeyMD5");
265
+ function decryptPhrase(password2, data) {
266
+ const { key, iv } = evpBytesToKeyMD5(password2, 24, 16);
267
+ const decipher = import_node_crypto.default.createDecipheriv("aes-192-cbc", key, iv);
268
+ return new Promise((resolve) => {
269
+ try {
270
+ let decrypted = "";
271
+ decipher.on("readable", () => {
272
+ const data2 = decipher.read();
273
+ if (data2) {
274
+ decrypted += data2.toString("utf8");
275
+ }
276
+ });
277
+ decipher.on("error", (error) => {
278
+ console.error(`Cannot decode secret: ${error.message}`);
279
+ resolve(null);
280
+ });
281
+ decipher.on("end", () => resolve(decrypted));
282
+ decipher.write(data, "hex");
283
+ decipher.end();
284
+ } catch (e) {
285
+ console.error(`Cannot decode secret: ${e.message}`);
286
+ resolve(null);
287
+ }
288
+ });
264
289
  }
290
+ __name(decryptPhrase, "decryptPhrase");
265
291
  async function isSingleHost(objects) {
266
292
  const res = await objects.getObjectList({
267
293
  startkey: "system.host.",
@@ -270,6 +296,7 @@ async function isSingleHost(objects) {
270
296
  const hostObjs = res.rows.filter((obj) => obj.value && obj.value.type === "host");
271
297
  return hostObjs.length <= 1;
272
298
  }
299
+ __name(isSingleHost, "isSingleHost");
273
300
  async function isHostRunning(objects, states) {
274
301
  const res = await objects.getObjectList({
275
302
  startkey: "system.host.",
@@ -278,21 +305,24 @@ async function isHostRunning(objects, states) {
278
305
  res.rows = res.rows.filter((obj) => obj.value?.type === "host");
279
306
  for (const hostObj of res.rows) {
280
307
  const state = await states.getState(`${hostObj.id}.alive`);
281
- if (state && state.val) {
308
+ if (state?.val) {
282
309
  return true;
283
310
  }
284
311
  }
285
312
  return false;
286
313
  }
314
+ __name(isHostRunning, "isHostRunning");
287
315
  function isDevInstallation() {
288
316
  return import_fs_extra.default.pathExistsSync(`${getControllerDir()}/../../packages/controller`);
289
317
  }
318
+ __name(isDevInstallation, "isDevInstallation");
290
319
  function getAppName() {
291
320
  if (isDevInstallation()) {
292
321
  return "ioBroker";
293
322
  }
294
323
  return "iobroker";
295
324
  }
325
+ __name(getAppName, "getAppName");
296
326
  const appNameLowerCase = "iobroker";
297
327
  const appName = getAppName();
298
328
  function findIPs() {
@@ -310,6 +340,7 @@ function findIPs() {
310
340
  }
311
341
  return ownIpArr;
312
342
  }
343
+ __name(findIPs, "findIPs");
313
344
  function findPath(path2, url2) {
314
345
  if (!url2) {
315
346
  return "";
@@ -325,6 +356,7 @@ function findPath(path2, url2) {
325
356
  }
326
357
  return `${thisDir}/../${path2}${url2}`;
327
358
  }
359
+ __name(findPath, "findPath");
328
360
  async function getMac() {
329
361
  const macRegex = /(?:[a-z0-9]{2}[:-]){5}[a-z0-9]{2}/gi;
330
362
  const zeroRegex = /(?:[0]{2}[:-]){5}[0]{2}/;
@@ -334,7 +366,7 @@ async function getMac() {
334
366
  throw new Error(stderr);
335
367
  }
336
368
  if (typeof stdout !== "string") {
337
- throw new Error(`Unexpected stdout: ${stdout?.toString()}`);
369
+ throw new Error(`Unexpected stdout: ${typeof stdout}`);
338
370
  }
339
371
  let macAddress;
340
372
  let match;
@@ -355,12 +387,14 @@ ${stdout}`);
355
387
  }
356
388
  return result.replace(/-/g, ":").toLowerCase();
357
389
  }
390
+ __name(getMac, "getMac");
358
391
  async function getNewestDockerImageVersion() {
359
392
  const res = await import_axios.default.get(DOCKER_INFO_URL);
360
393
  const dockerResult = res.data.results[0];
361
394
  const isNew = new Date(dockerResult.last_updated).getTime() > new Date(process.env.BUILD).getTime() + DOCKER_HUB_BUILD_TIME_MS;
362
395
  return { version: dockerResult.name, lastUpdated: dockerResult.last_updated, isNew };
363
396
  }
397
+ __name(getNewestDockerImageVersion, "getNewestDockerImageVersion");
364
398
  function getDockerInformation() {
365
399
  try {
366
400
  const versionString = import_fs_extra.default.readFileSync(OFFICIAL_DOCKER_FILE, { encoding: "utf-8" }).trim();
@@ -369,6 +403,7 @@ function getDockerInformation() {
369
403
  }
370
404
  return { isDocker: isDocker(), isOfficial: false };
371
405
  }
406
+ __name(getDockerInformation, "getDockerInformation");
372
407
  function isControllerUiUpgradeSupported() {
373
408
  const dockerInfo = getDockerInformation();
374
409
  if (dockerInfo.isDocker) {
@@ -382,6 +417,7 @@ function isControllerUiUpgradeSupported() {
382
417
  }
383
418
  return !["win32", "darwin"].includes(import_node_os.default.platform());
384
419
  }
420
+ __name(isControllerUiUpgradeSupported, "isControllerUiUpgradeSupported");
385
421
  function isDocker() {
386
422
  try {
387
423
  import_fs_extra.default.statSync("/.dockerenv");
@@ -404,39 +440,39 @@ function isDocker() {
404
440
  return false;
405
441
  }
406
442
  }
443
+ __name(isDocker, "isDocker");
407
444
  async function uuid(givenMac) {
408
- givenMac = givenMac ?? "";
445
+ givenMac ??= "";
409
446
  const _isDocker = isDocker();
410
447
  if (require2("ci-info").isCI) {
411
448
  return "55travis-pipe-line-cior-githubaction";
412
449
  }
413
- let mac = givenMac !== null ? givenMac || "" : null;
414
450
  let u;
415
- if (!_isDocker && mac === "") {
451
+ if (!_isDocker && !givenMac) {
416
452
  const ifaces = import_node_os.default.networkInterfaces();
417
453
  for (const iface of Object.values(ifaces)) {
418
454
  if (iface) {
419
455
  for (const entry of iface) {
420
456
  if (entry.mac !== "00:00:00:00:00:00") {
421
- mac = entry.mac;
457
+ givenMac = entry.mac;
422
458
  break;
423
459
  }
424
460
  }
425
461
  }
426
- if (mac) {
462
+ if (givenMac) {
427
463
  break;
428
464
  }
429
465
  }
430
466
  }
431
- if (!_isDocker && mac === "") {
432
- const mac2 = await getMac();
433
- return uuid(mac2);
467
+ if (!_isDocker && !givenMac) {
468
+ const mac = await getMac();
469
+ return uuid(mac);
434
470
  }
435
- if (!_isDocker && mac) {
471
+ if (!_isDocker && givenMac) {
436
472
  const md5sum = import_node_crypto.default.createHash("md5");
437
- md5sum.update(mac);
438
- mac = md5sum.digest("hex");
439
- u = `${mac.substring(0, 8)}-${mac.substring(8, 12)}-${mac.substring(12, 16)}-${mac.substring(16, 20)}-${mac.substring(20)}`;
473
+ md5sum.update(givenMac);
474
+ givenMac = md5sum.digest("hex");
475
+ u = `${givenMac.substring(0, 8)}-${givenMac.substring(8, 12)}-${givenMac.substring(12, 16)}-${givenMac.substring(16, 20)}-${givenMac.substring(20)}`;
440
476
  } else {
441
477
  let a;
442
478
  let b;
@@ -448,6 +484,7 @@ async function uuid(givenMac) {
448
484
  }
449
485
  return u;
450
486
  }
487
+ __name(uuid, "uuid");
451
488
  async function updateUuid(newUuid, _objects) {
452
489
  let _uuid = await uuid("");
453
490
  _uuid = newUuid || _uuid;
@@ -485,6 +522,7 @@ async function updateUuid(newUuid, _objects) {
485
522
  }
486
523
  return _uuid;
487
524
  }
525
+ __name(updateUuid, "updateUuid");
488
526
  async function createUuid(objects) {
489
527
  const userObj = await objects.getObject("system.user.admin");
490
528
  if (!userObj) {
@@ -523,7 +561,7 @@ async function createUuid(objects) {
523
561
  if (!PROBLEM_UUIDS.includes(obj.native.uuid)) {
524
562
  return;
525
563
  }
526
- const licObj = objects.getObject("system.adapter.vis.0");
564
+ const licObj = await objects.getObject("system.adapter.vis.0");
527
565
  if (!licObj || !licObj.native || !licObj.native.license) {
528
566
  return updateUuid("", objects);
529
567
  }
@@ -542,7 +580,8 @@ async function createUuid(objects) {
542
580
  console.warn(`Your iobroker.vis license must be updated. Please contact info@iobroker.net to get a new license!`);
543
581
  console.warn(`Provide following information in email: ${data.email}, invoice: ${data.invoice}`);
544
582
  }
545
- async function getFile(urlOrPath, fileName, callback) {
583
+ __name(createUuid, "createUuid");
584
+ async function getFile(urlOrPath, fileName) {
546
585
  if (urlOrPath.substring(0, "http://".length) === "http://" || urlOrPath.substring(0, "https://".length) === "https://") {
547
586
  const tmpFile = `${thisDir}/../tmp/${fileName || `${Math.floor(Math.random() * 268435454)}.zip`}`;
548
587
  try {
@@ -553,122 +592,92 @@ async function getFile(urlOrPath, fileName, callback) {
553
592
  "Accept-Encoding": "gzip"
554
593
  }
555
594
  });
556
- res.data.pipe(import_fs_extra.default.createWriteStream(tmpFile)).on("close", () => {
557
- console.log(`downloaded ${tmpFile}`);
558
- callback && callback(tmpFile);
595
+ await new Promise((resolve, reject) => {
596
+ res.data.pipe(import_fs_extra.default.createWriteStream(tmpFile)).on("close", resolve).on("error", reject);
559
597
  });
598
+ console.log(`downloaded ${tmpFile}`);
560
599
  } catch (e) {
561
600
  console.log(`Cannot download "${tmpFile}": ${e.message}`);
562
- callback && callback(tmpFile);
563
601
  }
564
- } else {
565
- try {
566
- if (import_fs_extra.default.existsSync(urlOrPath)) {
567
- callback && callback(urlOrPath);
568
- } else if (import_fs_extra.default.existsSync(`${thisDir}/../${urlOrPath}`)) {
569
- callback && callback(`${thisDir}/../${urlOrPath}`);
570
- } else if (import_fs_extra.default.existsSync(`${thisDir}/../tmp/${urlOrPath}`)) {
571
- callback && callback(`${thisDir}/../tmp/${urlOrPath}`);
572
- } else {
573
- console.log(`File not found: ${urlOrPath}`);
574
- process.exit(import_exitCodes.EXIT_CODES.FILE_NOT_FOUND);
575
- }
576
- } catch (err) {
577
- console.log(`File "${urlOrPath}" could no be read: ${err.message}`);
578
- process.exit(import_exitCodes.EXIT_CODES.FILE_NOT_FOUND);
602
+ return tmpFile;
603
+ }
604
+ try {
605
+ if (import_fs_extra.default.existsSync(urlOrPath)) {
606
+ return urlOrPath;
607
+ }
608
+ if (import_fs_extra.default.existsSync(`${thisDir}/../${urlOrPath}`)) {
609
+ return `${thisDir}/../${urlOrPath}`;
610
+ }
611
+ if (import_fs_extra.default.existsSync(`${thisDir}/../tmp/${urlOrPath}`)) {
612
+ return `${thisDir}/../tmp/${urlOrPath}`;
579
613
  }
614
+ console.log(`File not found: ${urlOrPath}`);
615
+ process.exit(import_exitCodes.EXIT_CODES.FILE_NOT_FOUND);
616
+ } catch (err) {
617
+ console.log(`File "${urlOrPath}" could no be read: ${err.message}`);
618
+ process.exit(import_exitCodes.EXIT_CODES.FILE_NOT_FOUND);
580
619
  }
581
620
  }
582
- async function getJson(urlOrPath, agent, callback) {
583
- if (typeof agent === "function") {
584
- callback = agent;
585
- agent = "";
621
+ __name(getFile, "getFile");
622
+ async function getJson(urlOrPath, agent) {
623
+ agent ||= "";
624
+ let result = {};
625
+ if (!urlOrPath) {
626
+ console.log("Empty url!");
627
+ return null;
586
628
  }
587
- agent = agent || "";
588
- let sources = {};
589
- if (urlOrPath && typeof urlOrPath === "object") {
590
- if (callback) {
591
- callback(urlOrPath);
629
+ if (urlOrPath.substring(0, "http://".length) === "http://" || urlOrPath.substring(0, "https://".length) === "https://") {
630
+ try {
631
+ const res = await import_axios.default.get(urlOrPath, {
632
+ headers: { "Accept-Encoding": "gzip", timeout: 1e4, "User-Agent": agent }
633
+ });
634
+ if (res.status !== 200 || !res.data) {
635
+ throw new Error(`Invalid response, body: ${res.data}, status code: ${res.status}`);
636
+ }
637
+ result = res.data;
638
+ return result;
639
+ } catch (e) {
640
+ console.warn(`Cannot download json from ${urlOrPath}. Error: ${e.message}`);
641
+ return null;
592
642
  }
593
- } else if (!urlOrPath) {
594
- console.log("Empty url!");
595
- if (callback) {
596
- callback(null);
643
+ }
644
+ if (import_fs_extra.default.existsSync(urlOrPath)) {
645
+ try {
646
+ result = import_fs_extra.default.readJSONSync(urlOrPath);
647
+ } catch (e) {
648
+ console.log(`Cannot parse json file from ${urlOrPath}. Error: ${e.message}`);
649
+ return null;
597
650
  }
598
- } else {
599
- if (urlOrPath.substring(0, "http://".length) === "http://" || urlOrPath.substring(0, "https://".length) === "https://") {
600
- try {
601
- const res = await import_axios.default.get(urlOrPath, {
602
- headers: { "Accept-Encoding": "gzip", timeout: 1e4, "User-Agent": agent }
603
- });
604
- if (res.status !== 200 || !res.data) {
605
- throw new Error(`Invalid response, body: ${res.data}, status code: ${res.status}`);
606
- }
607
- sources = res.data;
608
- if (callback) {
609
- callback(sources, urlOrPath);
610
- }
611
- } catch (e) {
612
- console.warn(`Cannot download json from ${urlOrPath}. Error: ${e.message}`);
613
- if (callback) {
614
- callback(null, urlOrPath);
615
- }
616
- return;
617
- }
618
- } else {
619
- if (import_fs_extra.default.existsSync(urlOrPath)) {
620
- try {
621
- sources = import_fs_extra.default.readJSONSync(urlOrPath);
622
- } catch (e) {
623
- console.log(`Cannot parse json file from ${urlOrPath}. Error: ${e.message}`);
624
- if (callback) {
625
- callback(null, urlOrPath);
626
- }
627
- return;
628
- }
629
- if (callback) {
630
- callback(sources, urlOrPath);
631
- }
632
- } else if (import_fs_extra.default.existsSync(`${thisDir}/../${urlOrPath}`)) {
633
- try {
634
- sources = import_fs_extra.default.readJSONSync(`${thisDir}/../${urlOrPath}`);
635
- } catch (e) {
636
- console.log(`Cannot parse json file from ${thisDir}/../${urlOrPath}. Error: ${e.message}`);
637
- if (callback) {
638
- callback(null, urlOrPath);
639
- }
640
- return;
641
- }
642
- if (callback) {
643
- callback(sources, urlOrPath);
644
- }
645
- } else if (import_fs_extra.default.existsSync(`${thisDir}/../tmp/${urlOrPath}`)) {
646
- try {
647
- sources = import_fs_extra.default.readJSONSync(`${thisDir}/../tmp/${urlOrPath}`);
648
- } catch (e) {
649
- console.log(`Cannot parse json file from ${thisDir}/../tmp/${urlOrPath}. Error: ${e.message}`);
650
- if (callback) {
651
- callback(null, urlOrPath);
652
- }
653
- return;
654
- }
655
- if (callback) {
656
- callback(sources, urlOrPath);
657
- }
658
- } else {
659
- if (callback) {
660
- callback(null, urlOrPath);
661
- }
662
- }
651
+ return result;
652
+ }
653
+ if (import_fs_extra.default.existsSync(`${thisDir}/../${urlOrPath}`)) {
654
+ try {
655
+ result = import_fs_extra.default.readJSONSync(`${thisDir}/../${urlOrPath}`);
656
+ } catch (e) {
657
+ console.log(`Cannot parse json file from ${thisDir}/../${urlOrPath}. Error: ${e.message}`);
658
+ return null;
663
659
  }
660
+ return result;
664
661
  }
662
+ if (import_fs_extra.default.existsSync(`${thisDir}/../tmp/${urlOrPath}`)) {
663
+ try {
664
+ result = import_fs_extra.default.readJSONSync(`${thisDir}/../tmp/${urlOrPath}`);
665
+ } catch (e) {
666
+ console.log(`Cannot parse json file from ${thisDir}/../tmp/${urlOrPath}. Error: ${e.message}`);
667
+ return null;
668
+ }
669
+ return result;
670
+ }
671
+ return null;
665
672
  }
673
+ __name(getJson, "getJson");
666
674
  async function getJsonAsync(urlOrPath, agent) {
667
- agent = agent || "";
675
+ agent ||= "";
668
676
  let sources = {};
669
677
  if (urlOrPath && typeof urlOrPath === "object") {
670
678
  return urlOrPath;
671
- } else if (!urlOrPath) {
679
+ }
680
+ if (!urlOrPath) {
672
681
  console.log("Empty url!");
673
682
  return null;
674
683
  }
@@ -677,7 +686,7 @@ async function getJsonAsync(urlOrPath, agent) {
677
686
  const result = await (0, import_axios.default)(urlOrPath, {
678
687
  timeout: 1e4,
679
688
  headers: { "User-Agent": agent },
680
- validateStatus: (status) => status !== 200
689
+ validateStatus: /* @__PURE__ */ __name((status) => status !== 200, "validateStatus")
681
690
  });
682
691
  return result.data;
683
692
  } catch (e) {
@@ -713,6 +722,7 @@ async function getJsonAsync(urlOrPath, agent) {
713
722
  return null;
714
723
  }
715
724
  }
725
+ __name(getJsonAsync, "getJsonAsync");
716
726
  function scanDirectory(dirName, list, regExp) {
717
727
  if (import_fs_extra.default.existsSync(dirName)) {
718
728
  let dirs;
@@ -754,6 +764,7 @@ function scanDirectory(dirName, list, regExp) {
754
764
  }
755
765
  }
756
766
  }
767
+ __name(scanDirectory, "scanDirectory");
757
768
  function getInstalledInfo(hostRunningVersion) {
758
769
  const result = {};
759
770
  const fullPath = getControllerDir();
@@ -791,305 +802,169 @@ function getInstalledInfo(hostRunningVersion) {
791
802
  scanDirectory(import_node_path.default.join(fullPath, ".."), result, regExp);
792
803
  return result;
793
804
  }
794
- function getNpmVersion(adapter, callback) {
805
+ __name(getInstalledInfo, "getInstalledInfo");
806
+ async function getNpmVersion(adapter) {
795
807
  adapter = adapter ? `${appName}.${adapter}` : appName;
796
808
  adapter = adapter.toLowerCase();
797
809
  const cliCommand = `npm view ${adapter}@latest version`;
798
- (0, import_node_child_process.exec)(cliCommand, { timeout: 2e3, windowsHide: true }, (error, stdout, _stderr) => {
799
- let version;
800
- if (error) {
801
- if (typeof callback === "function") {
802
- callback(error);
803
- return;
804
- }
805
- } else if (stdout) {
806
- version = import_semver.default.valid(stdout.trim());
807
- }
808
- if (typeof callback === "function") {
809
- callback(null, version);
810
- }
811
- });
810
+ const result = await execAsync(cliCommand, { timeout: 2e3, windowsHide: true });
811
+ let version;
812
+ if (result?.stdout) {
813
+ version = import_semver.default.valid(result.stdout.trim());
814
+ }
815
+ return version || "";
812
816
  }
813
- function getIoPack(sources, name, callback) {
814
- getJson(sources[name].meta, "", (ioPack) => {
815
- const packUrl = sources[name].meta.replace("io-package.json", "package.json");
817
+ __name(getNpmVersion, "getNpmVersion");
818
+ async function getIoPack(sources, name, failCounter) {
819
+ let packSource = sources[name];
820
+ try {
821
+ const ioPack = await getJson(packSource.meta);
822
+ const packUrl = packSource.meta.replace("io-package.json", "package.json");
816
823
  if (!ioPack) {
817
- if (sources._helper) {
818
- sources._helper.failCounter.push(name);
819
- }
820
- if (callback) {
821
- callback(sources, name);
822
- }
823
- } else {
824
- setImmediate(() => {
825
- getJson(packUrl, "", (pack) => {
826
- const version = sources[name].version;
827
- const type = sources[name].type;
828
- if (sources[name].url && name !== "js-controller") {
829
- if (ioPack && ioPack.common) {
830
- sources[name] = (0, import_node.default)(true, sources[name], ioPack.common);
831
- if (type) {
832
- sources[name].type = type;
833
- }
834
- if (pack && pack.licenses && pack.licenses.length) {
835
- if (!sources[name].license) {
836
- sources[name].license = pack.licenses[0].type;
837
- }
838
- if (!sources[name].licenseUrl) {
839
- sources[name].licenseUrl = pack.licenses[0].url;
840
- }
841
- }
842
- }
843
- if (callback) {
844
- callback(sources, name);
845
- }
846
- } else {
847
- if (ioPack && ioPack.common) {
848
- sources[name] = (0, import_node.default)(true, sources[name], ioPack.common);
849
- if (pack && pack.licenses && pack.licenses.length) {
850
- if (!sources[name].license) {
851
- sources[name].license = pack.licenses[0].type;
852
- }
853
- if (!sources[name].licenseUrl) {
854
- sources[name].licenseUrl = pack.licenses[0].url;
855
- }
856
- }
857
- }
858
- if (type) {
859
- sources[name].type = type;
860
- }
861
- if (version) {
862
- sources[name].version = version;
863
- if (callback) {
864
- callback(sources, name);
865
- }
866
- } else {
867
- if (sources[name].meta.substring(0, "http://".length) === "http://" || sources[name].meta.substring(0, "https://".length) === "https://") {
868
- getNpmVersion(name, (_err, version2) => {
869
- if (version2) {
870
- sources[name].version = version2;
871
- } else {
872
- sources[name].version = "npm error";
873
- }
874
- if (callback) {
875
- callback(sources, name);
876
- }
877
- });
878
- } else {
879
- if (callback) {
880
- callback(sources, name);
881
- }
882
- }
883
- }
884
- }
885
- });
886
- });
824
+ failCounter.push(name);
825
+ return;
887
826
  }
888
- });
889
- }
890
- function _getRepositoryFile(sources, path2, callback) {
891
- if (!sources._helper) {
892
- let count = 0;
893
- for (const _name in sources) {
894
- if (!Object.prototype.hasOwnProperty.call(sources, _name)) {
895
- continue;
896
- }
897
- count++;
898
- }
899
- sources._helper = { failCounter: [] };
900
- sources._helper.timeout = setTimeout(() => {
901
- if (sources._helper) {
902
- delete sources._helper;
903
- for (const __name of Object.keys(sources)) {
904
- if (sources[__name].processed !== void 0) {
905
- delete sources[__name].processed;
906
- }
827
+ const pack = await getJson(packUrl);
828
+ const version = packSource.version;
829
+ const type = packSource.type;
830
+ if (packSource.url && name !== "js-controller") {
831
+ if (ioPack?.common) {
832
+ sources[name] = (0, import_node.default)(true, packSource, ioPack.common);
833
+ packSource = sources[name];
834
+ if (type) {
835
+ packSource.type = type;
907
836
  }
908
- if (callback) {
909
- callback(new Error(`Timeout by read all package.json (${count}) seconds`), sources);
837
+ if (pack?.licenses?.length) {
838
+ packSource.license ||= pack.licenses[0].type;
839
+ packSource.licenseUrl ||= pack.licenses[0].url;
910
840
  }
911
- callback = void 0;
912
841
  }
913
- }, count * 1e3);
914
- }
915
- for (const name of Object.keys(sources)) {
916
- if (sources[name].processed || name === "_helper") {
917
- continue;
918
- }
919
- sources[name].processed = true;
920
- if (sources[name].url) {
921
- sources[name].url = findPath(path2, sources[name].url);
922
- }
923
- if (sources[name].meta) {
924
- sources[name].meta = findPath(path2, sources[name].meta);
925
- }
926
- if (sources[name].icon) {
927
- sources[name].icon = findPath(path2, sources[name].icon);
928
- }
929
- if (!sources[name].name && sources[name].meta) {
930
- getIoPack(sources, name, (_ignore) => {
931
- if (sources._helper) {
932
- if (sources._helper.failCounter.length > 10) {
933
- clearTimeout(sources._helper.timeout);
934
- delete sources._helper;
935
- for (const _name of Object.keys(sources)) {
936
- if (sources[_name].processed !== void 0) {
937
- delete sources[_name].processed;
938
- }
939
- }
940
- if (callback) {
941
- callback(new Error("Looks like there is no internet."), sources);
942
- }
943
- callback = void 0;
944
- } else {
945
- setImmediate(() => _getRepositoryFile(sources, path2, callback));
946
- }
947
- }
948
- });
949
842
  return;
950
843
  }
951
- }
952
- if (sources._helper) {
953
- let err;
954
- if (sources._helper.failCounter.length) {
955
- err = new Error(`Following packages cannot be read: ${sources._helper.failCounter.join(", ")}`);
956
- }
957
- clearTimeout(sources._helper.timeout);
958
- delete sources._helper;
959
- for (const __name of Object.keys(sources)) {
960
- if (sources[__name].processed !== void 0) {
961
- delete sources[__name].processed;
844
+ if (ioPack?.common) {
845
+ sources[name] = (0, import_node.default)(true, packSource, ioPack.common);
846
+ packSource = sources[name];
847
+ if (pack?.licenses?.length) {
848
+ packSource.license ||= pack.licenses[0].type;
849
+ packSource.licenseUrl ||= pack.licenses[0].url;
962
850
  }
963
851
  }
964
- if (callback) {
965
- callback(err, sources);
852
+ if (type) {
853
+ packSource.type = type;
966
854
  }
967
- callback = void 0;
968
- }
969
- }
970
- async function _checkRepositoryFileHash(urlOrPath, additionalInfo, callback) {
971
- if (urlOrPath.startsWith("http://") || urlOrPath.startsWith("https://")) {
972
- urlOrPath = urlOrPath.replace(/\.json$/, "-hash.json");
973
- let json = null;
974
- try {
975
- const res = await import_axios.default.get(urlOrPath, { headers: { "Accept-Encoding": "gzip", timeout: 1e4 } });
976
- if (!res.data || res.status !== 200) {
977
- throw new Error(`Invalid response, body: ${res.data}, status code: ${res.status}`);
978
- }
979
- json = res.data;
980
- } catch (e) {
981
- console.warn(`Cannot download json from ${urlOrPath}. Error: ${e.message}`);
855
+ if (version) {
856
+ packSource.version = version;
857
+ return;
982
858
  }
983
- if (json && json.hash) {
984
- if (additionalInfo && additionalInfo.sources && json.hash === additionalInfo.hash) {
985
- console.log("hash unchanged, use cached sources");
986
- callback(null, additionalInfo.sources, json.hash);
987
- } else {
988
- console.log("hash changed or no sources cached => force download of new sources");
989
- callback(null, null, json.hash);
859
+ if (packSource.meta.substring(0, "http://".length) === "http://" || packSource.meta.substring(0, "https://".length) === "https://") {
860
+ try {
861
+ const version2 = await getNpmVersion(name);
862
+ if (version2) {
863
+ packSource.version = version2;
864
+ } else {
865
+ packSource.version = "npm error";
866
+ }
867
+ } catch {
868
+ packSource.version = "npm error";
990
869
  }
991
- } else {
992
- console.log("failed to download new sources, use cached sources");
993
- callback(null, additionalInfo.sources, "");
994
- }
995
- } else {
996
- callback(null, null, 0);
997
- }
998
- }
999
- function getRepositoryFile(urlOrPath, additionalInfo, callback) {
1000
- let sources = {};
1001
- let _path = "";
1002
- if (typeof additionalInfo === "function") {
1003
- callback = additionalInfo;
1004
- additionalInfo = {};
1005
- }
1006
- additionalInfo = additionalInfo || {};
1007
- if (urlOrPath) {
1008
- const parts = urlOrPath.split("/");
1009
- _path = `${parts.splice(0, parts.length - 1).join("/")}/`;
1010
- }
1011
- if (urlOrPath && typeof urlOrPath === "object") {
1012
- if (typeof callback === "function") {
1013
- callback(null, urlOrPath);
1014
870
  }
1015
- } else if (!urlOrPath) {
1016
- try {
1017
- const controllerDir = getControllerDir();
1018
- if (controllerDir) {
1019
- sources = import_fs_extra.default.readJSONSync(import_node_path.default.join(controllerDir, getDefaultDataDir(), "sources.json"));
871
+ } catch (e) {
872
+ console.error(`Cannot prepare repository entry for ${name}: ${e.message}`);
873
+ }
874
+ }
875
+ __name(getIoPack, "getIoPack");
876
+ async function _getRepositoryFile(sources, path2 = "") {
877
+ const names = Object.keys(sources).filter((name) => name !== "_helper");
878
+ const failCounter = [];
879
+ let aborted = false;
880
+ let timeout;
881
+ const timeoutPromise = new Promise((resolve) => {
882
+ timeout = setTimeout(() => {
883
+ aborted = true;
884
+ resolve(new Error(`Timeout by read all package.json (${names.length}) seconds`));
885
+ }, names.length * 1e4);
886
+ });
887
+ const processPromise = (async () => {
888
+ for (const name of names) {
889
+ if (aborted) {
890
+ return null;
1020
891
  }
1021
- } catch {
1022
- sources = {};
1023
- }
1024
- try {
1025
- const controllerDir = getControllerDir();
1026
- if (controllerDir) {
1027
- const sourcesDist = import_fs_extra.default.readJSONSync(import_node_path.default.join(controllerDir, "conf", "sources-dist.json"));
1028
- sources = (0, import_node.default)(true, sourcesDist, sources);
892
+ const source = sources[name];
893
+ if (source.url) {
894
+ source.url = findPath(path2, source.url);
1029
895
  }
1030
- } catch {
1031
- }
1032
- for (const s of Object.keys(sources)) {
1033
- if (additionalInfo[s] && additionalInfo[s].published) {
1034
- sources[s].published = additionalInfo[s].published;
896
+ if (source.meta) {
897
+ source.meta = findPath(path2, source.meta);
1035
898
  }
1036
- }
1037
- _getRepositoryFile(sources, _path, (err) => {
1038
- if (err) {
1039
- console.error(`[${(/* @__PURE__ */ new Date()).toString()}] ${err.message}`);
899
+ if (source.icon) {
900
+ source.icon = findPath(path2, source.icon);
1040
901
  }
1041
- if (typeof callback === "function") {
1042
- callback(err, sources);
902
+ if (!source.name && source.meta) {
903
+ await getIoPack(sources, name, failCounter);
904
+ if (failCounter.length > 10) {
905
+ return new Error("Looks like there is no internet.");
906
+ }
1043
907
  }
1044
- });
1045
- } else {
1046
- let agent = "";
1047
- if (additionalInfo) {
1048
- agent = `${additionalInfo.name}, RND: ${additionalInfo.randomID || randomID}, Node:${additionalInfo.node}, V:${additionalInfo.controller}`;
1049
908
  }
1050
- _checkRepositoryFileHash(urlOrPath, additionalInfo, (err, sources2, actualSourcesHash) => {
1051
- if (!err && sources2) {
1052
- typeof callback === "function" && callback(err, sources2, actualSourcesHash);
1053
- } else {
1054
- getJson(urlOrPath, agent, (sources3) => {
1055
- if (sources3) {
1056
- for (const s of Object.keys(sources3)) {
1057
- if (additionalInfo[s] && additionalInfo[s].published) {
1058
- sources3[s].published = additionalInfo[s].published;
1059
- }
1060
- }
1061
- setImmediate(() => _getRepositoryFile(sources3, _path, (err2) => {
1062
- err2 && console.error(`[${(/* @__PURE__ */ new Date()).toString()}] ${err2.message}`);
1063
- typeof callback === "function" && callback(err2, sources3, actualSourcesHash);
1064
- }));
1065
- } else {
1066
- console.log(`failed to download new sources, ${additionalInfo.sources ? "use cached sources" : "no cached sources available"}`);
1067
- return (0, import_maybeCallback.maybeCallbackWithError)(callback, `Cannot read "${urlOrPath}"`, additionalInfo.sources, "");
1068
- }
1069
- });
1070
- }
1071
- });
909
+ return failCounter.length ? new Error(`Following packages cannot be read: ${failCounter.join(", ")}`) : null;
910
+ })();
911
+ try {
912
+ return await Promise.race([processPromise, timeoutPromise]);
913
+ } finally {
914
+ clearTimeout(timeout);
1072
915
  }
1073
916
  }
917
+ __name(_getRepositoryFile, "_getRepositoryFile");
918
+ async function getRepositoryFile() {
919
+ let sources = {};
920
+ let controllerDir;
921
+ try {
922
+ controllerDir = getControllerDir();
923
+ if (controllerDir) {
924
+ sources = import_fs_extra.default.readJSONSync(import_node_path.default.join(controllerDir, getDefaultDataDir(), "sources.json"));
925
+ }
926
+ } catch {
927
+ sources = {};
928
+ }
929
+ try {
930
+ if (controllerDir) {
931
+ const sourcesDist = import_fs_extra.default.readJSONSync(import_node_path.default.join(controllerDir, "conf", "sources-dist.json"));
932
+ sources = (0, import_node.default)(true, sourcesDist, sources);
933
+ }
934
+ } catch {
935
+ }
936
+ const error = await _getRepositoryFile(sources);
937
+ if (error) {
938
+ console.error(`[${(/* @__PURE__ */ new Date()).toString()}] ${error.message}`);
939
+ }
940
+ if (!error || Object.keys(sources).length > 0) {
941
+ return sources;
942
+ }
943
+ throw error;
944
+ }
945
+ __name(getRepositoryFile, "getRepositoryFile");
1074
946
  async function getRepositoryFileAsync(url2, hash, force, _actualRepo) {
1075
- let _hash;
1076
- let data;
947
+ let hashResponse;
948
+ let data = null;
1077
949
  if (url2.startsWith("http://") || url2.startsWith("https://")) {
1078
950
  try {
1079
- _hash = await (0, import_axios.default)({ url: url2.replace(/\.json$/, "-hash.json"), timeout: 1e4 });
951
+ hashResponse = await (0, import_axios.default)({
952
+ url: url2.replace(/\.json$/, `-${HASH_TEXT}.json`),
953
+ timeout: 1e4
954
+ });
1080
955
  } catch {
1081
956
  }
1082
- if (_actualRepo && !force && hash && _hash?.data && _hash.data.hash === hash) {
957
+ if (_actualRepo && !force && hash && hashResponse?.data?.hash === hash) {
1083
958
  data = _actualRepo;
1084
959
  } else {
1085
960
  const agent = `${appName}, RND: ${randomID}, Node:${process.version}, V:${require2("@iobroker/js-controller-common/package.json").version}`;
1086
961
  try {
1087
- data = await (0, import_axios.default)({
962
+ const response = await (0, import_axios.default)({
1088
963
  url: url2,
1089
964
  timeout: 1e4,
1090
965
  headers: { "User-Agent": agent }
1091
966
  });
1092
- data = data.data;
967
+ data = response.data;
1093
968
  } catch (e) {
1094
969
  throw new Error(`Cannot download repository file from "${url2}": ${e.message}`);
1095
970
  }
@@ -1107,10 +982,11 @@ async function getRepositoryFileAsync(url2, hash, force, _actualRepo) {
1107
982
  }
1108
983
  return {
1109
984
  json: data,
1110
- changed: _hash?.data ? hash !== _hash.data.hash : true,
1111
- hash: _hash?.data ? _hash.data.hash : ""
985
+ changed: hashResponse?.data ? hash !== hashResponse.data.hash : true,
986
+ hash: hashResponse?.data ? hashResponse.data.hash : ""
1112
987
  };
1113
988
  }
989
+ __name(getRepositoryFileAsync, "getRepositoryFileAsync");
1114
990
  async function sendDiagInfo(obj) {
1115
991
  const objStr = JSON.stringify(obj);
1116
992
  console.log(`Send diag info: ${objStr}`);
@@ -1126,6 +1002,7 @@ async function sendDiagInfo(obj) {
1126
1002
  console.log(`Cannot send diag info: ${e.message}`);
1127
1003
  }
1128
1004
  }
1005
+ __name(sendDiagInfo, "sendDiagInfo");
1129
1006
  function getAdapterDir(adapter) {
1130
1007
  if (adapter.toLowerCase().startsWith(`${appNameLowerCase}.`)) {
1131
1008
  adapter = adapter.substring(appName.length + 1);
@@ -1157,6 +1034,7 @@ function getAdapterDir(adapter) {
1157
1034
  parts.pop();
1158
1035
  return parts.join("/");
1159
1036
  }
1037
+ __name(getAdapterDir, "getAdapterDir");
1160
1038
  function getHostName() {
1161
1039
  if (process.env.IOB_HOSTNAME) {
1162
1040
  return process.env.IOB_HOSTNAME;
@@ -1169,42 +1047,21 @@ function getHostName() {
1169
1047
  return import_node_os.default.hostname();
1170
1048
  }
1171
1049
  }
1172
- function getSystemNpmVersion(callback) {
1173
- const { exec: exec2 } = require2("node:child_process");
1050
+ __name(getHostName, "getHostName");
1051
+ async function getSystemNpmVersion() {
1174
1052
  const newEnv = Object.assign({}, process.env);
1175
- newEnv.PATH = (newEnv.PATH || newEnv.Path || newEnv.path).split(import_node_path.default.delimiter).filter((dir) => {
1053
+ newEnv.PATH = (newEnv.PATH || newEnv.Path || newEnv.path || "").split(import_node_path.default.delimiter).filter((dir) => {
1176
1054
  dir = dir.toLowerCase();
1177
1055
  return !dir.includes("iobroker") || !dir.includes(import_node_path.default.join("node_modules", ".bin"));
1178
1056
  }).join(import_node_path.default.delimiter);
1179
- try {
1180
- let timeout = setTimeout(() => {
1181
- timeout = null;
1182
- if (callback) {
1183
- callback(new Error("timeout"));
1184
- callback = void 0;
1185
- }
1186
- }, 1e4);
1187
- exec2("npm -v", { encoding: "utf8", env: newEnv, windowsHide: true }, (error, stdout) => {
1188
- if (timeout) {
1189
- clearTimeout(timeout);
1190
- timeout = null;
1191
- }
1192
- if (stdout) {
1193
- stdout = import_semver.default.valid(stdout.trim());
1194
- }
1195
- if (callback) {
1196
- callback(error, stdout);
1197
- callback = void 0;
1198
- }
1199
- });
1200
- } catch (e) {
1201
- if (callback) {
1202
- callback(e);
1203
- callback = void 0;
1204
- }
1057
+ const result = await execAsync("npm -v", { env: newEnv, timeout: 1e4 });
1058
+ let version;
1059
+ if (result.stdout) {
1060
+ version = import_semver.default.valid(result.stdout.trim());
1205
1061
  }
1062
+ return version || null;
1206
1063
  }
1207
- const getSystemNpmVersionAsync = promisify(getSystemNpmVersion);
1064
+ __name(getSystemNpmVersion, "getSystemNpmVersion");
1208
1065
  async function detectPackageManagerWithFallback(cwd) {
1209
1066
  try {
1210
1067
  return await (0, import_pak.detectPackageManager)(typeof cwd === "string" ? (
@@ -1224,6 +1081,7 @@ async function detectPackageManagerWithFallback(cwd) {
1224
1081
  pak.cwd = cwd || ioBrokerRootDir;
1225
1082
  return pak;
1226
1083
  }
1084
+ __name(detectPackageManagerWithFallback, "detectPackageManagerWithFallback");
1227
1085
  async function installNodeModule(npmUrl, options = {}) {
1228
1086
  const pak = await detectPackageManagerWithFallback(options.cwd);
1229
1087
  if (!options.debug) {
@@ -1247,6 +1105,7 @@ async function installNodeModule(npmUrl, options = {}) {
1247
1105
  }
1248
1106
  return pak.install([npmUrl], installOpts);
1249
1107
  }
1108
+ __name(installNodeModule, "installNodeModule");
1250
1109
  async function uninstallNodeModule(packageName, options = {}) {
1251
1110
  const pak = await detectPackageManagerWithFallback(options.cwd);
1252
1111
  if (!options.debug) {
@@ -1263,6 +1122,7 @@ async function uninstallNodeModule(packageName, options = {}) {
1263
1122
  }
1264
1123
  return pak.uninstall([packageName]);
1265
1124
  }
1125
+ __name(uninstallNodeModule, "uninstallNodeModule");
1266
1126
  async function rebuildNodeModules(options = {}) {
1267
1127
  const pak = await detectPackageManagerWithFallback(options.cwd);
1268
1128
  if (!options.debug) {
@@ -1279,6 +1139,7 @@ async function rebuildNodeModules(options = {}) {
1279
1139
  }
1280
1140
  return pak.rebuild(options.module ? [options.module] : void 0);
1281
1141
  }
1142
+ __name(rebuildNodeModules, "rebuildNodeModules");
1282
1143
  async function getDiskInfo() {
1283
1144
  const platform = process.platform;
1284
1145
  if (diskusage) {
@@ -1323,6 +1184,7 @@ async function getDiskInfo() {
1323
1184
  }
1324
1185
  return null;
1325
1186
  }
1187
+ __name(getDiskInfo, "getDiskInfo");
1326
1188
  function getCertificateInfo(cert) {
1327
1189
  let info = null;
1328
1190
  if (!cert) {
@@ -1357,6 +1219,7 @@ function getCertificateInfo(cert) {
1357
1219
  return null;
1358
1220
  }
1359
1221
  }
1222
+ __name(getCertificateInfo, "getCertificateInfo");
1360
1223
  const MAX_CERT_VALIDITY = 365 * 24 * 60 * 60 * 1e3;
1361
1224
  function generateDefaultCertificates() {
1362
1225
  const pki = import_node_forge.default.pki;
@@ -1429,6 +1292,7 @@ function generateDefaultCertificates() {
1429
1292
  defaultPublic: pem_cert
1430
1293
  };
1431
1294
  }
1295
+ __name(generateDefaultCertificates, "generateDefaultCertificates");
1432
1296
  function makeid(length) {
1433
1297
  let result = "";
1434
1298
  const characters = "abcdef0123456789";
@@ -1438,6 +1302,7 @@ function makeid(length) {
1438
1302
  }
1439
1303
  return result;
1440
1304
  }
1305
+ __name(makeid, "makeid");
1441
1306
  async function getHostInfo(objects) {
1442
1307
  if (!diskusage) {
1443
1308
  try {
@@ -1450,11 +1315,11 @@ async function getHostInfo(objects) {
1450
1315
  const allRepos = {};
1451
1316
  if (systemRepos?.native?.repositories && systemConfig) {
1452
1317
  const repos = Array.isArray(systemConfig.common.activeRepo) ? systemConfig.common.activeRepo : [systemConfig.common.activeRepo];
1453
- repos.filter((repo) => systemRepos.native.repositories[repo] && systemRepos.native.repositories[repo].json).forEach((repo) => Object.assign(allRepos, systemRepos.native.repositories[repo].json));
1318
+ repos.filter((repo) => systemRepos.native.repositories[repo]?.json).forEach((repo) => Object.assign(allRepos, systemRepos.native.repositories[repo].json));
1454
1319
  }
1455
1320
  if (!npmVersion) {
1456
1321
  try {
1457
- npmVersion = await getSystemNpmVersionAsync();
1322
+ npmVersion = await getSystemNpmVersion() || "";
1458
1323
  } catch (e) {
1459
1324
  console.error(`Cannot get NPM version: ${e.message}`);
1460
1325
  }
@@ -1474,7 +1339,7 @@ async function getHostInfo(objects) {
1474
1339
  time: dateObj.getTime(),
1475
1340
  timeOffset: dateObj.getTimezoneOffset(),
1476
1341
  NPM: npmVersion,
1477
- "adapters count": Object.keys(allRepos).length
1342
+ "adapters count": Object.keys(allRepos).filter((id) => id !== "_repoInfo").length
1478
1343
  };
1479
1344
  if (data.Platform === "win32") {
1480
1345
  data.Platform = "Windows";
@@ -1494,6 +1359,7 @@ async function getHostInfo(objects) {
1494
1359
  }
1495
1360
  return data;
1496
1361
  }
1362
+ __name(getHostInfo, "getHostInfo");
1497
1363
  function getControllerDir() {
1498
1364
  const possibilities = ["iobroker.js-controller", "ioBroker.js-controller"];
1499
1365
  for (const pkg of possibilities) {
@@ -1525,12 +1391,15 @@ function getControllerDir() {
1525
1391
  }
1526
1392
  throw new Error("Could not determine controller directory");
1527
1393
  }
1394
+ __name(getControllerDir, "getControllerDir");
1528
1395
  function getRootDir() {
1529
1396
  return import_node_path.default.join(getControllerDir(), "..", "..");
1530
1397
  }
1398
+ __name(getRootDir, "getRootDir");
1531
1399
  function isDevServerInstallation() {
1532
1400
  return !!require2.main?.path.includes(`${import_node_path.default.sep}.dev-server${import_node_path.default.sep}`);
1533
1401
  }
1402
+ __name(isDevServerInstallation, "isDevServerInstallation");
1534
1403
  function getDefaultDataDir() {
1535
1404
  let envDataDir = process.env[`${appName.toUpperCase()}_DATA_DIR`];
1536
1405
  if (envDataDir) {
@@ -1544,6 +1413,7 @@ function getDefaultDataDir() {
1544
1413
  }
1545
1414
  return import_node_path.default.join("..", "..", `${appNameLowerCase}-data/`);
1546
1415
  }
1416
+ __name(getDefaultDataDir, "getDefaultDataDir");
1547
1417
  function getConfigFileName() {
1548
1418
  let envDataDir = process.env[`${appName.toUpperCase()}_DATA_DIR`];
1549
1419
  if (envDataDir) {
@@ -1569,6 +1439,7 @@ function getConfigFileName() {
1569
1439
  }
1570
1440
  return prodConfigFile;
1571
1441
  }
1442
+ __name(getConfigFileName, "getConfigFileName");
1572
1443
  function sliceArgs(argsObj, startIndex = 0) {
1573
1444
  if (startIndex === null || startIndex === void 0) {
1574
1445
  startIndex = 0;
@@ -1579,6 +1450,7 @@ function sliceArgs(argsObj, startIndex = 0) {
1579
1450
  }
1580
1451
  return ret;
1581
1452
  }
1453
+ __name(sliceArgs, "sliceArgs");
1582
1454
  function promisify(fn, context, returnArgNames) {
1583
1455
  return function() {
1584
1456
  const args = sliceArgs(arguments);
@@ -1618,6 +1490,7 @@ function promisify(fn, context, returnArgNames) {
1618
1490
  });
1619
1491
  };
1620
1492
  }
1493
+ __name(promisify, "promisify");
1621
1494
  function promisifyNoError(fn, context, returnArgNames) {
1622
1495
  return function() {
1623
1496
  const args = sliceArgs(arguments);
@@ -1650,6 +1523,7 @@ function promisifyNoError(fn, context, returnArgNames) {
1650
1523
  });
1651
1524
  };
1652
1525
  }
1526
+ __name(promisifyNoError, "promisifyNoError");
1653
1527
  async function _setQualityForStates(states, keys, quality) {
1654
1528
  for (const key of keys) {
1655
1529
  try {
@@ -1658,6 +1532,7 @@ async function _setQualityForStates(states, keys, quality) {
1658
1532
  }
1659
1533
  }
1660
1534
  }
1535
+ __name(_setQualityForStates, "_setQualityForStates");
1661
1536
  function setQualityForInstance(objects, states, namespace, q) {
1662
1537
  return new Promise((resolve, reject) => {
1663
1538
  objects.getObjectView("system", "state", {
@@ -1687,6 +1562,7 @@ function setQualityForInstance(objects, states, namespace, q) {
1687
1562
  });
1688
1563
  });
1689
1564
  }
1565
+ __name(setQualityForInstance, "setQualityForInstance");
1690
1566
  function pattern2RegEx(pattern) {
1691
1567
  pattern = (pattern || "").toString();
1692
1568
  if (!isValidPattern(pattern)) {
@@ -1697,10 +1573,12 @@ function pattern2RegEx(pattern) {
1697
1573
  pattern = pattern.replace(/[-/\\^$+?.()|[\]{}]/g, "\\$&").replace(/\*/g, ".*");
1698
1574
  return (startsWithWildcard ? "" : "^") + pattern + (endsWithWildcard ? "" : "$");
1699
1575
  }
1576
+ __name(pattern2RegEx, "pattern2RegEx");
1700
1577
  function isValidPattern(pattern) {
1701
1578
  pattern = pattern.replace(/\*/g, "");
1702
1579
  return !FORBIDDEN_CHARS.test(pattern);
1703
1580
  }
1581
+ __name(isValidPattern, "isValidPattern");
1704
1582
  function captureStackTrace(wrapperName) {
1705
1583
  if (typeof wrapperName !== "string") {
1706
1584
  wrapperName = "captureStackTrace";
@@ -1721,6 +1599,7 @@ function captureStackTrace(wrapperName) {
1721
1599
  }
1722
1600
  return "";
1723
1601
  }
1602
+ __name(captureStackTrace, "captureStackTrace");
1724
1603
  function appendStackTrace(str) {
1725
1604
  if (typeof str !== "string") {
1726
1605
  str = String(str);
@@ -1730,6 +1609,7 @@ function appendStackTrace(str) {
1730
1609
  }
1731
1610
  return str + captureStackTrace("appendStackTrace");
1732
1611
  }
1612
+ __name(appendStackTrace, "appendStackTrace");
1733
1613
  function encryptLegacy(key, value) {
1734
1614
  let result = "";
1735
1615
  for (let i = 0; i < value.length; i++) {
@@ -1737,6 +1617,7 @@ function encryptLegacy(key, value) {
1737
1617
  }
1738
1618
  return result;
1739
1619
  }
1620
+ __name(encryptLegacy, "encryptLegacy");
1740
1621
  function decryptLegacy(key, value) {
1741
1622
  let result = "";
1742
1623
  for (let i = 0; i < value.length; i++) {
@@ -1744,6 +1625,7 @@ function decryptLegacy(key, value) {
1744
1625
  }
1745
1626
  return result;
1746
1627
  }
1628
+ __name(decryptLegacy, "decryptLegacy");
1747
1629
  function encrypt(key, value) {
1748
1630
  if (!/^[0-9a-f]{48}$/.test(key)) {
1749
1631
  return encryptLegacy(key, value);
@@ -1753,6 +1635,7 @@ function encrypt(key, value) {
1753
1635
  const encrypted = Buffer.concat([cipher.update(value), cipher.final()]);
1754
1636
  return `$/aes-192-cbc:${iv.toString("hex")}:${encrypted.toString("hex")}`;
1755
1637
  }
1638
+ __name(encrypt, "encrypt");
1756
1639
  function decrypt(key, value) {
1757
1640
  if (!value.startsWith(`$/aes-192-cbc:`) || !/^[0-9a-f]{48}$/.test(key)) {
1758
1641
  return decryptLegacy(key, value);
@@ -1764,12 +1647,15 @@ function decrypt(key, value) {
1764
1647
  const decrypted = Buffer.concat([decipher.update(encryptedText), decipher.final()]);
1765
1648
  return decrypted.toString();
1766
1649
  }
1650
+ __name(decrypt, "decrypt");
1767
1651
  function isObject(it) {
1768
1652
  return Object.prototype.toString.call(it) === "[object Object]";
1769
1653
  }
1654
+ __name(isObject, "isObject");
1770
1655
  function isArray(it) {
1771
1656
  return Array.isArray(it);
1772
1657
  }
1658
+ __name(isArray, "isArray");
1773
1659
  function measureEventLoopLag(ms, cb) {
1774
1660
  let start = hrtime();
1775
1661
  let timeout = setTimeout(check, ms);
@@ -1777,16 +1663,19 @@ function measureEventLoopLag(ms, cb) {
1777
1663
  function check() {
1778
1664
  clearTimeout(timeout);
1779
1665
  const t = hrtime();
1780
- cb && cb(Math.max(0, t - start - ms));
1666
+ cb?.(Math.max(0, t - start - ms));
1781
1667
  start = t;
1782
1668
  timeout = setTimeout(check, ms);
1783
1669
  timeout.unref();
1784
1670
  }
1671
+ __name(check, "check");
1785
1672
  function hrtime() {
1786
1673
  const t = process.hrtime();
1787
1674
  return t[0] * 1e3 + t[1] / 1e6;
1788
1675
  }
1676
+ __name(hrtime, "hrtime");
1789
1677
  }
1678
+ __name(measureEventLoopLag, "measureEventLoopLag");
1790
1679
  function formatAliasValue(options) {
1791
1680
  const { sourceCommon, sourceId, targetCommon, targetId, state, logger } = options;
1792
1681
  const logNamespace = options.logNamespace ? `${options.logNamespace} ` : "";
@@ -1837,10 +1726,9 @@ function formatAliasValue(options) {
1837
1726
  state.val = (0, import_aliasProcessing.applyAliasAutoScaling)({ state, sourceCommon, targetCommon });
1838
1727
  return state;
1839
1728
  }
1729
+ __name(formatAliasValue, "formatAliasValue");
1840
1730
  async function removeIdFromAllEnums(objects, id, allEnums) {
1841
- if (!allEnums) {
1842
- allEnums = await getAllEnums(objects);
1843
- }
1731
+ allEnums ||= await getAllEnums(objects);
1844
1732
  let error = null;
1845
1733
  for (const [enumId, enumObj] of Object.entries(allEnums)) {
1846
1734
  const idx = enumObj.common.members ? enumObj.common.members.indexOf(id) : -1;
@@ -1850,9 +1738,7 @@ async function removeIdFromAllEnums(objects, id, allEnums) {
1850
1738
  await objects.setObjectAsync(enumId, enumObj);
1851
1739
  allEnums[enumId] = enumObj;
1852
1740
  } catch (err) {
1853
- if (!error) {
1854
- error = err;
1855
- }
1741
+ error ||= err;
1856
1742
  }
1857
1743
  }
1858
1744
  }
@@ -1860,6 +1746,7 @@ async function removeIdFromAllEnums(objects, id, allEnums) {
1860
1746
  throw error;
1861
1747
  }
1862
1748
  }
1749
+ __name(removeIdFromAllEnums, "removeIdFromAllEnums");
1863
1750
  function parseDependencies(dependencies) {
1864
1751
  let adapters = {};
1865
1752
  if (Array.isArray(dependencies)) {
@@ -1877,6 +1764,7 @@ function parseDependencies(dependencies) {
1877
1764
  }
1878
1765
  return adapters;
1879
1766
  }
1767
+ __name(parseDependencies, "parseDependencies");
1880
1768
  function validateGeneralObjectProperties(obj, extend2) {
1881
1769
  if (!obj || obj.type === void 0 && !extend2) {
1882
1770
  throw new Error(`obj.type has to exist`);
@@ -1944,8 +1832,9 @@ function validateGeneralObjectProperties(obj, extend2) {
1944
1832
  throw new Error(`obj.common.min (${obj.common.min}) needs to be less than or equal to obj.common.max (${obj.common.max})`);
1945
1833
  }
1946
1834
  }
1947
- if (obj.common.def !== void 0 && obj.common.def !== null) {
1948
- if (!(obj.common.type === "mixed" && typeof obj.common.def !== "object" || obj.common.type !== "object" && obj.common.type === typeof obj.common.def || obj.common.type === "array" && typeof obj.common.def === "string" || obj.common.type === "json" && typeof obj.common.def === "string" || obj.common.type === "object" && typeof obj.common.def === "string")) {
1835
+ if (obj.common.def != null) {
1836
+ if (!(obj.common.type === "mixed" && typeof obj.common.def !== "object" || obj.common.type !== "object" && obj.common.type === typeof obj.common.def || obj.common.type === "array" && typeof obj.common.def === "string" || // @ts-expect-error deprecated
1837
+ obj.common.type === "json" && typeof obj.common.def === "string" || obj.common.type === "object" && typeof obj.common.def === "string")) {
1949
1838
  if (["object", "json", "array"].includes(obj.common.type)) {
1950
1839
  throw new Error(`Default value has to be stringified but received type "${typeof obj.common.def}"`);
1951
1840
  } else {
@@ -1967,14 +1856,15 @@ function validateGeneralObjectProperties(obj, extend2) {
1967
1856
  if (obj.common.desc !== void 0 && typeof obj.common.desc !== "string" && typeof obj.common.desc !== "object") {
1968
1857
  throw new Error(`obj.common.desc has an invalid type! Expected "string" or "object", received "${typeof obj.common.desc}"`);
1969
1858
  }
1970
- if (obj.type === "state" && obj.common.custom !== void 0 && obj.common.custom !== null && !isObject(obj.common.custom)) {
1859
+ if (obj.type === "state" && obj.common.custom != null && !isObject(obj.common.custom)) {
1971
1860
  throw new Error(`obj.common.custom has an invalid type! Expected "object", received "${typeof obj.common.custom}"`);
1972
1861
  }
1973
- if (obj.common.states !== null && // we allow null for deletion TODO: implement https://github.com/ioBroker/ioBroker.js-controller/issues/1735
1974
- obj.common.states !== void 0 && !isObject(obj.common.states) && !Array.isArray(obj.common.states)) {
1862
+ if (obj.common.states != null && // we allow null for deletion TODO: implement https://github.com/ioBroker/ioBroker.js-controller/issues/1735
1863
+ !isObject(obj.common.states) && !Array.isArray(obj.common.states)) {
1975
1864
  throw new Error(`obj.common.states has an invalid type! Expected "object", received "${typeof obj.common.states}"`);
1976
1865
  }
1977
1866
  }
1867
+ __name(validateGeneralObjectProperties, "validateGeneralObjectProperties");
1978
1868
  async function getAllInstances(adapters, objects) {
1979
1869
  const instances = [];
1980
1870
  for (let i = 0; i < adapters.length; i++) {
@@ -1988,14 +1878,13 @@ async function getAllInstances(adapters, objects) {
1988
1878
  instances.push(inst[j]);
1989
1879
  }
1990
1880
  }
1991
- } else {
1992
- if (!instances.includes(adapters[i])) {
1993
- instances.push(adapters[i]);
1994
- }
1881
+ } else if (!instances.includes(adapters[i])) {
1882
+ instances.push(adapters[i]);
1995
1883
  }
1996
1884
  }
1997
1885
  return instances;
1998
1886
  }
1887
+ __name(getAllInstances, "getAllInstances");
1999
1888
  async function getAllEnums(objects) {
2000
1889
  const allEnums = {};
2001
1890
  const res = await objects.getObjectViewAsync("system", "enum", {
@@ -2009,6 +1898,7 @@ async function getAllEnums(objects) {
2009
1898
  }
2010
1899
  return allEnums;
2011
1900
  }
1901
+ __name(getAllEnums, "getAllEnums");
2012
1902
  async function getInstances(adapter, objects, withObjects) {
2013
1903
  const arr = await objects.getObjectListAsync({
2014
1904
  startkey: `system.adapter.${adapter}.`,
@@ -2029,6 +1919,7 @@ async function getInstances(adapter, objects, withObjects) {
2029
1919
  }
2030
1920
  return instances;
2031
1921
  }
1922
+ __name(getInstances, "getInstances");
2032
1923
  function execAsync(command, execOptions) {
2033
1924
  const defaultOptions = {
2034
1925
  // we do not want to show the node.js window on Windows
@@ -2036,8 +1927,45 @@ function execAsync(command, execOptions) {
2036
1927
  // And we want to capture stdout/stderr
2037
1928
  encoding: "utf8"
2038
1929
  };
2039
- return (0, import_promisify_child_process.exec)(command, { ...defaultOptions, ...execOptions });
1930
+ return new Promise((resolve, reject) => {
1931
+ (0, import_node_child_process.exec)(command, { ...defaultOptions, ...execOptions }, (error, stdout, stderr) => {
1932
+ if (error) {
1933
+ reject(stderr ? new Error(stderr.toString()) : error);
1934
+ } else {
1935
+ resolve({
1936
+ stderr: stderr?.toString(),
1937
+ stdout: stdout?.toString()
1938
+ });
1939
+ }
1940
+ });
1941
+ });
2040
1942
  }
1943
+ __name(execAsync, "execAsync");
1944
+ function execFileAsync(file, args, execOptions) {
1945
+ const defaultOptions = {
1946
+ // we do not want to show the node.js window on Windows
1947
+ windowsHide: true,
1948
+ // And we want to capture stdout/stderr
1949
+ encoding: "utf8"
1950
+ };
1951
+ return new Promise((resolve, reject) => {
1952
+ (0, import_node_child_process.execFile)(file, [...args], { ...defaultOptions, ...execOptions }, (error, stdout, stderr) => {
1953
+ if (error) {
1954
+ const failure = error;
1955
+ if (stderr) {
1956
+ failure.message = stderr.toString();
1957
+ }
1958
+ reject(failure);
1959
+ } else {
1960
+ resolve({
1961
+ stderr: stderr?.toString(),
1962
+ stdout: stdout?.toString()
1963
+ });
1964
+ }
1965
+ });
1966
+ });
1967
+ }
1968
+ __name(execFileAsync, "execFileAsync");
2041
1969
  function pipeLinewise(input, output) {
2042
1970
  const rl = (0, import_node_readline.createInterface)({
2043
1971
  input,
@@ -2052,6 +1980,7 @@ function pipeLinewise(input, output) {
2052
1980
  rl.on("error", () => {
2053
1981
  });
2054
1982
  }
1983
+ __name(pipeLinewise, "pipeLinewise");
2055
1984
  async function isAdapterEsmModule(adapter) {
2056
1985
  const adapterDir = getAdapterDir(adapter);
2057
1986
  if (!adapterDir) {
@@ -2060,6 +1989,7 @@ async function isAdapterEsmModule(adapter) {
2060
1989
  const packJson = await import_fs_extra.default.readJSON(import_node_path.default.join(adapterDir, "package.json"), { encoding: "utf-8" });
2061
1990
  return packJson.type === "module";
2062
1991
  }
1992
+ __name(isAdapterEsmModule, "isAdapterEsmModule");
2063
1993
  async function resolveAdapterMainFile(adapter) {
2064
1994
  const adapterDir = getAdapterDir(adapter);
2065
1995
  if (!adapterDir) {
@@ -2088,6 +2018,7 @@ async function resolveAdapterMainFile(adapter) {
2088
2018
  }
2089
2019
  throw new Error(`Could not find main file of ${adapter}`);
2090
2020
  }
2021
+ __name(resolveAdapterMainFile, "resolveAdapterMainFile");
2091
2022
  function getDefaultNodeArgs(mainFile) {
2092
2023
  const ret = [];
2093
2024
  if (mainFile.endsWith(".ts")) {
@@ -2098,6 +2029,7 @@ function getDefaultNodeArgs(mainFile) {
2098
2029
  }
2099
2030
  return ret;
2100
2031
  }
2032
+ __name(getDefaultNodeArgs, "getDefaultNodeArgs");
2101
2033
  function getDefaultRequireResolvePaths(callerModule) {
2102
2034
  const ret = [
2103
2035
  // This is the default for require.resolve
@@ -2108,10 +2040,12 @@ function getDefaultRequireResolvePaths(callerModule) {
2108
2040
  }
2109
2041
  return ret;
2110
2042
  }
2043
+ __name(getDefaultRequireResolvePaths, "getDefaultRequireResolvePaths");
2111
2044
  const shortGithubUrlRegex = /^(?<user>[^/]+)\/(?<repo>[^#]+)(?:#(?<commit>.+))?$/;
2112
2045
  function isShortGithubUrl(url2) {
2113
2046
  return shortGithubUrlRegex.test(url2);
2114
2047
  }
2048
+ __name(isShortGithubUrl, "isShortGithubUrl");
2115
2049
  function parseShortGithubUrl(url2) {
2116
2050
  const match = shortGithubUrlRegex.exec(url2);
2117
2051
  if (!match || !match.groups) {
@@ -2123,10 +2057,12 @@ function parseShortGithubUrl(url2) {
2123
2057
  commit: match.groups.commit
2124
2058
  };
2125
2059
  }
2060
+ __name(parseShortGithubUrl, "parseShortGithubUrl");
2126
2061
  const githubPathnameRegex = /^\/(?<user>[^/]+)\/(?<repo>[^/]*?)(?:\.git)?(?:\/(?:tree|tarball|archive)\/(?<commit>.*?)(?:\.(?:zip|gz|tar\.gz))?)?$/;
2127
2062
  function isGithubPathname(pathname) {
2128
2063
  return githubPathnameRegex.test(pathname);
2129
2064
  }
2065
+ __name(isGithubPathname, "isGithubPathname");
2130
2066
  function parseGithubPathname(pathname) {
2131
2067
  const match = githubPathnameRegex.exec(pathname);
2132
2068
  if (!match || !match.groups) {
@@ -2138,6 +2074,7 @@ function parseGithubPathname(pathname) {
2138
2074
  commit: match.groups.commit
2139
2075
  };
2140
2076
  }
2077
+ __name(parseGithubPathname, "parseGithubPathname");
2141
2078
  function removePreservedProperties(preserve, oldObj, newObj) {
2142
2079
  for (const prop of Object.keys(preserve)) {
2143
2080
  if (isObject(preserve[prop]) && isObject(newObj[prop])) {
@@ -2155,6 +2092,7 @@ function removePreservedProperties(preserve, oldObj, newObj) {
2155
2092
  }
2156
2093
  }
2157
2094
  }
2095
+ __name(removePreservedProperties, "removePreservedProperties");
2158
2096
  function getInstanceIndicatorObjects(namespace, adapterCommon) {
2159
2097
  const id = `system.adapter.${namespace}`;
2160
2098
  return [
@@ -2357,27 +2295,29 @@ function getInstanceIndicatorObjects(namespace, adapterCommon) {
2357
2295
  }
2358
2296
  ];
2359
2297
  }
2298
+ __name(getInstanceIndicatorObjects, "getInstanceIndicatorObjects");
2360
2299
  function getLogger(log) {
2361
2300
  if (!log) {
2362
2301
  log = {
2363
- silly: function(_msg) {
2364
- },
2365
- debug: function(_msg) {
2366
- },
2367
- info: function(_msg) {
2368
- },
2369
- warn: function(msg) {
2302
+ silly: /* @__PURE__ */ __name(function(_msg) {
2303
+ }, "silly"),
2304
+ debug: /* @__PURE__ */ __name(function(_msg) {
2305
+ }, "debug"),
2306
+ info: /* @__PURE__ */ __name(function(_msg) {
2307
+ }, "info"),
2308
+ warn: /* @__PURE__ */ __name(function(msg) {
2370
2309
  console.log(msg);
2371
- },
2372
- error: function(msg) {
2310
+ }, "warn"),
2311
+ error: /* @__PURE__ */ __name(function(msg) {
2373
2312
  console.log(msg);
2374
- }
2313
+ }, "error")
2375
2314
  };
2376
2315
  } else if (!log.silly) {
2377
2316
  log.silly = log.debug;
2378
2317
  }
2379
2318
  return log;
2380
2319
  }
2320
+ __name(getLogger, "getLogger");
2381
2321
  async function setExecutableCapabilities(execPath, capabilities, modeEffective, modePermitted, modeInherited) {
2382
2322
  if (import_node_os.default.platform() !== "linux") {
2383
2323
  return;
@@ -2417,6 +2357,7 @@ async function setExecutableCapabilities(execPath, capabilities, modeEffective,
2417
2357
  await execAsync(`sudo setcap ${capabilitiesStr}${modes} ${execPath}`);
2418
2358
  }
2419
2359
  }
2360
+ __name(setExecutableCapabilities, "setExecutableCapabilities");
2420
2361
  async function _readLicenses(login, password2) {
2421
2362
  const config = {
2422
2363
  headers: { Authorization: `Basic ${Buffer.from(`${login}:${password2}`).toString("base64")}` },
@@ -2439,12 +2380,13 @@ async function _readLicenses(login, password2) {
2439
2380
  }
2440
2381
  }
2441
2382
  }
2383
+ __name(_readLicenses, "_readLicenses");
2442
2384
  async function updateLicenses(objects, login, password2) {
2443
2385
  if (login && password2) {
2444
- return _readLicenses(login, password2);
2386
+ return await _readLicenses(login, password2);
2445
2387
  }
2446
2388
  const systemLicenses = await objects.getObjectAsync("system.licenses");
2447
- if (systemLicenses && systemLicenses.native && systemLicenses.native.password && systemLicenses.native.login) {
2389
+ if (systemLicenses?.native?.password && systemLicenses.native.login) {
2448
2390
  try {
2449
2391
  const systemConfig = await objects.getObjectAsync("system.config");
2450
2392
  let password3;
@@ -2469,7 +2411,7 @@ async function updateLicenses(objects, login, password2) {
2469
2411
  return licenses;
2470
2412
  } catch (err) {
2471
2413
  if (err.message.includes("Authentication required") || err.message.includes("Cannot decode password:")) {
2472
- if (systemLicenses && systemLicenses.native && systemLicenses.native.licenses && systemLicenses.native.licenses.length) {
2414
+ if (systemLicenses?.native?.licenses?.length) {
2473
2415
  systemLicenses.native.licenses = [];
2474
2416
  systemLicenses.native.readTime = (/* @__PURE__ */ new Date()).toISOString();
2475
2417
  await objects.setObjectAsync("system.licenses", systemLicenses);
@@ -2478,7 +2420,7 @@ async function updateLicenses(objects, login, password2) {
2478
2420
  throw err;
2479
2421
  }
2480
2422
  } else {
2481
- if (systemLicenses && systemLicenses.native && systemLicenses.native.licenses && systemLicenses.native.licenses.length) {
2423
+ if (systemLicenses?.native?.licenses?.length) {
2482
2424
  systemLicenses.native.licenses = [];
2483
2425
  systemLicenses.native.readTime = (/* @__PURE__ */ new Date()).toISOString();
2484
2426
  await objects.setObjectAsync("system.licenses", systemLicenses);
@@ -2486,6 +2428,7 @@ async function updateLicenses(objects, login, password2) {
2486
2428
  throw new Error("No password or login");
2487
2429
  }
2488
2430
  }
2431
+ __name(updateLicenses, "updateLicenses");
2489
2432
  function compressFileGZip(inputFilename, outputFilename, options = {}) {
2490
2433
  const { deleteInput = false } = options;
2491
2434
  return new Promise((resolve, reject) => {
@@ -2513,6 +2456,7 @@ function compressFileGZip(inputFilename, outputFilename, options = {}) {
2513
2456
  input.pipe(compress).pipe(output);
2514
2457
  });
2515
2458
  }
2459
+ __name(compressFileGZip, "compressFileGZip");
2516
2460
  function validateDataDir(dataDir) {
2517
2461
  if (!import_node_path.default.isAbsolute(dataDir)) {
2518
2462
  dataDir = import_node_path.default.normalize(import_node_path.default.join(getControllerDir(), dataDir));
@@ -2525,12 +2469,14 @@ function validateDataDir(dataDir) {
2525
2469
  reason: isValid ? "Valid data directory" : "Data directory is not allowed to point into node_modules folder"
2526
2470
  };
2527
2471
  }
2472
+ __name(validateDataDir, "validateDataDir");
2528
2473
  function maybeArrayToString(maybeArr) {
2529
2474
  if (Array.isArray(maybeArr)) {
2530
2475
  return JSON.stringify(maybeArr);
2531
2476
  }
2532
2477
  return maybeArr;
2533
2478
  }
2479
+ __name(maybeArrayToString, "maybeArrayToString");
2534
2480
  function getDNSResolutionOrder() {
2535
2481
  let dnsOrder = "ipv4first";
2536
2482
  try {
@@ -2544,25 +2490,31 @@ function getDNSResolutionOrder() {
2544
2490
  }
2545
2491
  return dnsOrder;
2546
2492
  }
2493
+ __name(getDNSResolutionOrder, "getDNSResolutionOrder");
2547
2494
  function isLocalAddress(ip) {
2548
2495
  const localAddresses = ["::1", "127.0.0.1", "localhost"];
2549
2496
  return localAddresses.includes(ip);
2550
2497
  }
2498
+ __name(isLocalAddress, "isLocalAddress");
2551
2499
  function isListenAllAddress(ip) {
2552
2500
  return ip === "0.0.0.0" || ip === "::";
2553
2501
  }
2502
+ __name(isListenAllAddress, "isListenAllAddress");
2554
2503
  function getLocalAddress() {
2555
2504
  const dnsOrder = getDNSResolutionOrder();
2556
2505
  return dnsOrder === "ipv4first" ? "127.0.0.1" : "::1";
2557
2506
  }
2507
+ __name(getLocalAddress, "getLocalAddress");
2558
2508
  function getListenAllAddress() {
2559
2509
  const dnsOrder = getDNSResolutionOrder();
2560
2510
  return dnsOrder === "ipv4first" ? "0.0.0.0" : "::";
2561
2511
  }
2512
+ __name(getListenAllAddress, "getListenAllAddress");
2562
2513
  function ensureDNSOrder() {
2563
2514
  const dnsOrder = getDNSResolutionOrder();
2564
2515
  (0, import_node_dns.setDefaultResultOrder)(dnsOrder);
2565
2516
  }
2517
+ __name(ensureDNSOrder, "ensureDNSOrder");
2566
2518
  async function isIoBrokerInstalledAsSystemd() {
2567
2519
  try {
2568
2520
  const res = await execAsync("systemctl status iobroker");
@@ -2571,6 +2523,7 @@ async function isIoBrokerInstalledAsSystemd() {
2571
2523
  return false;
2572
2524
  }
2573
2525
  }
2526
+ __name(isIoBrokerInstalledAsSystemd, "isIoBrokerInstalledAsSystemd");
2574
2527
  function getHostObject(oldObj) {
2575
2528
  const hostname = getHostName();
2576
2529
  const ioPackage = import_fs_extra.default.readJSONSync(import_node_path.default.join(getControllerDir(), "io-package.json"));
@@ -2627,9 +2580,11 @@ function getHostObject(oldObj) {
2627
2580
  }
2628
2581
  return newObj;
2629
2582
  }
2583
+ __name(getHostObject, "getHostObject");
2630
2584
  function getPidsFileName() {
2631
2585
  return import_node_path.default.join(getControllerDir(), "pids.txt");
2632
2586
  }
2587
+ __name(getPidsFileName, "getPidsFileName");
2633
2588
  async function getPids() {
2634
2589
  let pids = [];
2635
2590
  try {
@@ -2642,13 +2597,99 @@ async function getPids() {
2642
2597
  }
2643
2598
  return pids;
2644
2599
  }
2600
+ __name(getPids, "getPids");
2645
2601
  function isLogLevel(level) {
2646
2602
  return ["silly", "debug", "info", "warn", "error"].includes(level);
2647
2603
  }
2604
+ __name(isLogLevel, "isLogLevel");
2648
2605
  async function getControllerPid() {
2649
2606
  const pids = await getPids();
2650
2607
  return pids.pop();
2651
2608
  }
2609
+ __name(getControllerPid, "getControllerPid");
2610
+ function isProcessRunning(pid) {
2611
+ if (!Number.isInteger(pid) || pid <= 0) {
2612
+ return false;
2613
+ }
2614
+ try {
2615
+ process.kill(pid, 0);
2616
+ return true;
2617
+ } catch (e) {
2618
+ return e.code === "EPERM";
2619
+ }
2620
+ }
2621
+ __name(isProcessRunning, "isProcessRunning");
2622
+ function isControllerCommandLine(commandLine) {
2623
+ const command = commandLine.toLowerCase();
2624
+ return (
2625
+ // On POSIX the title the running controller gives itself replaces the command line
2626
+ command.startsWith(`${appNameLowerCase}.js-controller`) || // "node <path>/controller.js", as started by the CLI, the service or the installer
2627
+ /(^|[\s"'/\\])controller\.js(["'\s]|$)/.test(command) || // The entry point started directly
2628
+ /[/\\](iobroker\.js-controller|controller)[/\\]build[/\\](esm|cjs)[/\\]main\.js/.test(command)
2629
+ );
2630
+ }
2631
+ __name(isControllerCommandLine, "isControllerCommandLine");
2632
+ async function isForeignProcess(pid) {
2633
+ if (!Number.isInteger(pid) || pid <= 0) {
2634
+ return false;
2635
+ }
2636
+ if (pid === process.pid) {
2637
+ return true;
2638
+ }
2639
+ try {
2640
+ if (import_node_os.default.platform() === "win32") {
2641
+ const { stdout: stdout2 } = await execFileAsync(
2642
+ "powershell.exe",
2643
+ [
2644
+ "-NoProfile",
2645
+ "-NonInteractive",
2646
+ "-Command",
2647
+ `[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}' | Select-Object Name, CommandLine | ConvertTo-Json -Compress`
2648
+ ],
2649
+ // PowerShell needs seconds for its cold start alone, and WMI answers slowly on a
2650
+ // busy machine - exactly the situation this runs in, right after a crash or a
2651
+ // power loss. A timeout is answered with "cannot inspect", which keeps the
2652
+ // controller from starting, so it is better to wait than to give up early.
2653
+ { timeout: 3e4 }
2654
+ );
2655
+ const output = (stdout2 || "").trim();
2656
+ if (!output) {
2657
+ return false;
2658
+ }
2659
+ const { Name, CommandLine } = JSON.parse(output);
2660
+ if (!Name) {
2661
+ return false;
2662
+ }
2663
+ if (!Name.toLowerCase().startsWith("node")) {
2664
+ return true;
2665
+ }
2666
+ return CommandLine ? !isControllerCommandLine(CommandLine) : false;
2667
+ }
2668
+ const { stdout } = await execFileAsync("ps", ["-p", String(pid), "-o", "args="], { timeout: 1e4 });
2669
+ const commandLine = (stdout || "").trim();
2670
+ if (!commandLine) {
2671
+ return false;
2672
+ }
2673
+ return !isControllerCommandLine(commandLine);
2674
+ } catch (e) {
2675
+ console.warn(`Cannot inspect process ${pid}, assuming it belongs to the controller: ${e.message}`);
2676
+ return false;
2677
+ }
2678
+ }
2679
+ __name(isForeignProcess, "isForeignProcess");
2680
+ const RESOURCE_TYPE_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
2681
+ function isValidUsedResourceType(type) {
2682
+ return typeof type === "string" && RESOURCE_TYPE_PATTERN.test(type);
2683
+ }
2684
+ __name(isValidUsedResourceType, "isValidUsedResourceType");
2685
+ function hasRegisteredResourceShape(entry) {
2686
+ if (typeof entry !== "object" || entry === null) {
2687
+ return false;
2688
+ }
2689
+ const candidate = entry;
2690
+ return isValidUsedResourceType(candidate.type) && typeof candidate.instance === "string" && !!candidate.instance && typeof candidate.ts === "number" && typeof candidate.isBlocked === "boolean" && typeof candidate.data === "object" && candidate.data !== null && !Array.isArray(candidate.data);
2691
+ }
2692
+ __name(hasRegisteredResourceShape, "hasRegisteredResourceShape");
2652
2693
  // Annotate the CommonJS export names for ESM import in node:
2653
2694
  0 && (module.exports = {
2654
2695
  ERRORS,
@@ -2667,6 +2708,7 @@ async function getControllerPid() {
2667
2708
  encrypt,
2668
2709
  ensureDNSOrder,
2669
2710
  execAsync,
2711
+ execFileAsync,
2670
2712
  findIPs,
2671
2713
  formatAliasValue,
2672
2714
  generateDefaultCertificates,
@@ -2700,6 +2742,7 @@ async function getControllerPid() {
2700
2742
  getRepositoryFile,
2701
2743
  getRepositoryFileAsync,
2702
2744
  getRootDir,
2745
+ hasRegisteredResourceShape,
2703
2746
  installNodeModule,
2704
2747
  isAdapterEsmModule,
2705
2748
  isArray,
@@ -2707,6 +2750,7 @@ async function getControllerPid() {
2707
2750
  isDevInstallation,
2708
2751
  isDevServerInstallation,
2709
2752
  isDocker,
2753
+ isForeignProcess,
2710
2754
  isGithubPathname,
2711
2755
  isHostRunning,
2712
2756
  isIoBrokerInstalledAsSystemd,
@@ -2714,9 +2758,11 @@ async function getControllerPid() {
2714
2758
  isLocalAddress,
2715
2759
  isLogLevel,
2716
2760
  isObject,
2761
+ isProcessRunning,
2717
2762
  isShortGithubUrl,
2718
2763
  isSingleHost,
2719
2764
  isValidPattern,
2765
+ isValidUsedResourceType,
2720
2766
  maybeArrayToString,
2721
2767
  measureEventLoopLag,
2722
2768
  parseDependencies,