• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 1113439055

19 Dec 2023 09:01PM UTC coverage: 82.752% (-17.2%) from 99.964%
1113439055

Pull #4258

gitlab-ci

mender-test-bot
chore: Types update

Signed-off-by: Mender Test Bot <mender@northern.tech>
Pull Request #4258: chore: Types update

4326 of 6319 branches covered (0.0%)

8348 of 10088 relevant lines covered (82.75%)

189.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.76
/src/js/helpers.js
1
// Copyright 2017 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React from 'react';
15

16
import pluralize from 'pluralize';
17
import Cookies from 'universal-cookie';
18

19
import { DARK_MODE } from './constants/appConstants';
20
import {
21
  DEPLOYMENT_STATES,
22
  defaultStats,
23
  deploymentDisplayStates,
24
  deploymentStatesToSubstates,
25
  deploymentStatesToSubstatesWithSkipped
26
} from './constants/deploymentConstants';
27
import { ATTRIBUTE_SCOPES, DEVICE_FILTERING_OPTIONS } from './constants/deviceConstants';
28

29
const isEncoded = uri => {
183✔
30
  uri = uri || '';
8✔
31
  return uri !== decodeURIComponent(uri);
8✔
32
};
33

34
export const fullyDecodeURI = uri => {
183✔
35
  while (isEncoded(uri)) {
6✔
36
    uri = decodeURIComponent(uri);
2✔
37
  }
38
  return uri;
6✔
39
};
40

41
export const groupDeploymentDevicesStats = deployment => {
183✔
42
  const deviceStatCollector = (deploymentStates, devices) =>
1✔
43
    Object.values(devices).reduce((accu, device) => (deploymentStates.includes(device.status) ? accu + 1 : accu), 0);
50✔
44

45
  const inprogress = deviceStatCollector(deploymentStatesToSubstates.inprogress, deployment.devices);
1✔
46
  const pending = deviceStatCollector(deploymentStatesToSubstates.pending, deployment.devices);
1✔
47
  const successes = deviceStatCollector(deploymentStatesToSubstates.successes, deployment.devices);
1✔
48
  const failures = deviceStatCollector(deploymentStatesToSubstates.failures, deployment.devices);
1✔
49
  const paused = deviceStatCollector(deploymentStatesToSubstates.paused, deployment.devices);
1✔
50
  return { inprogress, paused, pending, successes, failures };
1✔
51
};
52

53
export const statCollector = (items, statistics) => items.reduce((accu, property) => accu + Number(statistics[property] || 0), 0);
60,470✔
54
export const groupDeploymentStats = (deployment, withSkipped) => {
183✔
55
  const { statistics = {} } = deployment;
4,646✔
56
  const { status = {} } = statistics;
4,646✔
57
  const stats = { ...defaultStats, ...status };
4,646✔
58
  let groupStates = deploymentStatesToSubstates;
4,646✔
59
  let result = {};
4,646✔
60
  if (withSkipped) {
4,646✔
61
    groupStates = deploymentStatesToSubstatesWithSkipped;
2,784✔
62
    result.skipped = statCollector(groupStates.skipped, stats);
2,784✔
63
  }
64
  result = {
4,646✔
65
    ...result,
66
    // don't include 'pending' as inprogress, as all remaining devices will be pending - we don't discriminate based on phase membership
67
    inprogress: statCollector(groupStates.inprogress, stats),
68
    pending: (deployment.max_devices ? deployment.max_devices - deployment.device_count : 0) + statCollector(groupStates.pending, stats),
4,646✔
69
    successes: statCollector(groupStates.successes, stats),
70
    failures: statCollector(groupStates.failures, stats),
71
    paused: statCollector(groupStates.paused, stats)
72
  };
73
  return result;
4,646✔
74
};
75

