@iobroker/repochecker 5.17.9 → 5.18.0

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.
package/README.md CHANGED
@@ -25,6 +25,10 @@ Example:
25
25
  Placeholder for the next version (at the beginning of the line):
26
26
  ### **WORK IN PROGRESS**
27
27
  -->
28
+ ### 5.18.0 (2026-06-05)
29
+
30
+ - (mcm1957) Support for objectStructure chek added
31
+
28
32
  ### 5.17.9 (2026-06-04)
29
33
 
30
34
  - (mcm1957) Require release-script 5.2.1.
@@ -1,3 +1,72 @@
1
+ 'use strict';
2
+
3
+ const ROOT_OBJECT_SCHEMA = {
4
+ _id: 'string',
5
+ type: 'string',
6
+ common: 'object',
7
+ native: 'object',
8
+ from: 'string',
9
+ ts: 'number',
10
+ acl: 'object',
11
+ user: 'string',
12
+ };
13
+
14
+ const ALLOWED_OBJECT_TYPES = new Set([
15
+ 'state',
16
+ 'channel',
17
+ 'device',
18
+ 'enum',
19
+ 'host',
20
+ 'adapter',
21
+ 'instance',
22
+ 'meta',
23
+ 'config',
24
+ 'script',
25
+ 'user',
26
+ 'group',
27
+ 'chart',
28
+ 'folder',
29
+ 'schedule',
30
+ 'design',
31
+ ]);
32
+
33
+ const HIERARCHY_TYPES = new Set(['device', 'channel', 'state', 'folder']);
34
+
35
+ const VALID_STATE_TYPES = new Set([
36
+ 'array',
37
+ 'boolean',
38
+ 'file',
39
+ 'json',
40
+ 'mixed',
41
+ 'multistate',
42
+ 'number',
43
+ 'object',
44
+ 'string',
45
+ ]);
46
+
47
+ // Keys are prefixed with "common." to reflect the actual object path being validated.
48
+ const STATE_SCHEMA = {
49
+ 'common.min': { types: ['number'], onlyForTypes: ['number'] },
50
+ 'common.max': { types: ['number'], onlyForTypes: ['number'] },
51
+ 'common.step': { types: ['number'], onlyForTypes: ['number'] },
52
+ 'common.unit': { types: ['string'] },
53
+ 'common.def': { any: true, matchesCommonType: true },
54
+ 'common.defAck': { types: ['boolean'] },
55
+ 'common.desc': { types: ['string'] },
56
+ 'common.read': { types: ['boolean'], required: true },
57
+ 'common.write': { types: ['boolean'], required: true },
58
+ 'common.role': { types: ['string'], required: true, role: true },
59
+ 'common.states': { types: ['object'] },
60
+ 'common.workingID': { any: true },
61
+ 'common.custom': { any: true },
62
+ 'common.type': { types: ['string'], required: true },
63
+ 'common.name': { required: true, name: true },
64
+ 'common.expert': { types: ['boolean'] },
65
+ 'common.dontDelete':{ types: ['boolean'] },
66
+ 'common.color': { types: ['string'] },
67
+ 'common.icon': { types: ['string'] },
68
+ };
69
+
1
70
  const STATE_ROLE_RULES = {
2
71
  'adapter.messagebox': {
3
72
  types: ['object'],
@@ -1123,5 +1192,10 @@ const STATE_ROLE_RULES = {
1123
1192
  };
1124
1193
 
1125
1194
  module.exports = {
1195
+ ROOT_OBJECT_SCHEMA,
1196
+ ALLOWED_OBJECT_TYPES,
1197
+ HIERARCHY_TYPES,
1198
+ VALID_STATE_TYPES,
1199
+ STATE_SCHEMA,
1126
1200
  STATE_ROLE_RULES,
1127
1201
  };
@@ -0,0 +1,429 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * objectStructure.js
5
+ *
6
+ * Validates an ioBroker object dump (already parsed into a JS object) against
7
+ * the schema rules defined in config_StateRoles.js.
8
+ *
9
+ * Does NOT perform any file I/O and does NOT log anything.
10
+ * Returns a structured result object; callers decide how to present it.
11
+ *
12
+ * Exported API:
13
+ *
14
+ * checkObjectStructure(objects, adapter)
15
+ *
16
+ * @param {object} objects - Parsed content of an ioBroker object-dump JSON file.
17
+ * Keys are object ids, values are ioBroker object records.
18
+ * @param {string} adapter - Adapter name (used only for id-prefix validation).
19
+ * @returns {CheckResult}
20
+ *
21
+ * CheckResult shape:
22
+ * {
23
+ * adapter: string, // adapter name passed in
24
+ * objectCount: number, // total number of objects checked
25
+ * errors: [ { code, message } ], // severity: error (rule violations)
26
+ * warnings: [ { code, message } ], // severity: warning (style / convention)
27
+ * }
28
+ */
29
+
30
+ const {
31
+ ROOT_OBJECT_SCHEMA,
32
+ ALLOWED_OBJECT_TYPES,
33
+ HIERARCHY_TYPES,
34
+ VALID_STATE_TYPES,
35
+ STATE_SCHEMA,
36
+ STATE_ROLE_RULES,
37
+ } = require('./config_StateRoles');
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // One-time setup: strip ambiguous read/write constraints from roles whose
41
+ // directionality is context-dependent and should not be enforced globally.
42
+ // ---------------------------------------------------------------------------
43
+ const ROLE_RULES = (() => {
44
+ // Shallow-clone each entry so we never mutate the imported config object.
45
+ const cloned = {};
46
+ for (const [role, rule] of Object.entries(STATE_ROLE_RULES)) {
47
+ cloned[role] = { ...rule };
48
+ }
49
+ for (const ambiguousRole of ['button', 'button.long']) {
50
+ if (cloned[ambiguousRole]) {
51
+ delete cloned[ambiguousRole].read;
52
+ delete cloned[ambiguousRole].write;
53
+ }
54
+ }
55
+ return cloned;
56
+ })();
57
+
58
+ const FORBIDDEN_ID_CHARS_REGEX = /[^._\-/ :!#$%&()+=@^{}|~\p{Ll}\p{Lu}\p{Nd}]+/gu;
59
+ const ID_SUGGESTION_REGEX = /[^a-zA-Z0-9_,-.]+/g;
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // Internal helpers
63
+ // ---------------------------------------------------------------------------
64
+
65
+ function getValueType(value) {
66
+ if (Array.isArray(value)) return 'array';
67
+ if (value === null) return 'null';
68
+ return typeof value;
69
+ }
70
+
71
+ function isPlainObject(value) {
72
+ return getValueType(value) === 'object';
73
+ }
74
+
75
+ function isStringOrI18nObject(value) {
76
+ if (typeof value === 'string') return true;
77
+ if (!isPlainObject(value)) return false;
78
+ const vals = Object.values(value);
79
+ return vals.length > 0 && vals.every(v => typeof v === 'string');
80
+ }
81
+
82
+ function matchesCommonType(value, commonType) {
83
+ switch (commonType) {
84
+ case 'mixed': return true;
85
+ case 'array': return Array.isArray(value);
86
+ case 'boolean': return typeof value === 'boolean';
87
+ case 'number': return typeof value === 'number' && Number.isFinite(value);
88
+ case 'object': return isPlainObject(value);
89
+ case 'string':
90
+ case 'file':
91
+ case 'json': return typeof value === 'string';
92
+ case 'multistate': return ['string', 'number', 'boolean'].includes(typeof value);
93
+ default: return false;
94
+ }
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Role-rule lookup (built once per call via createRoleRuleMaps)
99
+ // ---------------------------------------------------------------------------
100
+
101
+ function createRoleRuleMaps() {
102
+ const exactRules = new Map();
103
+ const prefixRules = [];
104
+
105
+ for (const [role, rule] of Object.entries(ROLE_RULES)) {
106
+ if (role.endsWith('.')) {
107
+ prefixRules.push({ prefix: role, rule });
108
+ } else {
109
+ exactRules.set(role, rule);
110
+ }
111
+ }
112
+
113
+ return { exactRules, prefixRules };
114
+ }
115
+
116
+ function getRoleRule(role, { exactRules, prefixRules }) {
117
+ if (exactRules.has(role)) return exactRules.get(role);
118
+
119
+ for (const { prefix, rule } of prefixRules) {
120
+ if (role.startsWith(prefix)) return rule;
121
+ }
122
+
123
+ // ".setting." is a valid infix that should fall through to the base role
124
+ if (role.includes('.setting.')) {
125
+ const base = role.replace('.setting.', '.');
126
+ if (exactRules.has(base)) return exactRules.get(base);
127
+ for (const { prefix, rule } of prefixRules) {
128
+ if (base.startsWith(prefix)) return rule;
129
+ }
130
+ }
131
+
132
+ return null;
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Collector — replaces the logger; stores issues as plain objects
137
+ // ---------------------------------------------------------------------------
138
+
139
+ function createCollector() {
140
+ const errors = [];
141
+ const warnings = [];
142
+
143
+ return {
144
+ error: (code, message) => errors.push({ code, message }),
145
+ warning: (code, message) => warnings.push({ code, message }),
146
+ get errors() { return errors; },
147
+ get warnings() { return warnings; },
148
+ };
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // Validation — common block of a state object
153
+ // ---------------------------------------------------------------------------
154
+
155
+ /**
156
+ * Validates the `common` sub-object of a state against STATE_SCHEMA.
157
+ *
158
+ * STATE_SCHEMA keys carry a "common." prefix (e.g. "common.role") to
159
+ * document the full object path. The bare field name is derived by
160
+ * stripping that prefix before reading values from `common`.
161
+ */
162
+ function validateStateCommon(stateId, common, collector, roleRuleMaps) {
163
+ if (!isPlainObject(common)) {
164
+ collector.error('E1001', `Object "${stateId}": common must be an object.`);
165
+ return;
166
+ }
167
+
168
+ // Allowed bare keys derived from schema
169
+ const schemaKeys = new Set(
170
+ Object.keys(STATE_SCHEMA).map(k => k.slice('common.'.length))
171
+ );
172
+
173
+ const unsupportedKeys = Object.keys(common).filter(k => !schemaKeys.has(k));
174
+ if (unsupportedKeys.length > 0) {
175
+ collector.error('E1002',
176
+ `Object "${stateId}": common contains unsupported keys: ${unsupportedKeys.join(', ')}.`);
177
+ }
178
+
179
+ for (const [schemaKey, schema] of Object.entries(STATE_SCHEMA)) {
180
+ const bareKey = schemaKey.slice('common.'.length);
181
+ const hasValue = Object.prototype.hasOwnProperty.call(common, bareKey);
182
+
183
+ if (schema.required && !hasValue) {
184
+ collector.error('E1003',
185
+ `Object "${stateId}": common is missing required key "${schemaKey}".`);
186
+ continue;
187
+ }
188
+
189
+ if (!hasValue) continue;
190
+
191
+ const value = common[bareKey];
192
+
193
+ if (schema.types && !schema.types.includes(getValueType(value))) {
194
+ collector.error('E1004',
195
+ `Object "${stateId}": "${schemaKey}" must be of type ${schema.types.join(' or ')}.`);
196
+ continue;
197
+ }
198
+
199
+ if (schema.onlyForTypes && !schema.onlyForTypes.includes(common.type)) {
200
+ collector.error('E1005',
201
+ `Object "${stateId}": "${schemaKey}" is only allowed for common.type = ${schema.onlyForTypes.join(' or ')}.`);
202
+ }
203
+
204
+ if (schema.matchesCommonType && common.type && !matchesCommonType(value, common.type)) {
205
+ collector.error('E1006',
206
+ `Object "${stateId}": "${schemaKey}" value must match common.type "${common.type}".`);
207
+ }
208
+
209
+ if (schema.name && !isStringOrI18nObject(value)) {
210
+ collector.error('E1007',
211
+ `Object "${stateId}": "${schemaKey}" must be a string or an i18n object.`);
212
+ }
213
+
214
+ if (schema.role) {
215
+ const roleRule = getRoleRule(value, roleRuleMaps);
216
+ if (!roleRule) {
217
+ collector.error('E1008',
218
+ `Object "${stateId}": unknown role "${value}".`);
219
+ continue;
220
+ }
221
+
222
+ if (Array.isArray(roleRule.types) && common.type && !roleRule.types.includes(common.type)) {
223
+ collector.error('E1009',
224
+ `Object "${stateId}": role "${value}" does not support common.type "${common.type}".`);
225
+ }
226
+
227
+ if (typeof roleRule.read === 'boolean' && common.read !== roleRule.read) {
228
+ collector.error('E1010',
229
+ `Object "${stateId}": role "${value}" requires common.read = ${roleRule.read}.`);
230
+ }
231
+
232
+ if (typeof roleRule.write === 'boolean' && common.write !== roleRule.write) {
233
+ collector.error('E1011',
234
+ `Object "${stateId}": role "${value}" requires common.write = ${roleRule.write}.`);
235
+ }
236
+ }
237
+ }
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // Validation — hierarchy order
242
+ // ---------------------------------------------------------------------------
243
+
244
+ function validateHierarchyObjectOrder(objectsById, idsToCheck, collector) {
245
+ for (const objectId of idsToCheck) {
246
+ const levels = objectId.split('.');
247
+ const chain = [];
248
+
249
+ for (let i = 3; i <= levels.length; i++) {
250
+ const levelId = levels.slice(0, i).join('.');
251
+ const levelObj = objectsById[levelId];
252
+ if (levelObj) chain.push({ id: levelId, type: levelObj.type });
253
+ }
254
+
255
+ const hasHierarchyMember = chain.some(e => HIERARCHY_TYPES.has(e.type));
256
+ if (hasHierarchyMember && chain.some(e => !HIERARCHY_TYPES.has(e.type))) {
257
+ collector.error('E2001',
258
+ `Object "${objectId}": hierarchy contains non-hierarchy object types.`);
259
+ }
260
+
261
+ if (chain.filter(e => e.type === 'device').length > 1) {
262
+ collector.error('E2002',
263
+ `Object "${objectId}": hierarchy contains more than one device.`);
264
+ }
265
+
266
+ const firstChannelIdx = chain.findIndex(e => e.type === 'channel');
267
+ if (firstChannelIdx !== -1 &&
268
+ chain.slice(firstChannelIdx + 1).some(e => e.type === 'device')) {
269
+ collector.error('E2003',
270
+ `Object "${objectId}": hierarchy contains a device after a channel.`);
271
+ }
272
+
273
+ for (let i = 0; i < chain.length - 1; i++) {
274
+ if (chain[i].type === 'state') {
275
+ collector.error('E2004',
276
+ `Object "${objectId}": state object "${chain[i].id}" has children.`);
277
+ break;
278
+ }
279
+ }
280
+ }
281
+ }
282
+
283
+ // ---------------------------------------------------------------------------
284
+ // Validation — full object dump
285
+ // ---------------------------------------------------------------------------
286
+
287
+ function validateObjectDump(objects, adapter, collector) {
288
+ if (!isPlainObject(objects)) {
289
+ collector.error('E3001', 'Input must be a plain JSON object at root level.');
290
+ return [];
291
+ }
292
+
293
+ const entries = Object.entries(objects);
294
+
295
+ // Every root key must match its record's _id
296
+ for (const [rootKey, rootObj] of entries) {
297
+ if (!isPlainObject(rootObj) || rootObj._id !== rootKey) {
298
+ collector.error('E3002',
299
+ `Root object "${rootKey}": invalid — expected a plain object with _id === "${rootKey}".`);
300
+ }
301
+ }
302
+
303
+ if (collector.errors.length > 0) {
304
+ collector.error('E3003',
305
+ 'Input is not a valid ioBroker object dump — processing aborted.');
306
+ return [];
307
+ }
308
+
309
+ const roleRuleMaps = createRoleRuleMaps();
310
+ const relevantIds = [];
311
+
312
+ for (const [objectId, objectData] of entries) {
313
+
314
+ // --- Root-schema key presence and types ---
315
+ for (const [requiredKey, expectedType] of Object.entries(ROOT_OBJECT_SCHEMA)) {
316
+ if (!Object.prototype.hasOwnProperty.call(objectData, requiredKey)) {
317
+ collector.error('E3004',
318
+ `Object "${objectId}": missing required key "${requiredKey}".`);
319
+ continue;
320
+ }
321
+ const actualType = getValueType(objectData[requiredKey]);
322
+ if (actualType !== expectedType) {
323
+ collector.error('E3005',
324
+ `Object "${objectId}": key "${requiredKey}" must be type ${expectedType}, got ${actualType}.`);
325
+ }
326
+ }
327
+
328
+ // --- No extra root keys ---
329
+ const unsupportedKeys = Object.keys(objectData)
330
+ .filter(k => !Object.prototype.hasOwnProperty.call(ROOT_OBJECT_SCHEMA, k));
331
+ if (unsupportedKeys.length > 0) {
332
+ collector.error('E3006',
333
+ `Object "${objectId}": contains unsupported root keys: ${unsupportedKeys.join(', ')}.`);
334
+ }
335
+
336
+ // --- Known object type ---
337
+ if (!ALLOWED_OBJECT_TYPES.has(objectData.type)) {
338
+ collector.error('E3007',
339
+ `Object "${objectId}": unknown type "${objectData.type}".`);
340
+ }
341
+
342
+ if (HIERARCHY_TYPES.has(objectData.type)) {
343
+ relevantIds.push(objectId);
344
+ }
345
+
346
+ // --- Object id character checks ---
347
+ FORBIDDEN_ID_CHARS_REGEX.lastIndex = 0;
348
+ if (FORBIDDEN_ID_CHARS_REGEX.test(objectId)) {
349
+ const sanitized = objectId.replace(FORBIDDEN_ID_CHARS_REGEX, '');
350
+ collector.error('E3008',
351
+ `Object id "${objectId}": contains forbidden characters. Suggested id: "${sanitized}".`);
352
+ }
353
+
354
+ const suggestionMatches = objectId.match(ID_SUGGESTION_REGEX);
355
+ if (suggestionMatches) {
356
+ const uniqueChars = [...new Set(suggestionMatches.join('').split(''))].join('');
357
+ collector.warning('W3001',
358
+ `Object id "${objectId}": contains non [a-zA-Z0-9_,-] characters (${uniqueChars}). Consider removing them.`);
359
+ }
360
+ }
361
+
362
+ // --- Every hierarchy object must have all intermediate parents present ---
363
+ for (const objectId of relevantIds) {
364
+ const levels = objectId.split('.');
365
+ // Skip adapter name (index 0) and instance number (index 1)
366
+ for (let i = 3; i < levels.length; i++) {
367
+ const prefix = levels.slice(0, i).join('.');
368
+ if (!Object.prototype.hasOwnProperty.call(objects, prefix)) {
369
+ collector.error('E3009',
370
+ `Object "${objectId}": missing intermediate object "${prefix}".`);
371
+ }
372
+ }
373
+ }
374
+
375
+ validateHierarchyObjectOrder(objects, relevantIds, collector);
376
+
377
+ // --- State-specific validation ---
378
+ for (const objectId of relevantIds) {
379
+ const objectData = objects[objectId];
380
+ if (objectData.type !== 'state') continue;
381
+
382
+ const common = objectData.common;
383
+
384
+ if (!isPlainObject(common) ||
385
+ !Object.prototype.hasOwnProperty.call(common, 'type')) {
386
+ collector.error('E3010',
387
+ `Object "${objectId}": state must define common.type.`);
388
+ continue;
389
+ }
390
+
391
+ if (!VALID_STATE_TYPES.has(common.type)) {
392
+ collector.error('E3011',
393
+ `Object "${objectId}": invalid common.type "${common.type}".`);
394
+ }
395
+
396
+ validateStateCommon(objectId, common, collector, roleRuleMaps);
397
+ }
398
+
399
+ return relevantIds;
400
+ }
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // Public API
404
+ // ---------------------------------------------------------------------------
405
+
406
+ /**
407
+ * Checks an ioBroker object dump for structural and schema errors.
408
+ *
409
+ * @param {object} objects - Parsed JSON content of the object-dump file.
410
+ * @param {string} adapter - Adapter name used for contextual validation.
411
+ * @returns {{ adapter: string, objectCount: number,
412
+ * errors: {code: string, message: string}[],
413
+ * warnings: {code: string, message: string}[] }}
414
+ */
415
+ function checkObjectStructure(objects, adapter) {
416
+ const collector = createCollector();
417
+
418
+ const objectCount = isPlainObject(objects) ? Object.keys(objects).length : 0;
419
+ validateObjectDump(objects, adapter, collector);
420
+
421
+ return {
422
+ adapter,
423
+ objectCount,
424
+ errors: collector.errors,
425
+ warnings: collector.warnings,
426
+ };
427
+ }
428
+
429
+ module.exports = { checkObjectStructure };
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "5.17.9",
2
+ "version": "5.18.0",
3
3
  "name": "@iobroker/repochecker",
4
4
  "dependencies": {
5
5
  "ajv": "^8.20.0",