76
export const getDeploymentState = deployment => {
183✔
77
  const { status: deploymentStatus = DEPLOYMENT_STATES.pending } = deployment;
1,846✔
78
  const { inprogress: currentProgressCount, paused } = groupDeploymentStats(deployment);
1,846✔
79

80
  let status = deploymentDisplayStates[deploymentStatus];
1,846✔
81
  if (deploymentStatus === DEPLOYMENT_STATES.pending && currentProgressCount === 0) {
1,846✔
82
    status = 'queued';
918✔
83
  } else if (paused > 0) {
928!
84
    status = deploymentDisplayStates.paused;
×
85
  }
86
  return status;
1,846✔
87
};
88

89
export const isEmpty = obj => {
183✔
90
  for (const _ in obj) {
335✔
91
    return false;
160✔
92
  }
93
  return true;
175✔
94
};
95

96
export const extractErrorMessage = (err, fallback = '') =>
183✔
97
  err.response?.data?.error?.message || err.response?.data?.error || err.error || err.message || fallback;
10!
98

99
export const preformatWithRequestID = (res, failMsg) => {
183✔
100
  // ellipsis line
101
  if (failMsg.length > 100) failMsg = `${failMsg.substring(0, 220)}...`;
11✔
102

103
  try {
11✔
104
    if (res?.data && Object.keys(res.data).includes('request_id')) {
11✔
105
      let shortRequestUUID = res.data['request_id'].substring(0, 8);
2✔
106
      return `${failMsg} [Request ID: ${shortRequestUUID}]`;
2✔
107
    }
108
  } catch (e) {
109
    console.log('failed to extract request id:', e);
×
110
  }
111
  return failMsg;
9✔
112
};
113

114
export const versionCompare = (v1, v2) => {
183✔
115
  const partsV1 = `${v1}`.split('.');
19✔
116
  const partsV2 = `${v2}`.split('.');
19✔
117
  for (let index = 0; index < partsV1.length; index++) {
19✔
118
    const numberV1 = partsV1[index];
24✔
119
    const numberV2 = partsV2[index];
24✔
120
    if (numberV1 > numberV2) {
24✔
121
      return 1;
13✔
122
    }
123
    if (numberV2 > numberV1) {
11✔
124
      return -1;
5✔
125
    }
126
  }
127
  return 0;
1✔
128
};
129

130
/*
131
 *
132
 * Deep compare
133
 *
134
 */
135
// eslint-disable-next-line sonarjs/cognitive-complexity
136
export function deepCompare() {
137
  var i, l, leftChain, rightChain;
138

139
  function compare2Objects(x, y) {
140
    var p;
141

142
    // remember that NaN === NaN returns false
143
    // and isNaN(undefined) returns true
144
    if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
460!
145
      return true;
×
146
    }
147

148
    // Compare primitives and functions.
149
    // Check if both arguments link to the same object.
150
    // Especially useful on the step where we compare prototypes
151
    if (x === y) {
460✔
152
      return true;
225✔
153
    }
154

155
    // Works in case when functions are created in constructor.
156
    // Comparing dates is a common scenario. Another built-ins?
157
    // We can even handle functions passed across iframes
158
    if (
235✔
159
      (typeof x === 'function' && typeof y === 'function') ||
1,173!
160
      (x instanceof Date && y instanceof Date) ||
161
      (x instanceof RegExp && y instanceof RegExp) ||
162
      (x instanceof String && y instanceof String) ||
163
      (x instanceof Number && y instanceof Number)
164
    ) {
165
      return x.toString() === y.toString();
1✔
166
    }
167

168
    // At last checking prototypes as good as we can
169
    if (!(x instanceof Object && y instanceof Object)) {
234✔
170
      return false;
12✔
171
    }
172

173
    if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
222!
174
      return false;
×
175
    }
176

177
    if (x.constructor !== y.constructor) {
222!
178
      return false;
×
179
    }
180

181
    if (x.prototype !== y.prototype) {
222!
182
      return false;
×
183
    }
184

185
    // Check for infinitive linking loops
186
    if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
222!
187
      return false;
×
188
    }
189

190
    // Quick checking of one object being a subset of another.
191
    // todo: cache the structure of arguments[0] for performance
192
    for (p in y) {
222✔
193
      if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || typeof y[p] !== typeof x[p]) {
1,032✔
194
        return false;
52✔
195
      }
196
    }
197

198
    for (p in x) {
170✔
199
      if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || typeof y[p] !== typeof x[p]) {
680✔
200
        return false;
9✔
201
      }
202

203
      switch (typeof x[p]) {
671✔
204
        case 'object':
205
        case 'function':
206
          leftChain.push(x);
279✔
207
          rightChain.push(y);
279✔
208

209
          if (!compare2Objects(x[p], y[p])) {
279✔
210
            return false;
12✔
211
          }
212

213
          leftChain.pop();
267✔
214
          rightChain.pop();
267✔
215
          break;
267✔
216

217
        default:
218
          if (x[p] !== y[p]) {
392✔
219
            return false;
7✔
220
          }
221
          break;
385✔
222
      }
223
    }
224

225
    return true;
142✔
226
  }
227

228
  if (arguments.length < 1) {
179!
229
    return true; //Die silently? Don't know how to handle such case, please help...
×
230
    // throw "Need two or more arguments to compare";
231
  }
232

233
  for (i = 1, l = arguments.length; i < l; i++) {
179✔
234
    leftChain = []; //Todo: this can be cached
181✔
235
    rightChain = [];
181✔
236

237
    if (!compare2Objects(arguments[0], arguments[i])) {
181✔
238
      return false;
80✔
239
    }
240
  }
241

242
  return true;
99✔
243
}
244

245
export const stringToBoolean = content => {
183✔
246
  if (!content) {
182✔
247
    return false;
163✔
248
  }
249
  const string = content + '';
19✔
250
  switch (string.trim().toLowerCase()) {
19✔
251
    case 'true':
252
    case 'yes':
253
    case '1':
254
      return true;
15✔
255
    case 'false':
256
    case 'no':
257
    case '0':
258
    case null:
259
      return false;
3✔
260
    default:
261
      return Boolean(string);
1✔
262
  }
263
};
264

265
export const toggle = current => !current;
183✔
266

267
export const formatTime = date => {
183✔
268
  if (date && Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date)) {
82✔
269
    return date.toISOString().slice(0, -1);
1✔
270
  } else if (date) {
81✔
271
    return date.replace(' ', 'T').replace(/ /g, '').replace('UTC', '');
67✔
272
  }
273
};
274

275
export const customSort = (direction, field) => (a, b) => {
648✔
276
  if (typeof a[field] === 'string') {
163,444✔
277
    const result = a[field].localeCompare(b[field], { sensitivity: 'case' });
163,429✔
278
    return direction ? result * -1 : result;
163,429✔
279
  }
280
  if (a[field] > b[field]) return direction ? -1 : 1;
15!
281
  if (a[field] < b[field]) return direction ? 1 : -1;
15!
282
  return 0;
15✔
283
};
284

285
export const duplicateFilter = (item, index, array) => array.indexOf(item) == index;
3,085✔
286

287
export const attributeDuplicateFilter = (filterableArray, attributeName = 'key') =>
183!
288
  filterableArray.filter(
5✔
289
    (item, index, array) => array.findIndex(filter => filter[attributeName] === item[attributeName] && filter.scope === item.scope) == index
266✔
290
  );
291

292
export const unionizeStrings = (someStrings, someOtherStrings) => {
183✔
293
  const startingPoint = new Set(someStrings.filter(item => item.length));
24✔
294
  const uniqueStrings = someOtherStrings.length
24✔
295
    ? someOtherStrings.reduce((accu, item) => {
296
        if (item.trim().length) {
33✔
297
          accu.add(item.trim());
14✔
298
        }
299
        return accu;
33✔
300
      }, startingPoint)
301
    : startingPoint;
302
  return [...uniqueStrings];
24✔
303
};
304

305
export const generateDeploymentGroupDetails = (filter, groupName) =>
183✔
306
  filter && filter.terms?.length
3✔
307
    ? `${groupName} (${filter.terms
308
        .map(filter => `${filter.attribute || filter.key} ${DEVICE_FILTERING_OPTIONS[filter.type || filter.operator].shortform} ${filter.value}`)
4✔
309
        .join(', ')})`
310
    : groupName;
311

312
export const mapDeviceAttributes = (attributes = []) =>
183✔
313
  attributes.reduce(
120✔
314
    (accu, attribute) => {
315
      if (!(attribute.value && attribute.name) && attribute.scope === ATTRIBUTE_SCOPES.inventory) {
1,327!
316
        return accu;
×
317
      }
318
      accu[attribute.scope || ATTRIBUTE_SCOPES.inventory] = {
1,327✔
319
        ...accu[attribute.scope || ATTRIBUTE_SCOPES.inventory],
1,333✔
320
        [attribute.name]: attribute.value
321
      };
322
      if (attribute.name === 'device_type' && attribute.scope === ATTRIBUTE_SCOPES.inventory) {
1,327✔
323
        accu.inventory.device_type = [].concat(attribute.value);
64✔
324
      }
325
      return accu;
1,327✔
326
    },
327
    { inventory: { device_type: [], artifact_name: '' }, identity: {}, monitor: {}, system: {}, tags: {} }
328
  );
329

330
export const getFormattedSize = bytes => {
183✔
331
  const suffixes = ['Bytes', 'KB', 'MB', 'GB'];
150✔
332
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
150✔
333
  if (!bytes) {
150✔
334
    return '0 Bytes';
33✔
335
  }
336
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${suffixes[i]}`;
117✔
337
};
338

339
export const FileSize = React.forwardRef(({ fileSize, style }, ref) => (
183✔
340
  <div ref={ref} style={style}>
141✔
341
    {getFormattedSize(fileSize)}
342
  </div>
343
));
344
FileSize.displayName = 'FileSize';
183✔
345

346
const collectAddressesFrom = devices =>
183✔
347
  devices.reduce((collector, { attributes = {} }) => {
12!
348
    const ips = Object.entries(attributes).reduce((accu, [name, value]) => {
34✔
349
      if (name.startsWith('ipv4')) {
84✔
350
        if (Array.isArray(value)) {
23!
351
          const texts = value.map(text => text.slice(0, text.indexOf('/')));
×
352
          accu.push(...texts);
×
353
        } else {
354
          const text = value.slice(0, value.indexOf('/'));
23✔
355
          accu.push(text);
23✔
356
        }
357
      }
358
      return accu;
84✔
359
    }, []);
360
    collector.push(...ips);
34✔
361
    return collector;
34✔
362
  }, []);
363

364
export const getDemoDeviceAddress = (devices, onboardingApproach) => {
183✔
365
  const defaultVitualizedIp = '10.0.2.15';
12✔
366
  const addresses = collectAddressesFrom(devices);
12✔
367
  const address = addresses.reduce((accu, item) => {
12✔
368
    if (accu && item === defaultVitualizedIp) {
23!
369
      return accu;
×
370
    }
371
    return item;
23✔
372
  }, null);
373
  if (!address || (onboardingApproach === 'virtual' && (navigator.appVersion.indexOf('Win') != -1 || navigator.appVersion.indexOf('Mac') != -1))) {
12✔
374
    return 'localhost';
1✔
375
  }
376
  return address;
11✔
377
};
378

379
export const detectOsIdentifier = () => {
183✔
380
  if (navigator.appVersion.indexOf('Win') != -1) return 'Windows';
3!
381
  if (navigator.appVersion.indexOf('Mac') != -1) return 'MacOs';
3✔
382
  if (navigator.appVersion.indexOf('X11') != -1) return 'Unix';
2!
383
  return 'Linux';
2✔
384
};
385

386
export const getRemainderPercent = phases => {
183✔
387
  // remove final phase size if set
388
  phases[phases.length - 1].batch_size = null;
75✔
389
  // use this to get remaining percent of final phase so we don't set a hard number
390
  return phases.reduce((accu, phase) => (phase.batch_size ? accu - phase.batch_size : accu), 100);
203✔
391
};
392

393
export const validatePhases = (phases, deploymentDeviceCount, hasFilter) => {
183✔
394
  if (!phases?.length) {
36✔
395
    return true;
11✔
396
  }
397
  const remainder = getRemainderPercent(phases);
25✔
398
  return phases.reduce((accu, phase) => {
25✔
399
    if (!accu) {
66✔
400
      return accu;
5✔
401
    }
402
    const deviceCount = Math.floor((deploymentDeviceCount / 100) * (phase.batch_size || remainder));
61✔
403
    return deviceCount >= 1 || hasFilter;
61✔
404
  }, true);
405
};
406

407
export const getPhaseDeviceCount = (numberDevices = 1, batchSize, remainder, isLastPhase) =>
183✔
408
  isLastPhase ? Math.ceil((numberDevices / 100) * (batchSize || remainder)) : Math.floor((numberDevices / 100) * (batchSize || remainder));
130✔
409

410
export const startTimeSort = (a, b) => (b.created > a.created) - (b.created < a.created);
279✔
411

412
export const standardizePhases = phases =>
183✔
413
  phases.map((phase, index) => {
3✔
414
    let standardizedPhase = { batch_size: phase.batch_size, start_ts: index };
8✔
415
    if (phase.delay) {
8✔
416
      standardizedPhase.delay = phase.delay;
5✔
417
      standardizedPhase.delayUnit = phase.delayUnit || 'hours';
5✔
418
    }
419
    if (index === 0) {
8✔
420
      // delete the start timestamp from a deployment pattern, to default to starting without delay
421
      delete standardizedPhase.start_ts;
3✔
422
    }
423
    return standardizedPhase;
8✔
424
  });
425

426
const getInstallScriptArgs = ({ isHosted, isPreRelease }) => {
183✔
427
  let installScriptArgs = '--demo';
11✔
428
  installScriptArgs = isPreRelease ? `${installScriptArgs} -c experimental` : installScriptArgs;
11✔
429
  installScriptArgs = isHosted ? `${installScriptArgs} --commercial --jwt-token $JWT_TOKEN` : installScriptArgs;
11✔
430
  return installScriptArgs;
11✔
431
};
432

433
const getSetupArgs = ({ deviceType = 'generic-armv6', ipAddress, isDemoMode, tenantToken, isOnboarding }) => {
183✔
434
  let menderSetupArgs = `--quiet --device-type "${deviceType}"`;
11✔
435
  menderSetupArgs = tenantToken ? `${menderSetupArgs} --tenant-token $TENANT_TOKEN` : menderSetupArgs;
11✔
436
  // in production we use polling intervals from the client examples: https://github.com/mendersoftware/mender/blob/master/examples/mender.conf.production
437
  menderSetupArgs = isDemoMode || isOnboarding ? `${menderSetupArgs} --demo` : `${menderSetupArgs} --retry-poll 300 --update-poll 1800 --inventory-poll 28800`;
11✔
438
  if (isDemoMode) {
11✔
439
    // Demo installation, either OS os Enterprise. Install demo cert and add IP to /etc/hosts
440
    menderSetupArgs = `${menderSetupArgs}${ipAddress ? ` --server-ip ${ipAddress}` : ''}`;
6!
441
  } else {
442
    // Production installation, either OS, HM, or Enterprise
443
    menderSetupArgs = `${menderSetupArgs} --server-url https://${window.location.hostname} --server-cert=""`;
5✔
444
  }
445
  return menderSetupArgs;
11✔
446
};
447

448
export const getDebConfigurationCode = props => {
183✔
449
  const { tenantToken, token, isPreRelease } = props;
11✔
450
  const envVars = tenantToken ? `JWT_TOKEN="${token}"\nTENANT_TOKEN="${tenantToken}"\n` : '';
11✔
451
  const installScriptArgs = getInstallScriptArgs(props);
11✔
452
  const scriptUrl = isPreRelease ? 'https://get.mender.io/staging' : 'https://get.mender.io';
11✔
453
  const menderSetupArgs = getSetupArgs(props);
11✔
454
  return `${envVars}wget -O- ${scriptUrl} | sudo bash -s -- ${installScriptArgs} -- ${menderSetupArgs}`;
11✔
455
};
456

457
export const getSnackbarMessage = (skipped, done) => {
183✔
458
  pluralize.addIrregularRule('its', 'their');
1✔
459
  const skipText = skipped
1!
460
    ? `${skipped} ${pluralize('devices', skipped)} ${pluralize('have', skipped)} more than one pending authset. Expand ${pluralize(
461
        'this',
462
        skipped
463
      )} ${pluralize('device', skipped)} to individually adjust ${pluralize('their', skipped)} authorization status. `
464
    : '';
465
  const doneText = done ? `${done} ${pluralize('device', done)} ${pluralize('was', done)} updated successfully. ` : '';
1!
466
  return `${doneText}${skipText}`;
1✔
467
};
468

469
export const extractSoftware = (attributes = {}) => {
183✔
470
  const softwareKeys = Object.keys(attributes).reduce((accu, item) => {
59✔
471
    if (item.endsWith('.version')) {
163✔
472
      accu.push(item.substring(0, item.lastIndexOf('.')));
70✔
473
    }
474
    return accu;
163✔
475
  }, []);
476
  return Object.entries(attributes).reduce(
59✔
477
    (accu, item) => {
478
      if (softwareKeys.some(key => item[0].startsWith(key))) {
273✔
479
        accu.software.push(item);
85✔
480
      } else {
481
        accu.nonSoftware.push(item);
78✔
482
      }
483
      return accu;
163✔
484
    },
485
    { software: [], nonSoftware: [] }
486
  );
487
};
488

489
export const extractSoftwareItem = (artifactProvides = {}) => {
183✔
490
  const { software } = extractSoftware(artifactProvides);
33✔
491
  return (
33✔
492
    software
493
      .reduce((accu, item) => {
494
        const infoItems = item[0].split('.');
31✔
495
        if (infoItems[infoItems.length - 1] !== 'version') {
31!
496
          return accu;
×
497
        }
498
        accu.push({ key: infoItems[0], name: infoItems.slice(1, infoItems.length - 1).join('.'), version: item[1], nestingLevel: infoItems.length });
31✔
499
        return accu;
31✔
500
      }, [])
501
      // we assume the smaller the nesting level in the software name, the closer the software is to the rootfs/ the higher the chances we show the rootfs
502
      // sort based on this assumption & then only return the first item (can't use index access, since there might not be any software item at all)
503
      .sort((a, b) => a.nestingLevel - b.nestingLevel)
×
504
      .reduce((accu, item) => accu ?? item, undefined)
31✔
505
  );
506
};
507

508
const cookies = new Cookies();
183✔
509

510
export const createDownload = (target, filename, token) => {
183✔
511
  let link = document.createElement('a');
1✔
512
  link.setAttribute('href', target);
1✔
513
  link.setAttribute('download', filename);
1✔
514
  link.style.display = 'none';
1✔
515
  document.body.appendChild(link);
1✔
516
  cookies.set('JWT', token, { path: '/', secure: true, sameSite: 'strict', maxAge: 5 });
1✔
517
  link.click();
1✔
518
  document.body.removeChild(link);
1✔
519
};
520

521
export const createFileDownload = (content, filename, token) => createDownload('data:text/plain;charset=utf-8,' + encodeURIComponent(content), filename, token);
183✔
522

523
export const getISOStringBoundaries = currentDate => {
183✔
524
  const date = [currentDate.getUTCFullYear(), `0${currentDate.getUTCMonth() + 1}`.slice(-2), `0${currentDate.getUTCDate()}`.slice(-2)].join('-');
295✔
525
  return { start: `${date}T00:00:00.000`, end: `${date}T23:59:59.999` };
295✔
526
};
527

528
export const isDarkMode = mode => mode === DARK_MODE;
445✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc