@northern.tech/store 0.30.0 → 0.30.2

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 (446) hide show
  1. package/dist/actions.cjs +21 -1130
  2. package/dist/actions.cjs.map +1 -1
  3. package/dist/actions.d.cts +212 -221
  4. package/dist/actions.d.ts +212 -220
  5. package/dist/actions.js +21 -18
  6. package/dist/actions.js.map +1 -1
  7. package/dist/api/general-api.cjs +61 -459
  8. package/dist/api/general-api.cjs.map +1 -1
  9. package/dist/api/general-api.d.cts +15 -17
  10. package/dist/api/general-api.d.ts +15 -17
  11. package/dist/api/general-api.js +56 -15
  12. package/dist/api/general-api.js.map +1 -1
  13. package/dist/api/users-api.cjs +32 -469
  14. package/dist/api/users-api.cjs.map +1 -1
  15. package/dist/api/users-api.d.cts +19 -14
  16. package/dist/api/users-api.d.ts +19 -13
  17. package/dist/api/users-api.js +30 -12
  18. package/dist/api/users-api.js.map +1 -1
  19. package/dist/appSlice/constants.cjs +190 -144
  20. package/dist/appSlice/constants.cjs.map +1 -1
  21. package/dist/appSlice/constants.d.cts +2 -159
  22. package/dist/appSlice/constants.d.ts +2 -159
  23. package/dist/appSlice/constants.js +181 -29
  24. package/dist/appSlice/constants.js.map +1 -1
  25. package/dist/appSlice/index.cjs +147 -178
  26. package/dist/appSlice/index.cjs.map +1 -1
  27. package/dist/appSlice/index.d.cts +2 -148
  28. package/dist/appSlice/index.d.ts +2 -148
  29. package/dist/appSlice/index.js +142 -18
  30. package/dist/appSlice/index.js.map +1 -1
  31. package/dist/appSlice/mocks.cjs +17 -191
  32. package/dist/appSlice/mocks.cjs.map +1 -1
  33. package/dist/appSlice/mocks.d.cts +33 -36
  34. package/dist/appSlice/mocks.d.ts +33 -36
  35. package/dist/appSlice/mocks.js +17 -25
  36. package/dist/appSlice/mocks.js.map +1 -1
  37. package/dist/appSlice/selectors.cjs +49 -91
  38. package/dist/appSlice/selectors.cjs.map +1 -1
  39. package/dist/appSlice/selectors.d.cts +216 -230
  40. package/dist/appSlice/selectors.d.ts +216 -230
  41. package/dist/appSlice/selectors.js +29 -44
  42. package/dist/appSlice/selectors.js.map +1 -1
  43. package/dist/appSlice/thunks.cjs +6 -4636
  44. package/dist/appSlice/thunks.d.cts +59 -62
  45. package/dist/appSlice/thunks.d.ts +59 -62
  46. package/dist/appSlice/thunks.js +2 -45
  47. package/dist/auth.cjs +68 -433
  48. package/dist/auth.cjs.map +1 -1
  49. package/dist/auth.d.cts +14 -14
  50. package/dist/auth.d.ts +14 -14
  51. package/dist/auth.js +65 -18
  52. package/dist/auth.js.map +1 -1
  53. package/dist/chunk-CKQMccvm.cjs +28 -0
  54. package/dist/commonConstants.cjs +14 -393
  55. package/dist/commonConstants.d.cts +2 -83
  56. package/dist/commonConstants.d.ts +2 -83
  57. package/dist/commonConstants.js +2 -33
  58. package/dist/commonSelectors.cjs +284 -1269
  59. package/dist/commonSelectors.cjs.map +1 -1
  60. package/dist/commonSelectors.d.cts +1623 -1416
  61. package/dist/commonSelectors.d.ts +1623 -1416
  62. package/dist/commonSelectors.js +277 -51
  63. package/dist/commonSelectors.js.map +1 -1
  64. package/dist/constants-5cdwz1iH.d.ts +160 -0
  65. package/dist/constants-BWEsNG5c.d.ts +28 -0
  66. package/dist/constants-BciiayPt.d.ts +17 -0
  67. package/dist/constants-C5AU0mCY.d.ts +157 -0
  68. package/dist/constants-CIx3fnBv.d.cts +17 -0
  69. package/dist/constants-CNhpIMME.d.cts +93 -0
  70. package/dist/constants-Cpgyuy_r.d.ts +57 -0
  71. package/dist/constants-D41U_jbR.d.cts +160 -0
  72. package/dist/constants-DK7fI3Rh.d.cts +28 -0
  73. package/dist/constants-DPLHhjVN.d.cts +157 -0
  74. package/dist/constants-DrwXHsJ1.d.ts +120 -0
  75. package/dist/constants-G3wymKIl.d.cts +57 -0
  76. package/dist/constants-MPLfugsi.d.cts +120 -0
  77. package/dist/constants-y2XVLQWf.d.ts +93 -0
  78. package/dist/constants.cjs +784 -972
  79. package/dist/constants.cjs.map +1 -1
  80. package/dist/constants.d.cts +8 -14
  81. package/dist/constants.d.ts +8 -14
  82. package/dist/constants.js +674 -232
  83. package/dist/constants.js.map +1 -1
  84. package/dist/deploymentsSlice/constants.cjs +15 -214
  85. package/dist/deploymentsSlice/constants.d.cts +2 -163
  86. package/dist/deploymentsSlice/constants.d.ts +2 -163
  87. package/dist/deploymentsSlice/constants.js +2 -35
  88. package/dist/deploymentsSlice/index.cjs +168 -302
  89. package/dist/deploymentsSlice/index.cjs.map +1 -1
  90. package/dist/deploymentsSlice/index.d.cts +2 -157
  91. package/dist/deploymentsSlice/index.d.ts +2 -157
  92. package/dist/deploymentsSlice/index.js +161 -18
  93. package/dist/deploymentsSlice/index.js.map +1 -1
  94. package/dist/deploymentsSlice/mocks.cjs +178 -433
  95. package/dist/deploymentsSlice/mocks.cjs.map +1 -1
  96. package/dist/deploymentsSlice/mocks.d.cts +176 -178
  97. package/dist/deploymentsSlice/mocks.d.ts +176 -178
  98. package/dist/deploymentsSlice/mocks.js +178 -144
  99. package/dist/deploymentsSlice/mocks.js.map +1 -1
  100. package/dist/deploymentsSlice/selectors.cjs +44 -223
  101. package/dist/deploymentsSlice/selectors.cjs.map +1 -1
  102. package/dist/deploymentsSlice/selectors.d.cts +73 -87
  103. package/dist/deploymentsSlice/selectors.d.ts +73 -87
  104. package/dist/deploymentsSlice/selectors.js +37 -25
  105. package/dist/deploymentsSlice/selectors.js.map +1 -1
  106. package/dist/deploymentsSlice/thunks.cjs +16 -4654
  107. package/dist/deploymentsSlice/thunks.d.cts +223 -236
  108. package/dist/deploymentsSlice/thunks.d.ts +223 -236
  109. package/dist/deploymentsSlice/thunks.js +2 -65
  110. package/dist/devicesSlice/constants.cjs +9 -68
  111. package/dist/devicesSlice/constants.d.cts +2 -37
  112. package/dist/devicesSlice/constants.d.ts +2 -37
  113. package/dist/devicesSlice/constants.js +2 -23
  114. package/dist/devicesSlice/index.cjs +215 -225
  115. package/dist/devicesSlice/index.cjs.map +1 -1
  116. package/dist/devicesSlice/index.d.cts +2 -202
  117. package/dist/devicesSlice/index.d.ts +2 -202
  118. package/dist/devicesSlice/index.js +209 -18
  119. package/dist/devicesSlice/index.js.map +1 -1
  120. package/dist/devicesSlice/mocks.cjs +146 -339
  121. package/dist/devicesSlice/mocks.cjs.map +1 -1
  122. package/dist/devicesSlice/mocks.d.cts +150 -148
  123. package/dist/devicesSlice/mocks.d.ts +150 -148
  124. package/dist/devicesSlice/mocks.js +145 -132
  125. package/dist/devicesSlice/mocks.js.map +1 -1
  126. package/dist/devicesSlice/selectors.cjs +145 -539
  127. package/dist/devicesSlice/selectors.cjs.map +1 -1
  128. package/dist/devicesSlice/selectors.d.cts +685 -699
  129. package/dist/devicesSlice/selectors.d.ts +685 -699
  130. package/dist/devicesSlice/selectors.js +123 -59
  131. package/dist/devicesSlice/selectors.js.map +1 -1
  132. package/dist/devicesSlice/thunks.cjs +48 -4718
  133. package/dist/devicesSlice/thunks.d.cts +800 -752
  134. package/dist/devicesSlice/thunks.d.ts +800 -752
  135. package/dist/devicesSlice/thunks.js +2 -129
  136. package/dist/index-4eaLEXy_.d.cts +152 -0
  137. package/dist/index-BEVkIiNa.d.cts +95 -0
  138. package/dist/index-BP0uAq36.d.cts +159 -0
  139. package/dist/index-Bwx9jEiL.d.cts +71 -0
  140. package/dist/index-CJkrL0oA.d.ts +64 -0
  141. package/dist/index-CO-py5d4.d.ts +95 -0
  142. package/dist/index-CTt-eIY8.d.cts +154 -0
  143. package/dist/index-CkwVnIqd.d.ts +159 -0
  144. package/dist/index-Cvkvcz4r.d.ts +115 -0
  145. package/dist/index-DJSlDPRX.d.ts +71 -0
  146. package/dist/index-DqyY6oZ3.d.ts +205 -0
  147. package/dist/index-DtePEQPT.d.ts +152 -0
  148. package/dist/index-Dv3Hfxk_.d.ts +154 -0
  149. package/dist/index-FyYBBeN-.d.cts +115 -0
  150. package/dist/index-Lz5JsJ6O.d.cts +205 -0
  151. package/dist/index-UPc3wvVd.d.cts +64 -0
  152. package/dist/liststatehook.cjs +83 -948
  153. package/dist/liststatehook.cjs.map +1 -1
  154. package/dist/liststatehook.d.cts +29 -239
  155. package/dist/liststatehook.d.ts +29 -239
  156. package/dist/liststatehook.js +77 -85
  157. package/dist/liststatehook.js.map +1 -1
  158. package/dist/locationutils.cjs +459 -916
  159. package/dist/locationutils.cjs.map +1 -1
  160. package/dist/locationutils.d.cts +244 -110
  161. package/dist/locationutils.d.ts +244 -110
  162. package/dist/locationutils.js +440 -44
  163. package/dist/locationutils.js.map +1 -1
  164. package/dist/monitorSlice/constants.cjs +0 -19
  165. package/dist/monitorSlice/constants.d.cts +2 -5
  166. package/dist/monitorSlice/constants.d.ts +2 -5
  167. package/dist/monitorSlice/constants.js +1 -2
  168. package/dist/monitorSlice/index.cjs +65 -82
  169. package/dist/monitorSlice/index.cjs.map +1 -1
  170. package/dist/monitorSlice/index.d.cts +2 -94
  171. package/dist/monitorSlice/index.d.ts +2 -94
  172. package/dist/monitorSlice/index.js +59 -18
  173. package/dist/monitorSlice/index.js.map +1 -1
  174. package/dist/monitorSlice/mocks.cjs +50 -126
  175. package/dist/monitorSlice/mocks.cjs.map +1 -1
  176. package/dist/monitorSlice/mocks.d.cts +49 -45
  177. package/dist/monitorSlice/mocks.d.ts +49 -45
  178. package/dist/monitorSlice/mocks.js +49 -62
  179. package/dist/monitorSlice/mocks.js.map +1 -1
  180. package/dist/monitorSlice/selectors.cjs +5 -29
  181. package/dist/monitorSlice/selectors.cjs.map +1 -1
  182. package/dist/monitorSlice/selectors.d.cts +10 -1
  183. package/dist/monitorSlice/selectors.d.ts +10 -1
  184. package/dist/monitorSlice/selectors.js +5 -6
  185. package/dist/monitorSlice/selectors.js.map +1 -1
  186. package/dist/monitorSlice/thunks.cjs +83 -1914
  187. package/dist/monitorSlice/thunks.cjs.map +1 -1
  188. package/dist/monitorSlice/thunks.d.cts +112 -120
  189. package/dist/monitorSlice/thunks.d.ts +112 -120
  190. package/dist/monitorSlice/thunks.js +78 -42
  191. package/dist/monitorSlice/thunks.js.map +1 -1
  192. package/dist/onboardingSlice/constants.cjs +44 -69
  193. package/dist/onboardingSlice/constants.cjs.map +1 -1
  194. package/dist/onboardingSlice/constants.d.cts +2 -26
  195. package/dist/onboardingSlice/constants.d.ts +2 -26
  196. package/dist/onboardingSlice/constants.js +43 -7
  197. package/dist/onboardingSlice/constants.js.map +1 -1
  198. package/dist/onboardingSlice/index.cjs +53 -73
  199. package/dist/onboardingSlice/index.cjs.map +1 -1
  200. package/dist/onboardingSlice/index.d.cts +2 -62
  201. package/dist/onboardingSlice/index.d.ts +2 -62
  202. package/dist/onboardingSlice/index.js +47 -13
  203. package/dist/onboardingSlice/index.js.map +1 -1
  204. package/dist/onboardingSlice/mocks.cjs +12 -81
  205. package/dist/onboardingSlice/mocks.cjs.map +1 -1
  206. package/dist/onboardingSlice/mocks.d.cts +14 -15
  207. package/dist/onboardingSlice/mocks.d.ts +14 -15
  208. package/dist/onboardingSlice/mocks.js +12 -15
  209. package/dist/onboardingSlice/mocks.js.map +1 -1
  210. package/dist/onboardingSlice/selectors.cjs +5 -29
  211. package/dist/onboardingSlice/selectors.cjs.map +1 -1
  212. package/dist/onboardingSlice/selectors.d.cts +6 -1
  213. package/dist/onboardingSlice/selectors.d.ts +6 -1
  214. package/dist/onboardingSlice/selectors.js +5 -6
  215. package/dist/onboardingSlice/selectors.js.map +1 -1
  216. package/dist/onboardingSlice/thunks.cjs +8 -4746
  217. package/dist/onboardingSlice/thunks.d.cts +124 -143
  218. package/dist/onboardingSlice/thunks.d.ts +124 -143
  219. package/dist/onboardingSlice/thunks.js +2 -49
  220. package/dist/organizationSlice/constants.cjs +11 -95
  221. package/dist/organizationSlice/constants.d.cts +2 -91
  222. package/dist/organizationSlice/constants.d.ts +2 -91
  223. package/dist/organizationSlice/constants.js +2 -27
  224. package/dist/organizationSlice/index.cjs +113 -152
  225. package/dist/organizationSlice/index.cjs.map +1 -1
  226. package/dist/organizationSlice/index.d.cts +2 -74
  227. package/dist/organizationSlice/index.d.ts +2 -74
  228. package/dist/organizationSlice/index.js +106 -18
  229. package/dist/organizationSlice/index.js.map +1 -1
  230. package/dist/organizationSlice/mocks.cjs +215 -406
  231. package/dist/organizationSlice/mocks.cjs.map +1 -1
  232. package/dist/organizationSlice/mocks.d.cts +209 -212
  233. package/dist/organizationSlice/mocks.d.ts +209 -212
  234. package/dist/organizationSlice/mocks.js +214 -184
  235. package/dist/organizationSlice/mocks.js.map +1 -1
  236. package/dist/organizationSlice/selectors.cjs +97 -474
  237. package/dist/organizationSlice/selectors.cjs.map +1 -1
  238. package/dist/organizationSlice/selectors.d.cts +381 -389
  239. package/dist/organizationSlice/selectors.d.ts +381 -389
  240. package/dist/organizationSlice/selectors.js +78 -50
  241. package/dist/organizationSlice/selectors.js.map +1 -1
  242. package/dist/organizationSlice/thunks.cjs +43 -5150
  243. package/dist/organizationSlice/thunks.d.cts +638 -649
  244. package/dist/organizationSlice/thunks.d.ts +638 -649
  245. package/dist/organizationSlice/thunks.js +2 -119
  246. package/dist/organizationSlice/types.cjs +0 -19
  247. package/dist/organizationSlice/types.d.cts +2 -88
  248. package/dist/organizationSlice/types.d.ts +2 -88
  249. package/dist/organizationSlice/types.js +1 -1
  250. package/dist/releasesSlice/constants.cjs +17 -41
  251. package/dist/releasesSlice/constants.cjs.map +1 -1
  252. package/dist/releasesSlice/constants.d.cts +2 -15
  253. package/dist/releasesSlice/constants.d.ts +2 -15
  254. package/dist/releasesSlice/constants.js +13 -14
  255. package/dist/releasesSlice/constants.js.map +1 -1
  256. package/dist/releasesSlice/index.cjs +106 -179
  257. package/dist/releasesSlice/index.cjs.map +1 -1
  258. package/dist/releasesSlice/index.d.cts +2 -113
  259. package/dist/releasesSlice/index.d.ts +2 -113
  260. package/dist/releasesSlice/index.js +100 -18
  261. package/dist/releasesSlice/index.js.map +1 -1
  262. package/dist/releasesSlice/mocks.cjs +44 -220
  263. package/dist/releasesSlice/mocks.cjs.map +1 -1
  264. package/dist/releasesSlice/mocks.d.cts +63 -61
  265. package/dist/releasesSlice/mocks.d.ts +63 -61
  266. package/dist/releasesSlice/mocks.js +43 -59
  267. package/dist/releasesSlice/mocks.js.map +1 -1
  268. package/dist/releasesSlice/selectors.cjs +44 -439
  269. package/dist/releasesSlice/selectors.cjs.map +1 -1
  270. package/dist/releasesSlice/selectors.d.cts +268 -280
  271. package/dist/releasesSlice/selectors.d.ts +268 -280
  272. package/dist/releasesSlice/selectors.js +31 -36
  273. package/dist/releasesSlice/selectors.js.map +1 -1
  274. package/dist/releasesSlice/thunks.cjs +422 -2175
  275. package/dist/releasesSlice/thunks.cjs.map +1 -1
  276. package/dist/releasesSlice/thunks.d.cts +305 -307
  277. package/dist/releasesSlice/thunks.d.ts +305 -307
  278. package/dist/releasesSlice/thunks.js +413 -65
  279. package/dist/releasesSlice/thunks.js.map +1 -1
  280. package/dist/selectors.cjs +136 -1530
  281. package/dist/selectors.d.cts +10 -36
  282. package/dist/selectors.d.ts +10 -36
  283. package/dist/selectors.js +10 -280
  284. package/dist/sockethook.cjs +140 -515
  285. package/dist/sockethook.cjs.map +1 -1
  286. package/dist/sockethook.d.cts +25 -9
  287. package/dist/sockethook.d.ts +25 -9
  288. package/dist/sockethook.js +134 -135
  289. package/dist/sockethook.js.map +1 -1
  290. package/dist/store-BQxOSRC1.d.ts +234 -0
  291. package/dist/store-BiIA0r0A.d.cts +234 -0
  292. package/dist/store.cjs +117 -1290
  293. package/dist/store.cjs.map +1 -1
  294. package/dist/store.d.cts +3 -206
  295. package/dist/store.d.ts +3 -206
  296. package/dist/store.js +110 -32
  297. package/dist/store.js.map +1 -1
  298. package/dist/storehooks.cjs +240 -5783
  299. package/dist/storehooks.cjs.map +1 -1
  300. package/dist/storehooks.d.cts +76 -4
  301. package/dist/storehooks.d.ts +76 -4
  302. package/dist/storehooks.js +229 -265
  303. package/dist/storehooks.js.map +1 -1
  304. package/dist/thunks.cjs +2656 -5918
  305. package/dist/thunks.cjs.map +1 -1
  306. package/dist/thunks.d.cts +9 -36
  307. package/dist/thunks.d.ts +9 -36
  308. package/dist/thunks.js +2481 -385
  309. package/dist/thunks.js.map +1 -1
  310. package/dist/types-B2NRQLFw.d.ts +88 -0
  311. package/dist/types-ClEfo0dK.d.cts +88 -0
  312. package/dist/useDeploymentDevice.cjs +26 -4650
  313. package/dist/useDeploymentDevice.cjs.map +1 -1
  314. package/dist/useDeploymentDevice.d.cts +4 -2
  315. package/dist/useDeploymentDevice.d.ts +4 -2
  316. package/dist/useDeploymentDevice.js +21 -60
  317. package/dist/useDeploymentDevice.js.map +1 -1
  318. package/dist/usersSlice/constants.cjs +8 -55
  319. package/dist/usersSlice/constants.d.cts +2 -52
  320. package/dist/usersSlice/constants.d.ts +2 -52
  321. package/dist/usersSlice/constants.js +2 -21
  322. package/dist/usersSlice/index.cjs +132 -172
  323. package/dist/usersSlice/index.cjs.map +1 -1
  324. package/dist/usersSlice/index.d.cts +2 -152
  325. package/dist/usersSlice/index.d.ts +2 -152
  326. package/dist/usersSlice/index.js +125 -18
  327. package/dist/usersSlice/index.js.map +1 -1
  328. package/dist/usersSlice/mocks.cjs +55 -196
  329. package/dist/usersSlice/mocks.cjs.map +1 -1
  330. package/dist/usersSlice/mocks.d.cts +68 -72
  331. package/dist/usersSlice/mocks.d.ts +68 -72
  332. package/dist/usersSlice/mocks.js +54 -46
  333. package/dist/usersSlice/mocks.js.map +1 -1
  334. package/dist/usersSlice/selectors.cjs +65 -567
  335. package/dist/usersSlice/selectors.cjs.map +1 -1
  336. package/dist/usersSlice/selectors.d.cts +364 -376
  337. package/dist/usersSlice/selectors.d.ts +364 -376
  338. package/dist/usersSlice/selectors.js +44 -50
  339. package/dist/usersSlice/selectors.js.map +1 -1
  340. package/dist/usersSlice/thunks.cjs +39 -4698
  341. package/dist/usersSlice/thunks.d.cts +820 -856
  342. package/dist/usersSlice/thunks.d.ts +820 -856
  343. package/dist/usersSlice/thunks.js +2 -111
  344. package/dist/utils-CO_CpGFP.d.ts +105 -0
  345. package/dist/utils-CpPfqW0Q.d.cts +105 -0
  346. package/dist/utils.cjs +231 -850
  347. package/dist/utils.cjs.map +1 -1
  348. package/dist/utils.d.cts +2 -80
  349. package/dist/utils.d.ts +2 -80
  350. package/dist/utils.js +211 -50
  351. package/dist/utils.js.map +1 -1
  352. package/package.json +11 -13
  353. package/dist/appSlice/thunks.cjs.map +0 -1
  354. package/dist/appSlice/thunks.js.map +0 -1
  355. package/dist/chunk-2DYA3X77.js +0 -15
  356. package/dist/chunk-2DYA3X77.js.map +0 -1
  357. package/dist/chunk-4BHM6WVX.js +0 -50
  358. package/dist/chunk-4BHM6WVX.js.map +0 -1
  359. package/dist/chunk-4UNLEL5A.js +0 -143
  360. package/dist/chunk-4UNLEL5A.js.map +0 -1
  361. package/dist/chunk-6V5IIIF7.js +0 -396
  362. package/dist/chunk-6V5IIIF7.js.map +0 -1
  363. package/dist/chunk-ARMI6SZS.js +0 -446
  364. package/dist/chunk-ARMI6SZS.js.map +0 -1
  365. package/dist/chunk-AZF4YY3P.js +0 -108
  366. package/dist/chunk-AZF4YY3P.js.map +0 -1
  367. package/dist/chunk-B5AI2YPV.js +0 -156
  368. package/dist/chunk-B5AI2YPV.js.map +0 -1
  369. package/dist/chunk-CQXDAXQF.js +0 -51
  370. package/dist/chunk-CQXDAXQF.js.map +0 -1
  371. package/dist/chunk-DBBE6D36.js +0 -115
  372. package/dist/chunk-DBBE6D36.js.map +0 -1
  373. package/dist/chunk-ECVQVQEL.js +0 -68
  374. package/dist/chunk-ECVQVQEL.js.map +0 -1
  375. package/dist/chunk-FAJ3I2UQ.js +0 -47
  376. package/dist/chunk-FAJ3I2UQ.js.map +0 -1
  377. package/dist/chunk-FCY7BUGK.js +0 -2876
  378. package/dist/chunk-FCY7BUGK.js.map +0 -1
  379. package/dist/chunk-FG37HJLC.js +0 -157
  380. package/dist/chunk-FG37HJLC.js.map +0 -1
  381. package/dist/chunk-FQAUVV6C.js +0 -246
  382. package/dist/chunk-FQAUVV6C.js.map +0 -1
  383. package/dist/chunk-HKN3RN2Z.js +0 -41
  384. package/dist/chunk-HKN3RN2Z.js.map +0 -1
  385. package/dist/chunk-HPKXWNEF.js +0 -100
  386. package/dist/chunk-HPKXWNEF.js.map +0 -1
  387. package/dist/chunk-JIS4PA3R.js +0 -7
  388. package/dist/chunk-JIS4PA3R.js.map +0 -1
  389. package/dist/chunk-JXBTIFMS.js +0 -82
  390. package/dist/chunk-JXBTIFMS.js.map +0 -1
  391. package/dist/chunk-JYPSCCT4.js +0 -58
  392. package/dist/chunk-JYPSCCT4.js.map +0 -1
  393. package/dist/chunk-L53CPHJU.js +0 -721
  394. package/dist/chunk-L53CPHJU.js.map +0 -1
  395. package/dist/chunk-MNJXEB7S.js +0 -304
  396. package/dist/chunk-MNJXEB7S.js.map +0 -1
  397. package/dist/chunk-NMAXZ3ZY.js +0 -1
  398. package/dist/chunk-NMAXZ3ZY.js.map +0 -1
  399. package/dist/chunk-NXLXPRYW.js +0 -142
  400. package/dist/chunk-NXLXPRYW.js.map +0 -1
  401. package/dist/chunk-O6VCSLNE.js +0 -59
  402. package/dist/chunk-O6VCSLNE.js.map +0 -1
  403. package/dist/chunk-PQADM3M3.js +0 -115
  404. package/dist/chunk-PQADM3M3.js.map +0 -1
  405. package/dist/chunk-SJ75YKOA.js +0 -44
  406. package/dist/chunk-SJ75YKOA.js.map +0 -1
  407. package/dist/chunk-TUPBZ6MQ.js +0 -162
  408. package/dist/chunk-TUPBZ6MQ.js.map +0 -1
  409. package/dist/chunk-XF3TZSZS.js +0 -25
  410. package/dist/chunk-XF3TZSZS.js.map +0 -1
  411. package/dist/chunk-YB3US6OT.js +0 -61
  412. package/dist/chunk-YB3US6OT.js.map +0 -1
  413. package/dist/chunk-YDDE5TIH.js +0 -204
  414. package/dist/chunk-YDDE5TIH.js.map +0 -1
  415. package/dist/chunk-YO22XLHI.js +0 -7
  416. package/dist/chunk-YO22XLHI.js.map +0 -1
  417. package/dist/chunk-Z2O6LYVP.js +0 -144
  418. package/dist/chunk-Z2O6LYVP.js.map +0 -1
  419. package/dist/chunk-ZKAH3APE.js +0 -1
  420. package/dist/chunk-ZKAH3APE.js.map +0 -1
  421. package/dist/commonConstants.cjs.map +0 -1
  422. package/dist/commonConstants.js.map +0 -1
  423. package/dist/deploymentsSlice/constants.cjs.map +0 -1
  424. package/dist/deploymentsSlice/constants.js.map +0 -1
  425. package/dist/deploymentsSlice/thunks.cjs.map +0 -1
  426. package/dist/deploymentsSlice/thunks.js.map +0 -1
  427. package/dist/devicesSlice/constants.cjs.map +0 -1
  428. package/dist/devicesSlice/constants.js.map +0 -1
  429. package/dist/devicesSlice/thunks.cjs.map +0 -1
  430. package/dist/devicesSlice/thunks.js.map +0 -1
  431. package/dist/monitorSlice/constants.cjs.map +0 -1
  432. package/dist/monitorSlice/constants.js.map +0 -1
  433. package/dist/onboardingSlice/thunks.cjs.map +0 -1
  434. package/dist/onboardingSlice/thunks.js.map +0 -1
  435. package/dist/organizationSlice/constants.cjs.map +0 -1
  436. package/dist/organizationSlice/constants.js.map +0 -1
  437. package/dist/organizationSlice/thunks.cjs.map +0 -1
  438. package/dist/organizationSlice/thunks.js.map +0 -1
  439. package/dist/organizationSlice/types.cjs.map +0 -1
  440. package/dist/organizationSlice/types.js.map +0 -1
  441. package/dist/selectors.cjs.map +0 -1
  442. package/dist/selectors.js.map +0 -1
  443. package/dist/usersSlice/constants.cjs.map +0 -1
  444. package/dist/usersSlice/constants.js.map +0 -1
  445. package/dist/usersSlice/thunks.cjs.map +0 -1
  446. package/dist/usersSlice/thunks.js.map +0 -1
@@ -1,4652 +1,28 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/useDeploymentDevice.ts
31
- var useDeploymentDevice_exports = {};
32
- __export(useDeploymentDevice_exports, {
33
- useDeploymentDevice: () => useDeploymentDevice
34
- });
35
- module.exports = __toCommonJS(useDeploymentDevice_exports);
36
- var import_react2 = require("react");
37
- var import_react_redux2 = require("react-redux");
38
- var import_validator2 = __toESM(require("validator"), 1);
39
-
40
- // src/appSlice/selectors.ts
41
- var import_helpers = require("@northern.tech/utils/helpers");
42
- var import_toolkit = require("@reduxjs/toolkit");
43
- var getFeatures = (state) => state.app.features;
44
- var getFullVersionInformation = (state) => state.app.versionInformation;
45
- var getSearchState = (state) => state.app.searchState;
46
- var getUploads = (state) => state.app.uploadsById;
47
- var getHostedAnnouncement = (state) => state.app.hostedAnnouncement;
48
- var getIsUploading = (0, import_toolkit.createSelector)([getUploads], (uploadsById) => !!Object.keys(uploadsById).length);
49
- var getSearchedDevices = (0, import_toolkit.createSelector)([getSearchState], ({ deviceIds }) => deviceIds);
50
- var getVersionInformation = (0, import_toolkit.createSelector)(
51
- [getFullVersionInformation, getFeatures],
52
- ({ Integration, ...remainder }, { isHosted }) => isHosted && Integration !== "next" ? remainder : { ...remainder, Integration }
53
- );
54
- var getIsPreview = (0, import_toolkit.createSelector)([getFullVersionInformation], ({ Integration }) => (0, import_helpers.versionCompare)(Integration, "next") > -1);
55
-
56
- // src/commonSelectors.ts
57
- var import_helpers4 = require("@northern.tech/utils/helpers");
58
- var import_toolkit7 = require("@reduxjs/toolkit");
59
- var import_dayjs = __toESM(require("dayjs"), 1);
60
-
61
- // src/appSlice/constants.ts
62
- var import_icons_material = require("@mui/icons-material");
63
- var import_utils = require("@northern.tech/utils");
64
- var chartTypes = {
65
- bar: { key: "bar", Icon: import_icons_material.BarChart },
66
- pie: { key: "pie", Icon: import_icons_material.PieChartOutline }
67
- };
68
- var emptyChartSelection = { software: "", group: "", chartType: chartTypes.bar.key, attribute: "artifact_name" };
69
- var defaultReportType = "distribution";
70
- var defaultReports = [{ ...emptyChartSelection, group: null, attribute: "artifact_name", type: defaultReportType }];
71
- var PLANS = {
72
- os: {
73
- id: "os",
74
- name: "Basic",
75
- description: "The core features of Mender. To continue using Enterprise Trial features\u2014like Delta updates, scheduled deployments, phased rollouts, device filtering, dynamic groups, RBAC, audit logs, and more\u2014please upgrade to a higher plan."
76
- },
77
- professional: {
78
- id: "professional",
79
- name: "Professional",
80
- description: "Everything in Basic, plus enhanced update management and automation features."
81
- },
82
- enterprise: {
83
- id: "enterprise",
84
- name: "Enterprise",
85
- description: "Every advanced feature of Mender, tailored for complex and large-scale deployments. Not available as a monthly subscription \u2014 ask us for a quote."
86
- }
87
- };
88
- var ADDONS = {
89
- configure: {
90
- id: "configure",
91
- title: "Configure",
92
- description: "Seamlessly configure applications and devices remotely \u2013 configure each device to its environment.",
93
- needs: ["hasDeviceConfig"],
94
- eligible: ["os", "professional", "enterprise"]
95
- },
96
- monitor: {
97
- id: "monitor",
98
- title: "Monitor",
99
- description: "Detect and analyze health issues of devices, services and applications. Set up alerts so you can act quickly.",
100
- needs: ["hasMonitor"],
101
- eligible: ["professional", "enterprise"]
102
- },
103
- troubleshoot: {
104
- id: "troubleshoot",
105
- title: "Troubleshoot",
106
- description: "Secure, remote access to your devices \u2013 quickly diagnose and fix issues in real time.",
107
- needs: ["hasDeviceConnect"],
108
- eligible: ["os", "professional", "enterprise"]
109
- }
110
- };
111
- var BENEFITS = {
112
- auditlog: {
113
- id: "auditlog",
114
- benefit: "gain access to logs for important events such as changes to devices, deployments and user management, as well as remote terminal session replays",
115
- requiredPlan: PLANS.enterprise.id
116
- },
117
- dashboard: { id: "dashboard", benefit: "actionable insights into the devices you are updating with Mender", requiredPlan: PLANS.enterprise.id },
118
- deltaGeneration: {
119
- id: "deltaGeneration",
120
- benefit: "automatic delta artifacts generation to minimize data transfer and improve the update delivery",
121
- requiredPlan: PLANS.enterprise.id
122
- },
123
- deviceConfiguration: { id: "deviceConfiguration", benefit: "device configuration features", requiredAddon: ADDONS.configure.id },
124
- deviceMonitor: { id: "deviceMonitor", benefit: "device monitoring features", requiredAddon: ADDONS.monitor.id, requiredPlan: PLANS.professional.id },
125
- deviceTroubleshoot: { id: "deviceTroubleshoot", benefit: "device troubleshooting features", requiredAddon: ADDONS.troubleshoot.id },
126
- dynamicGroups: { id: "dynamicGroups", benefit: "create dynamic groups to ease device management", requiredPlan: PLANS.enterprise.id },
127
- fullFiltering: { id: "fullFiltering", benefit: "filtering by multiple attributes to improve the device overview", requiredPlan: PLANS.professional.id },
128
- gateway: { id: "gateway", benefit: "see devices connected to your gateway device for easy access", requiredPlans: PLANS.professional.id },
129
- pausedDeployments: {
130
- id: "pausedDeployments",
131
- benefit: "granular control about update rollout to allow synchronization across your fleet",
132
- requiredPlan: PLANS.enterprise.id
133
- },
134
- phasedDeployments: { id: "phasedDeployments", benefit: "choose to roll out deployments in multiple phases", requiredPlan: PLANS.enterprise.id },
135
- rbac: { id: "rbac", benefit: "granular role based access control", requiredPlan: PLANS.enterprise.id },
136
- retryDeployments: { id: "retryDeployments", benefit: "optional retries for failed rollout attempts", requiredPlan: PLANS.professional.id },
137
- scheduledDeployments: {
138
- id: "scheduledDeployments",
139
- benefit: "scheduled deployments to steer the distribution of your updates.",
140
- requiredPlan: PLANS.professional.id
141
- },
142
- webhookEvents: {
143
- id: "webhookEvents",
144
- benefit: "receive inventory events and select which type(s) of events the webhook will receive",
145
- requiredPlan: PLANS.professional.id
146
- },
147
- default: { id: "default", benefit: "gain access to this feature", requiredPlan: PLANS.enterprise.id }
148
- };
149
- var DARK_MODE = "dark";
150
-
151
- // src/commonConstants.tsx
152
- var import_js = require("@mdi/js");
153
-
154
- // src/constants.ts
155
- var import_constants4 = require("@northern.tech/utils/constants");
156
-
157
- // src/deploymentsSlice/constants.ts
158
- var alreadyInstalled = "already-installed";
159
- var deploymentSubstates = {
160
- aborted: "aborted",
161
- alreadyInstalled,
162
- decommissioned: "decommissioned",
163
- downloading: "downloading",
164
- failure: "failure",
165
- installing: "installing",
166
- noartifact: "noartifact",
167
- artifact_too_big: "artifact_too_big",
168
- pause_before_committing: "pause_before_committing",
169
- pause_before_installing: "pause_before_installing",
170
- pause_before_rebooting: "pause_before_rebooting",
171
- pending: "pending",
172
- rebooting: "rebooting",
173
- success: "success"
174
- };
175
- var deploymentStatesToSubstates = {
176
- failures: [deploymentSubstates.failure, deploymentSubstates.aborted, deploymentSubstates.decommissioned],
177
- inprogress: [deploymentSubstates.downloading, deploymentSubstates.installing, deploymentSubstates.rebooting],
178
- paused: [deploymentSubstates.pause_before_installing, deploymentSubstates.pause_before_rebooting, deploymentSubstates.pause_before_committing],
179
- pending: [deploymentSubstates.pending],
180
- successes: [deploymentSubstates.success, deploymentSubstates.alreadyInstalled, deploymentSubstates.noartifact, deploymentSubstates.artifact_too_big]
181
- };
182
- var deploymentStatesToSubstatesWithSkipped = {
183
- ...deploymentStatesToSubstates,
184
- failures: [deploymentSubstates.failure],
185
- skipped: [
186
- deploymentSubstates.aborted,
187
- deploymentSubstates.noartifact,
188
- deploymentSubstates.artifact_too_big,
189
- deploymentSubstates.alreadyInstalled,
190
- deploymentSubstates.decommissioned
191
- ],
192
- successes: [deploymentSubstates.success]
193
- };
194
- var installationSubstatesMap = {
195
- download: {
196
- title: "download",
197
- done: "downloaded",
198
- successIndicators: [deploymentSubstates.installing, deploymentSubstates.rebooting, ...deploymentStatesToSubstates.paused, deploymentSubstates.success],
199
- failureIndicators: deploymentStatesToSubstates.failures,
200
- pauseConfigurationIndicator: "ArtifactInstall_Enter"
201
- },
202
- install: {
203
- title: "install",
204
- done: "installed",
205
- successIndicators: [
206
- deploymentSubstates.rebooting,
207
- deploymentSubstates.pause_before_rebooting,
208
- deploymentSubstates.pause_before_committing,
209
- deploymentSubstates.success
210
- ],
211
- failureIndicators: deploymentStatesToSubstates.failures,
212
- pauseConfigurationIndicator: "ArtifactReboot_Enter"
213
- },
214
- reboot: {
215
- title: "reboot",
216
- done: "rebooted",
217
- successIndicators: [deploymentSubstates.pause_before_committing, deploymentSubstates.success],
218
- failureIndicators: deploymentStatesToSubstates.failures,
219
- pauseConfigurationIndicator: "ArtifactCommit_Enter"
220
- },
221
- commit: {
222
- title: "commit",
223
- done: "committed",
224
- successIndicators: deploymentStatesToSubstates.successes,
225
- failureIndicators: deploymentStatesToSubstates.failures,
226
- pauseConfigurationIndicator: void 0
227
- }
228
- };
229
- var DEPLOYMENT_STATES = {
230
- finished: "finished",
231
- inprogress: "inprogress",
232
- pending: "pending",
233
- scheduled: "scheduled"
234
- };
235
- var listDefaultsByState = {
236
- [DEPLOYMENT_STATES.inprogress]: { page: 1, perPage: 10 },
237
- [DEPLOYMENT_STATES.pending]: { page: 1, perPage: 10 },
238
- [DEPLOYMENT_STATES.scheduled]: { ...import_constants4.DEVICE_LIST_DEFAULTS },
239
- [DEPLOYMENT_STATES.finished]: { ...import_constants4.DEVICE_LIST_DEFAULTS },
240
- sort: { direction: import_constants4.SORTING_OPTIONS.desc }
241
- };
242
- var DEFAULT_PENDING_INPROGRESS_COUNT = 10;
243
- var DEPLOYMENT_ROUTES = {
244
- active: {
245
- key: "active",
246
- route: "/deployments/active",
247
- states: [DEPLOYMENT_STATES.pending, DEPLOYMENT_STATES.inprogress],
248
- title: "Active"
249
- },
250
- finished: {
251
- key: "finished",
252
- route: "/deployments/finished",
253
- states: [DEPLOYMENT_STATES.finished],
254
- title: "Finished"
255
- },
256
- scheduled: {
257
- key: "scheduled",
258
- route: "/deployments/scheduled",
259
- states: [DEPLOYMENT_STATES.scheduled],
260
- title: "Scheduled"
261
- }
262
- };
263
- var DEPLOYMENT_TYPES = {
264
- software: "software",
265
- configuration: "configuration"
266
- };
267
- var defaultStats = {
268
- [deploymentSubstates.aborted]: 0,
269
- [deploymentSubstates.alreadyInstalled]: 0,
270
- [deploymentSubstates.decommissioned]: 0,
271
- [deploymentSubstates.downloading]: 0,
272
- [deploymentSubstates.failure]: 0,
273
- [deploymentSubstates.installing]: 0,
274
- [deploymentSubstates.noartifact]: 0,
275
- [deploymentSubstates.pause_before_committing]: 0,
276
- [deploymentSubstates.pause_before_installing]: 0,
277
- [deploymentSubstates.pause_before_rebooting]: 0,
278
- [deploymentSubstates.pending]: 0,
279
- [deploymentSubstates.rebooting]: 0,
280
- [deploymentSubstates.success]: 0
281
- };
282
- var deploymentPrototype = {
283
- devices: {},
284
- name: void 0,
285
- statistics: { status: {} }
286
- };
287
- var pauseMap = {
288
- [deploymentSubstates.pause_before_installing]: {
289
- title: installationSubstatesMap.download.done,
290
- followUp: installationSubstatesMap.download.pauseConfigurationIndicator
291
- },
292
- [deploymentSubstates.pause_before_rebooting]: {
293
- title: installationSubstatesMap.install.done,
294
- followUp: installationSubstatesMap.install.pauseConfigurationIndicator
295
- },
296
- [deploymentSubstates.pause_before_committing]: {
297
- title: installationSubstatesMap.reboot.done,
298
- followUp: installationSubstatesMap.reboot.pauseConfigurationIndicator
299
- }
300
- };
301
-
302
- // src/devicesSlice/constants.ts
303
- var emptyFilter = { key: null, value: "", operator: import_constants4.DEVICE_FILTERING_OPTIONS.$eq.key, scope: "inventory" };
304
- var geoAttributes = ["geo-lat", "geo-lon"].map((attribute) => ({ attribute, scope: "inventory" }));
305
-
306
- // src/onboardingSlice/constants.ts
307
- var onboardingSteps = {
308
- ONBOARDING_START: "onboarding-start",
309
- DEVICES_PENDING_ONBOARDING_START: "devices-pending-onboarding-start",
310
- DASHBOARD_ONBOARDING_START: "dashboard-onboarding-start",
311
- DASHBOARD_ONBOARDING_PENDINGS: "dashboard-onboarding-pendings",
312
- DEVICES_DELAYED_ONBOARDING: "devices-delayed-onboarding",
313
- DEVICES_PENDING_ONBOARDING: "devices-pending-onboarding",
314
- DEVICES_ACCEPTED_ONBOARDING: "devices-accepted-onboarding",
315
- DEVICES_PENDING_ACCEPTING_ONBOARDING: "devices-pending-accepting-onboarding",
316
- DEVICES_DEPLOY_RELEASE_ONBOARDING: "devices-deploy-release-onboarding",
317
- SCHEDULING_ARTIFACT_SELECTION: "scheduling-artifact-selection",
318
- SCHEDULING_ALL_DEVICES_SELECTION: "scheduling-all-devices-selection",
319
- SCHEDULING_GROUP_SELECTION: "scheduling-group-selection",
320
- SCHEDULING_RELEASE_TO_DEVICES: "scheduling-release-to-devices",
321
- DEPLOYMENTS_INPROGRESS: "deployments-inprogress",
322
- DEPLOYMENTS_COMPLETED: "deployments-completed",
323
- DEPLOYMENTS_PAST: "deployments-past",
324
- DEPLOYMENTS_PAST_COMPLETED: "deployments-past-completed",
325
- DEPLOYMENTS_PAST_COMPLETED_FAILURE: "deployments-past-completed-failure",
326
- ONBOARDING_CANCELED: "onboarding-canceled"
327
- };
328
- var orderedOnboardingSteps = [
329
- onboardingSteps.DASHBOARD_ONBOARDING_START,
330
- onboardingSteps.DEVICES_PENDING_ONBOARDING_START,
331
- onboardingSteps.DEVICES_DELAYED_ONBOARDING,
332
- onboardingSteps.DEVICES_PENDING_ONBOARDING,
333
- onboardingSteps.DEVICES_PENDING_ACCEPTING_ONBOARDING,
334
- onboardingSteps.DASHBOARD_ONBOARDING_PENDINGS,
335
- onboardingSteps.DEVICES_ACCEPTED_ONBOARDING,
336
- onboardingSteps.DEVICES_DEPLOY_RELEASE_ONBOARDING,
337
- onboardingSteps.SCHEDULING_ALL_DEVICES_SELECTION,
338
- onboardingSteps.SCHEDULING_GROUP_SELECTION,
339
- onboardingSteps.SCHEDULING_ARTIFACT_SELECTION,
340
- onboardingSteps.SCHEDULING_RELEASE_TO_DEVICES,
341
- onboardingSteps.DEPLOYMENTS_INPROGRESS,
342
- onboardingSteps.DEPLOYMENTS_PAST,
343
- onboardingSteps.DEPLOYMENTS_PAST_COMPLETED,
344
- onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_FAILURE,
345
- onboardingSteps.ONBOARDING_CANCELED
346
- ];
347
-
348
- // src/organizationSlice/constants.ts
349
- var XML_METADATA_FORMAT = "xml";
350
- var JSON_METADATA_FORMAT = "json";
351
- var getSamlStartUrl = (id) => `${window.location.origin}${import_constants4.useradmApiUrl}/auth/sso/${id}/login`;
352
- var getOidcStartUrl = (id) => `${window.location.origin}${import_constants4.useradmApiUrl}/oidc/${id}/start`;
353
- var SSO_TYPES = {
354
- saml: {
355
- id: "saml",
356
- type: "saml",
357
- title: "SAML",
358
- metadataFormat: XML_METADATA_FORMAT,
359
- editorLanguage: XML_METADATA_FORMAT,
360
- contentType: "application/samlmetadata+xml",
361
- getStartUrl: getSamlStartUrl,
362
- configDetails: [
363
- { key: "entityID", label: "Entity ID", getValue: (id) => `${window.location.origin}${import_constants4.useradmApiUrl}/sso/sp/metadata/${id}` },
364
- { key: "acs", label: "ACS URL", getValue: (id) => `${window.location.origin}${import_constants4.useradmApiUrl}/auth/sso/${id}/acs` },
365
- { key: "startURL", label: "Start URL", getValue: getSamlStartUrl }
366
- ]
367
- },
368
- oidc: {
369
- id: "oidc",
370
- type: "oidc",
371
- title: "OpenID Connect",
372
- metadataFormat: JSON_METADATA_FORMAT,
373
- editorLanguage: JSON_METADATA_FORMAT,
374
- contentType: "application/json",
375
- getStartUrl: getOidcStartUrl,
376
- configDetails: [{ key: "startURL", label: "Start Url", getValue: getOidcStartUrl }]
377
- }
378
- };
379
- var auditlogTypes = {
380
- artifact: { title: "Artifact", queryParameter: "object_type", value: "artifact" },
381
- deployment: { title: "Deployment", queryParameter: "object_deployment_name", value: "deployment" },
382
- device: { title: "Device", queryParameter: "object_id", value: "device" },
383
- user_access_token: { title: "Personal Access Token", queryParameter: "user_access_token", value: "user_access_token" },
384
- user: { title: "User", queryParameter: "object_id", value: "user" },
385
- tenant: { title: "Tenant", queryParameter: "object_id", value: "tenant" }
386
- };
387
- var AUDIT_LOGS_TYPES = [auditlogTypes.artifact, auditlogTypes.deployment, auditlogTypes.device, auditlogTypes.user_access_token, auditlogTypes.user];
388
- var SP_AUDIT_LOGS_TYPES = [auditlogTypes.user, auditlogTypes.tenant];
389
- var TENANT_LIST_DEFAULT = {
390
- page: 1,
391
- perPage: 20
392
- };
393
-
394
- // src/releasesSlice/constants.ts
395
- var rootfsImageVersion = "rootfs-image.version";
396
- var softwareTitleMap = { [rootfsImageVersion]: { title: "Root filesystem", priority: 0, key: rootfsImageVersion } };
397
-
398
- // src/usersSlice/constants.ts
399
- var itemUiPermissionsReducer = (accu, { item, uiPermissions }) => item ? { ...accu, [item]: uiPermissions } : accu;
400
- var USER_LOGOUT = "USER_LOGOUT";
401
- var OWN_USER_ID = "me";
402
- var settingsKeys = { initialized: "settings-initialized" };
403
- var READ_STATES = {
404
- read: "read",
405
- seen: "seen",
406
- unread: "unread"
407
- };
408
-
409
- // src/commonConstants.tsx
410
- var import_jsx_runtime = require("react/jsx-runtime");
411
- var timeUnits = {
412
- days: "days",
413
- minutes: "minutes",
414
- hours: "hours"
415
- };
416
- var UNGROUPED_GROUP = { id: "*|=ungrouped=|*", name: "Unassigned" };
417
- var DEVICE_LIST_MAXIMUM_LENGTH = 50;
418
- var oneSecond = 1e3;
419
- var TIMEOUTS = {
420
- debounceDefault: 700,
421
- debounceShort: 300,
422
- halfASecond: 0.5 * oneSecond,
423
- oneSecond,
424
- twoSeconds: 2 * oneSecond,
425
- threeSeconds: 3 * oneSecond,
426
- fiveSeconds: 5 * oneSecond,
427
- refreshDefault: 10 * oneSecond,
428
- refreshLong: 60 * oneSecond
429
- };
430
- var DEVICE_ONLINE_CUTOFF = { interval: 1, intervalName: timeUnits.days };
431
- var defaultIdAttribute = Object.freeze({ attribute: "id", scope: import_constants4.ATTRIBUTE_SCOPES.identity });
432
- var productOrder = ["micro", "standard", "system"];
433
- var credentialTypes = {
434
- aws: "aws",
435
- http: "http",
436
- sas: "sas",
437
- x509: "x509"
438
- };
439
- var EXTERNAL_PROVIDER = {
440
- "iot-core": {
441
- credentialsType: credentialTypes.aws,
442
- icon: import_js.mdiAws,
443
- title: "AWS IoT Core",
444
- twinTitle: "Device Shadow",
445
- provider: "iot-core",
446
- enabled: true,
447
- deviceTwin: true,
448
- configHint: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "For help finding your AWS IoT Core connection string, check the AWS IoT documentation." })
449
- },
450
- "iot-hub": {
451
- credentialsType: credentialTypes.sas,
452
- icon: import_js.mdiMicrosoftAzure,
453
- title: "Azure IoT Hub",
454
- twinTitle: "Device Twin",
455
- provider: "iot-hub",
456
- enabled: true,
457
- deviceTwin: true,
458
- configHint: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
459
- "For help finding your Azure IoT Hub connection string, look under 'Shared access policies' in the Microsoft Azure UI as described",
460
- " ",
461
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
462
- "a",
463
- {
464
- href: "https://devblogs.microsoft.com/iotdev/understand-different-connection-strings-in-azure-iot-hub/#iothubconn",
465
- target: "_blank",
466
- rel: "noopener noreferrer",
467
- children: "here"
468
- }
469
- ),
470
- "."
471
- ] })
472
- },
473
- webhook: {
474
- credentialsType: credentialTypes.http,
475
- deviceTwin: false,
476
- twinTitle: "",
477
- // disable the webhook provider here, since it is treated different than other integrations, with a custom configuration & management view, etc.
478
- enabled: false,
479
- provider: "webhook"
480
- }
481
- };
482
- var emptyWebhook = {
483
- description: "",
484
- provider: "webhook",
485
- credentials: {
486
- type: EXTERNAL_PROVIDER.webhook.credentialsType,
487
- [EXTERNAL_PROVIDER.webhook.credentialsType]: {
488
- secret: "",
489
- url: ""
490
- }
491
- }
492
- };
493
- var MAX_PAGE_SIZE = 500;
494
- var regionNames = new Intl.DisplayNames(["en"], { type: "region" });
495
- var countries = [
496
- "AD",
497
- "AE",
498
- "AF",
499
- "AG",
500
- "AI",
501
- "AL",
502
- "AM",
503
- "AO",
504
- "AQ",
505
- "AR",
506
- "AS",
507
- "AT",
508
- "AU",
509
- "AW",
510
- "AX",
511
- "AZ",
512
- "BA",
513
- "BB",
514
- "BD",
515
- "BE",
516
- "BF",
517
- "BG",
518
- "BH",
519
- "BI",
520
- "BJ",
521
- "BL",
522
- "BM",
523
- "BN",
524
- "BO",
525
- "BR",
526
- "BS",
527
- "BT",
528
- "BV",
529
- "BW",
530
- "BY",
531
- "BZ",
532
- "CA",
533
- "CC",
534
- "CD",
535
- "CF",
536
- "CG",
537
- "CH",
538
- "CI",
539
- "CK",
540
- "CL",
541
- "CM",
542
- "CN",
543
- "CO",
544
- "CR",
545
- "CU",
546
- "CV",
547
- "CW",
548
- "CX",
549
- "CY",
550
- "CZ",
551
- "DE",
552
- "DJ",
553
- "DK",
554
- "DM",
555
- "DO",
556
- "DZ",
557
- "EC",
558
- "EE",
559
- "EG",
560
- "EH",
561
- "ER",
562
- "ES",
563
- "ET",
564
- "FI",
565
- "FJ",
566
- "FK",
567
- "FM",
568
- "FO",
569
- "FR",
570
- "GA",
571
- "GB",
572
- "GD",
573
- "GE",
574
- "GF",
575
- "GG",
576
- "GH",
577
- "GI",
578
- "GL",
579
- "GM",
580
- "GN",
581
- "GP",
582
- "GQ",
583
- "GR",
584
- "GS",
585
- "GT",
586
- "GU",
587
- "GW",
588
- "GY",
589
- "HK",
590
- "HM",
591
- "HN",
592
- "HR",
593
- "HT",
594
- "HU",
595
- "ID",
596
- "IE",
597
- "IL",
598
- "IM",
599
- "IN",
600
- "IO",
601
- "IQ",
602
- "IR",
603
- "IS",
604
- "IT",
605
- "JE",
606
- "JM",
607
- "JO",
608
- "JP",
609
- "KE",
610
- "KG",
611
- "KH",
612
- "KI",
613
- "KM",
614
- "KN",
615
- "KP",
616
- "KR",
617
- "KW",
618
- "KY",
619
- "KZ",
620
- "LA",
621
- "LB",
622
- "LC",
623
- "LI",
624
- "LK",
625
- "LR",
626
- "LS",
627
- "LT",
628
- "LU",
629
- "LV",
630
- "LY",
631
- "MA",
632
- "MC",
633
- "MD",
634
- "ME",
635
- "MF",
636
- "MG",
637
- "MH",
638
- "MK",
639
- "ML",
640
- "MM",
641
- "MN",
642
- "MO",
643
- "MP",
644
- "MQ",
645
- "MR",
646
- "MS",
647
- "MT",
648
- "MU",
649
- "MV",
650
- "MW",
651
- "MX",
652
- "MY",
653
- "MZ",
654
- "NA",
655
- "NC",
656
- "NE",
657
- "NF",
658
- "NG",
659
- "NI",
660
- "NL",
661
- "NO",
662
- "NP",
663
- "NR",
664
- "NU",
665
- "NZ",
666
- "OM",
667
- "PA",
668
- "PE",
669
- "PF",
670
- "PG",
671
- "PH",
672
- "PK",
673
- "PL",
674
- "PM",
675
- "PN",
676
- "PR",
677
- "PS",
678
- "PT",
679
- "PW",
680
- "PY",
681
- "QA",
682
- "RE",
683
- "RO",
684
- "RS",
685
- "RU",
686
- "RW",
687
- "SA",
688
- "SB",
689
- "SC",
690
- "SD",
691
- "SE",
692
- "SG",
693
- "SH",
694
- "SI",
695
- "SJ",
696
- "SK",
697
- "SL",
698
- "SM",
699
- "SN",
700
- "SO",
701
- "SR",
702
- "SS",
703
- "ST",
704
- "SV",
705
- "SX",
706
- "SY",
707
- "SZ",
708
- "TC",
709
- "TD",
710
- "TF",
711
- "TG",
712
- "TH",
713
- "TJ",
714
- "TK",
715
- "TL",
716
- "TM",
717
- "TN",
718
- "TO",
719
- "TR",
720
- "TT",
721
- "TV",
722
- "TW",
723
- "TZ",
724
- "UA",
725
- "UG",
726
- "US",
727
- "UY",
728
- "UZ",
729
- "VA",
730
- "VC",
731
- "VE",
732
- "VG",
733
- "VI",
734
- "VN",
735
- "VU",
736
- "WF",
737
- "WS",
738
- "XK",
739
- "YE",
740
- "YT",
741
- "ZA",
742
- "ZM",
743
- "ZW"
744
- ].map((code) => ({ code, label: regionNames.of(code) })).sort((a, b) => a.label.localeCompare(b.label));
745
-
746
- // src/deploymentsSlice/selectors.ts
747
- var import_toolkit2 = require("@reduxjs/toolkit");
748
- var getDeploymentsById = (state) => state.deployments.byId;
749
- var getDeploymentsByStatus = (state) => state.deployments.byStatus;
750
- var getSelectedDeploymentDeviceIds = (state) => state.deployments.selectedDeviceIds;
751
- var getDeploymentsSelectionState = (state) => state.deployments.selectionState;
752
- var getDeploymentById = (0, import_toolkit2.createSelector)(
753
- [getDeploymentsById, (_, deploymentId) => deploymentId],
754
- (deploymentsById, deploymentId = "") => deploymentsById[deploymentId]
755
- );
756
- var getMappedDeploymentSelection = (0, import_toolkit2.createSelector)(
757
- [getDeploymentsSelectionState, (_, deploymentsState) => deploymentsState, getDeploymentsById],
758
- (selectionState, deploymentsState, deploymentsById) => {
759
- const { selection = [] } = selectionState[deploymentsState] ?? {};
760
- return selection.reduce((accu, id) => {
761
- if (deploymentsById[id]) {
762
- accu.push(deploymentsById[id]);
763
- }
764
- return accu;
765
- }, []);
766
- }
767
- );
768
- var relevantDeploymentStates = [DEPLOYMENT_STATES.pending, DEPLOYMENT_STATES.inprogress, DEPLOYMENT_STATES.finished];
769
- var DEPLOYMENT_CUTOFF = 3;
770
- var getRecentDeployments = (0, import_toolkit2.createSelector)(
771
- [getDeploymentsById, getDeploymentsByStatus],
772
- (deploymentsById, deploymentsByStatus) => Object.entries(deploymentsByStatus).reduce(
773
- (accu, [state, byStatus]) => {
774
- if (!relevantDeploymentStates.includes(state) || !byStatus.deploymentIds.length) {
775
- return accu;
776
- }
777
- accu[state] = byStatus.deploymentIds.reduce((accu2, id) => {
778
- if (deploymentsById[id]) {
779
- accu2.push(deploymentsById[id]);
780
- }
781
- return accu2;
782
- }, []).slice(0, DEPLOYMENT_CUTOFF);
783
- accu.total += byStatus.total;
784
- return accu;
785
- },
786
- { total: 0 }
787
- )
788
- );
789
-
790
- // src/devicesSlice/selectors.ts
791
- var import_helpers2 = require("@northern.tech/utils/helpers");
792
- var import_toolkit3 = require("@reduxjs/toolkit");
793
- var getAcceptedDevices = (state) => state.devices.byStatus.accepted;
794
- var getDevicesByStatus = (state) => state.devices.byStatus;
795
- var getDevicesById = (state) => state.devices.byId;
796
- var getDeviceReports = (state) => state.devices.reports;
797
- var getGroupsById = (state) => state.devices.groups.byId;
798
- var getSelectedGroup = (state) => state.devices.groups.selectedGroup;
799
- var getDeviceListState = (state) => state.devices.deviceList;
800
- var getListedDevices = (state) => state.devices.deviceList.deviceIds;
801
- var getFilteringAttributes = (state) => state.devices.filteringAttributes;
802
- var getDeviceFilters = (state) => state.devices.filters || [];
803
- var getFilteringAttributesFromConfig = (state) => state.devices.filteringAttributesConfig.attributes;
804
- var getSortedFilteringAttributes = (0, import_toolkit3.createSelector)([getFilteringAttributes], (filteringAttributes) => ({
805
- ...filteringAttributes,
806
- identityAttributes: [...filteringAttributes.identityAttributes, "id"]
807
- }));
808
- var getDeviceLimits = (state) => state.devices.limits;
809
- var getFilteringAttributesLimit = (state) => state.devices.filteringAttributesLimit;
810
- var getDeviceIdentityAttributes = (0, import_toolkit3.createSelector)(
811
- [getFilteringAttributes, getFilteringAttributesLimit],
812
- ({ identityAttributes }, filteringAttributesLimit) => {
813
- const attributes = identityAttributes.slice(0, filteringAttributesLimit);
814
- return attributes.reduce(
815
- (accu, value) => {
816
- accu.push({ value, label: value, scope: "identity" });
817
- return accu;
818
- },
819
- [
820
- { value: "name", label: "Name", scope: "tags" },
821
- { value: "id", label: "Device ID", scope: "identity" }
822
- ]
823
- );
824
- }
825
- );
826
- var getDeviceCountsByStatus = (0, import_toolkit3.createSelector)(
827
- [getDevicesByStatus],
828
- (byStatus) => Object.values(import_constants4.DEVICE_STATES).reduce(
829
- (accu, deviceState) => {
830
- const { counts } = byStatus[deviceState];
831
- const { total, ...tieredCounts } = counts;
832
- const count = Object.values(tieredCounts).reduce((accu2, countPerTier) => accu2 + countPerTier, 0);
833
- accu[deviceState] = count;
834
- accu.total = accu.total + count;
835
- return accu;
836
- },
837
- { total: 0 }
838
- )
839
- );
840
- var getDeviceById = (0, import_toolkit3.createSelector)([getDevicesById, (_, deviceId) => deviceId], (devicesById, deviceId = "") => devicesById[deviceId] ?? {});
841
- var getSelectedGroupInfo = (0, import_toolkit3.createSelector)(
842
- [getDeviceCountsByStatus, getGroupsById, getSelectedGroup],
843
- ({ accepted: acceptedDeviceTotal }, groupsById, selectedGroup) => {
844
- let groupCount = acceptedDeviceTotal;
845
- let groupFilters = [];
846
- if (selectedGroup && groupsById[selectedGroup]) {
847
- groupCount = groupsById[selectedGroup].total || 0;
848
- groupFilters = groupsById[selectedGroup].filters || [];
849
- }
850
- return { groupCount, selectedGroup, groupFilters };
851
- }
852
- );
853
- var getCombinedLimit = (0, import_toolkit3.createSelector)(
854
- [getDeviceLimits],
855
- (deviceLimits) => Object.values(deviceLimits).reduce((accu, limit) => accu + Math.max(limit ?? 0, 0), 0)
856
- // limit might be -1 for unlimited devices
857
- );
858
- var getLimitMaxed = (0, import_toolkit3.createSelector)(
859
- [getDeviceCountsByStatus, getCombinedLimit],
860
- ({ accepted: acceptedDevices }, combinedLimit) => !!combinedLimit && combinedLimit <= acceptedDevices
861
- );
862
- var getGroupsByIdWithoutUngrouped = (0, import_toolkit3.createSelector)([getGroupsById], ({ [UNGROUPED_GROUP.id]: ungrouped, ...groups }) => groups);
863
- var getGroupData = (0, import_toolkit3.createSelector)([getGroupsByIdWithoutUngrouped], (groups) => {
864
- const createdGroup = Object.keys(groups).length ? Object.keys(groups)[0] : void 0;
865
- const hasDynamicGroups = Object.values(groups).some((group) => !!group.id);
866
- return { createdGroup, hasDynamicGroups, groups };
867
- });
868
- var getGroups = (0, import_toolkit3.createSelector)([getGroupsById], (groupsById) => {
869
- const groupNames = Object.keys(groupsById).sort();
870
- const groupedGroups = Object.entries(groupsById).sort((a, b) => a[0].localeCompare(b[0])).reduce(
871
- (accu, [groupname, group]) => {
872
- const name = groupname === UNGROUPED_GROUP.id ? UNGROUPED_GROUP.name : groupname;
873
- const groupItem = { ...group, groupId: name, name: groupname };
874
- if ((group.filters ?? []).length > 0) {
875
- if (groupname !== UNGROUPED_GROUP.id) {
876
- accu.dynamic.push(groupItem);
877
- } else {
878
- accu.ungrouped.push(groupItem);
879
- }
880
- } else {
881
- accu.static.push(groupItem);
882
- }
883
- return accu;
884
- },
885
- { dynamic: [], static: [], ungrouped: [] }
886
- );
887
- return { groupNames, ...groupedGroups };
888
- });
889
- var getAttributesList = (0, import_toolkit3.createSelector)(
890
- [getFilteringAttributes, getFilteringAttributesFromConfig],
891
- ({ identityAttributes = [], inventoryAttributes = [] }, { identity = [], inventory = [] }) => [...identityAttributes, ...inventoryAttributes, ...identity, ...inventory].filter(import_helpers2.duplicateFilter)
892
- );
893
- var getEnabledTierLimits = (0, import_toolkit3.createSelector)([getDeviceLimits], (limits) => Object.entries(limits).filter(([, limit]) => limit !== 0));
894
- var getEnabledTiers = (0, import_toolkit3.createSelector)([getEnabledTierLimits], (enabledTierLimits) => enabledTierLimits.map(([type]) => type));
895
- var getDeviceLimitStats = (0, import_toolkit3.createSelector)([getEnabledTierLimits, getAcceptedDevices], (enabledTierLimits, accepted) => {
896
- const { counts } = accepted;
897
- return enabledTierLimits.map(([type, limit]) => ({
898
- type,
899
- limit,
900
- total: counts[type] || 0
901
- }));
902
- });
903
- var getDeviceTypes = (0, import_toolkit3.createSelector)(
904
- [getAcceptedDevices, getDevicesById],
905
- ({ deviceIds = [] }, devicesById) => Object.keys(
906
- deviceIds.slice(0, 200).reduce((accu, item) => {
907
- const { device_type: deviceTypes = [] } = devicesById[item] ? devicesById[item].attributes : {};
908
- accu = deviceTypes.reduce((deviceTypeAccu, deviceType) => {
909
- if (deviceType.length > 1) {
910
- deviceTypeAccu[deviceType] = deviceTypeAccu[deviceType] ? deviceTypeAccu[deviceType] + 1 : 1;
911
- }
912
- return deviceTypeAccu;
913
- }, accu);
914
- return accu;
915
- }, {})
916
- )
917
- );
918
-
919
- // src/monitorSlice/selectors.ts
920
- var getIssueCountsByType = (state) => state.monitor.issueCounts.byType;
921
-
922
- // src/onboardingSlice/selectors.ts
923
- var getOnboarding = (state) => state.onboarding;
924
-
925
- // src/organizationSlice/selectors.ts
926
- var import_toolkit4 = require("@reduxjs/toolkit");
927
- var getOrganization = (state) => state.organization.organization;
928
- var getExternalIntegrations = (state) => state.organization.externalDeviceIntegrations;
929
- var getAuditLog = (state) => state.organization.auditlog.events;
930
- var getAuditLogSelectionState = (state) => state.organization.auditlog.selectionState;
931
- var getTenantsList = (state) => state.organization.tenantList;
932
- var getWebhookEvents = (state) => state.organization.webhooks.events;
933
- var getWebhookEventTotal = (state) => state.organization.webhooks.eventsTotal;
934
- var getDeviceTwinIntegrations = (0, import_toolkit4.createSelector)(
935
- [getExternalIntegrations],
936
- (integrations) => integrations.filter((integration) => integration.id && EXTERNAL_PROVIDER[integration.provider]?.deviceTwin)
937
- );
938
- var getIsServiceProvider = (state) => state.organization.organization.service_provider;
939
- var getWebhooks = (0, import_toolkit4.createSelector)(
940
- [getExternalIntegrations],
941
- (integrations) => integrations.filter((integration) => integration.id && integration.provider === EXTERNAL_PROVIDER.webhook.provider)
942
- );
943
- var getWebhookEventInfo = (0, import_toolkit4.createSelector)(
944
- [getWebhooks, getWebhookEvents, getWebhookEventTotal],
945
- (webhooks, events, eventTotal) => webhooks.length ? { events, eventTotal } : { events: [], eventTotal: 0 }
946
- );
947
- var getAuditLogEntry = (0, import_toolkit4.createSelector)([getAuditLog, getAuditLogSelectionState], (events, { selectedId }) => {
948
- if (!selectedId) {
949
- return;
950
- }
951
- const [eventAction, eventTime] = atob(selectedId).split("|");
952
- return events.find((item) => item.action === eventAction && item.time === eventTime);
953
- });
954
- var toTierName = (key) => key.replace(/max_|_?devices/g, "") || "standard";
955
- var processDeviceLimits = (deviceLimits, skipFilter = false) => {
956
- const result = { limits: {}, disabled: [] };
957
- if (!deviceLimits) return result;
958
- const tiersByName = Object.fromEntries(Object.entries(deviceLimits).map(([key, limit]) => [toTierName(key), { key, limit }]));
959
- return productOrder.reduce((accu, tierName) => {
960
- const entry = tiersByName[tierName];
961
- if (!entry) return accu;
962
- const { key, limit } = entry;
963
- if (limit.value === 0) {
964
- accu.disabled.push(tierName);
965
- if (!skipFilter) return accu;
966
- }
967
- accu.limits[tierName] = {
968
- id: tierName,
969
- backendId: key,
970
- limit: limit.value,
971
- current: limit.current_value,
972
- name: tierName,
973
- quotaLeft: Math.max(limit.value - limit.current_value, 0),
974
- limitReached: limit.value !== -1 && limit.value <= limit.current_value
975
- };
976
- return accu;
977
- }, result);
978
- };
979
- var getDeviceLimitsInfo = (0, import_toolkit4.createSelector)([getOrganization], ({ device_limits }) => processDeviceLimits(device_limits));
980
- var getDisabledTiers = (0, import_toolkit4.createSelector)([getDeviceLimitsInfo], ({ disabled }) => disabled);
981
- var getSpLimits = (0, import_toolkit4.createSelector)([getDeviceLimitsInfo], ({ limits }) => limits);
982
- var getTenantListWithLimits = (0, import_toolkit4.createSelector)([getTenantsList], (tenantList) => ({
983
- ...tenantList,
984
- tenants: tenantList.tenants.map((tenant) => ({
985
- ...tenant,
986
- device_limits: processDeviceLimits(tenant.device_limits, true).limits
987
- }))
988
- }));
989
-
990
- // src/releasesSlice/selectors.ts
991
- var import_toolkit5 = require("@reduxjs/toolkit");
992
-
993
- // src/utils.ts
994
- var import_helpers3 = require("@northern.tech/utils/helpers");
995
- var filterProcessors = {
996
- [import_constants4.DEVICE_FILTERING_OPTIONS.$gt.key]: (val) => Number(val) || val,
997
- [import_constants4.DEVICE_FILTERING_OPTIONS.$gte.key]: (val) => Number(val) || val,
998
- [import_constants4.DEVICE_FILTERING_OPTIONS.$lt.key]: (val) => Number(val) || val,
999
- [import_constants4.DEVICE_FILTERING_OPTIONS.$lte.key]: (val) => Number(val) || val,
1000
- [import_constants4.DEVICE_FILTERING_OPTIONS.$ltne.key]: (val) => Number(val) || val,
1001
- [import_constants4.DEVICE_FILTERING_OPTIONS.$in.key]: (val) => ("" + val).split(",").map((i) => i.trim()),
1002
- [import_constants4.DEVICE_FILTERING_OPTIONS.$nin.key]: (val) => ("" + val).split(",").map((i) => i.trim()),
1003
- [import_constants4.DEVICE_FILTERING_OPTIONS.$exists.key]: import_helpers3.yes,
1004
- [import_constants4.DEVICE_FILTERING_OPTIONS.$nexists.key]: () => false
1005
- };
1006
- var filterAliases = {
1007
- $nexists: { alias: import_constants4.DEVICE_FILTERING_OPTIONS.$exists.key, value: false }
1008
- };
1009
- var mapFiltersToTerms = (filters) => filters.map((filter) => ({
1010
- scope: filter.scope,
1011
- attribute: filter.key,
1012
- type: filterAliases[filter.operator]?.alias || filter.operator,
1013
- value: filterProcessors.hasOwnProperty(filter.operator) ? filterProcessors[filter.operator](filter.value) : filter.value
1014
- }));
1015
- var mapTermsToFilters = (terms) => terms.map((term) => {
1016
- const aliasedFilter = Object.entries(filterAliases).find(
1017
- (aliasDefinition) => aliasDefinition[1].alias === term.type && aliasDefinition[1].value === term.value
1018
- );
1019
- const operator = aliasedFilter ? aliasedFilter[0] : term.type;
1020
- return { scope: term.scope, key: term.attribute, operator, value: term.value };
1021
- });
1022
- var convertIssueOptionsToFilters = (issuesSelection, filtersState = {}) => issuesSelection.map((item) => {
1023
- if (typeof import_constants4.DEVICE_ISSUE_OPTIONS[item].filterRule.value === "function") {
1024
- return { ...import_constants4.DEVICE_ISSUE_OPTIONS[item].filterRule, value: import_constants4.DEVICE_ISSUE_OPTIONS[item].filterRule.value(filtersState) };
1025
- }
1026
- return import_constants4.DEVICE_ISSUE_OPTIONS[item].filterRule;
1027
- });
1028
- var convertDeviceListStateToFilters = ({
1029
- filters = [],
1030
- group,
1031
- groups = { byId: {} },
1032
- offlineThreshold,
1033
- selectedIssues = [],
1034
- status
1035
- }) => {
1036
- let applicableFilters = [...filters];
1037
- if (typeof group === "string" && !(groups.byId[group]?.filters || applicableFilters).length) {
1038
- applicableFilters.push({ key: "group", value: group, operator: import_constants4.DEVICE_FILTERING_OPTIONS.$eq.key, scope: "system" });
1039
- }
1040
- const nonMonitorFilters = applicableFilters.filter(
1041
- (filter) => !Object.values(import_constants4.DEVICE_ISSUE_OPTIONS).some(
1042
- ({ filterRule }) => filter.scope !== "inventory" && filterRule.scope === filter.scope && filterRule.key === filter.key
1043
- )
1044
- );
1045
- const deviceIssueFilters = convertIssueOptionsToFilters(selectedIssues, { offlineThreshold });
1046
- applicableFilters = [...nonMonitorFilters, ...deviceIssueFilters];
1047
- const effectiveFilters = status ? [...applicableFilters, { key: "status", value: status, operator: import_constants4.DEVICE_FILTERING_OPTIONS.$eq.key, scope: "identity" }] : applicableFilters;
1048
- return { applicableFilters: nonMonitorFilters, filterTerms: mapFiltersToTerms(effectiveFilters) };
1049
- };
1050
- var filterCompare = (filter, item) => Object.keys(emptyFilter).every((key) => item[key]?.toString() === filter[key]?.toString());
1051
- var filtersFilter = (item, index, array) => {
1052
- const firstIndex = array.findIndex((filter) => filterCompare(filter, item));
1053
- return firstIndex === index;
1054
- };
1055
- var listItemMapper = (byId, ids, { cutOffSize = DEVICE_LIST_MAXIMUM_LENGTH, defaultObject = {} }) => ids.slice(0, cutOffSize).reduce((accu, id) => {
1056
- if (id && byId[id]) {
1057
- accu.push({ ...defaultObject, ...byId[id] });
1058
- }
1059
- return accu;
1060
- }, []);
1061
- var mergePermissions = (existingPermissions = { ...import_constants4.emptyUiPermissions }, addedPermissions) => Object.entries(existingPermissions).reduce(
1062
- (accu, [key, value]) => {
1063
- let values;
1064
- if (!accu[key]) {
1065
- accu[key] = value;
1066
- return accu;
1067
- }
1068
- if (Array.isArray(value)) {
1069
- values = [...value, ...accu[key]].filter(import_helpers3.duplicateFilter);
1070
- } else {
1071
- values = mergePermissions(accu[key], { ...value });
1072
- }
1073
- accu[key] = values;
1074
- return accu;
1075
- },
1076
- { ...addedPermissions }
1077
- );
1078
- var mapUserRolesToUiPermissions = (userRoles, roles) => userRoles.reduce(
1079
- (accu, roleId) => {
1080
- if (!(roleId && roles[roleId])) {
1081
- return accu;
1082
- }
1083
- return mergePermissions(accu, roles[roleId].uiPermissions);
1084
- },
1085
- { ...import_constants4.emptyUiPermissions }
1086
- );
1087
- var progress = ({ loaded, total }) => {
1088
- let uploadProgress3 = loaded / total * 100;
1089
- return uploadProgress3 = uploadProgress3 < 50 ? Math.ceil(uploadProgress3) : Math.round(uploadProgress3);
1090
- };
1091
- var extractErrorMessage = (err, fallback = "") => err.response?.data?.error?.message || err.response?.data?.error || err.error || err.message || fallback;
1092
- var getComparisonCompatibleVersion = (version) => isNaN(version.charAt(0)) && version !== "next" ? "master" : version;
1093
- var mapDeviceAttributes = (attributes = []) => attributes.reduce(
1094
- (accu, attribute) => {
1095
- if (!(attribute.value && attribute.name) && attribute.scope === import_constants4.ATTRIBUTE_SCOPES.inventory) {
1096
- return accu;
1097
- }
1098
- accu[attribute.scope || import_constants4.ATTRIBUTE_SCOPES.inventory] = {
1099
- ...accu[attribute.scope || import_constants4.ATTRIBUTE_SCOPES.inventory],
1100
- [attribute.name]: attribute.value
1101
- };
1102
- if (attribute.name === "device_type" && attribute.scope === import_constants4.ATTRIBUTE_SCOPES.inventory) {
1103
- accu.inventory.device_type = [].concat(attribute.value);
1104
- }
1105
- return accu;
1106
- },
1107
- { inventory: { device_type: [], artifact_name: "" }, identity: {}, monitor: {}, system: {}, tags: {} }
1108
- );
1109
- var isDarkMode = (mode) => mode === DARK_MODE;
1110
-
1111
- // src/releasesSlice/selectors.ts
1112
- var getSelectedReleaseId = (state) => state.releases.selectedRelease;
1113
- var getReleasesById = (state) => state.releases.byId;
1114
- var getReleaseTags = (state) => state.releases.tags;
1115
- var getReleaseListState = (state) => state.releases.releasesList;
1116
- var getListedReleases = (state) => state.releases.releasesList.releaseIds;
1117
- var releaseDefaults = {};
1118
- var getReleaseMappingDefaults = () => releaseDefaults;
1119
- var getReleasesList = (0, import_toolkit5.createSelector)([getReleasesById, getListedReleases, getReleaseMappingDefaults], listItemMapper);
1120
- var getReleaseTagsById = (0, import_toolkit5.createSelector)([getReleaseTags], (releaseTags) => releaseTags.reduce((accu, key) => ({ ...accu, [key]: key }), {}));
1121
- var getHasReleases = (0, import_toolkit5.createSelector)(
1122
- [getReleaseListState, getReleasesById],
1123
- ({ searchTotal, total }, byId) => !!(Object.keys(byId).length || total || searchTotal)
1124
- );
1125
- var getSelectedRelease = (0, import_toolkit5.createSelector)([getReleasesById, getSelectedReleaseId], (byId, id) => byId[id || ""] ?? {});
1126
- var getSelectedReleases = (0, import_toolkit5.createSelector)([getReleaseListState, getReleasesList], ({ selection }, releases) => selection.map((index) => releases[index]));
1127
- var getDeltaJobsById = (state) => state.releases.deltaJobs;
1128
- var getDeltaJobById = (0, import_toolkit5.createSelector)([getDeltaJobsById, (_, jobId) => jobId], (byId, jobId) => byId[jobId]);
1129
- var getSelectedJobId = (state) => state.releases.selectedJob;
1130
- var getSelectedJob = (0, import_toolkit5.createSelector)([getDeltaJobsById, getSelectedJobId], (byId, jobId) => byId[jobId || ""]);
1131
-
1132
- // src/usersSlice/selectors.ts
1133
- var import_toolkit6 = require("@reduxjs/toolkit");
1134
- var emptyObject = {};
1135
- var getRolesById = (state) => state.users.rolesById;
1136
- var getTooltipsById = (state) => state.users.tooltips.byId;
1137
- var getGlobalSettings = (state) => state.users.globalSettings;
1138
- var getUserSettingsInitialized = (state) => state.users.userSettingsInitialized;
1139
- var getCurrentUserId = (state) => state.users.currentUser;
1140
- var getUsersById = (state) => state.users.byId;
1141
- var getUsersList = (0, import_toolkit6.createSelector)([getUsersById], (usersById) => Object.values(usersById));
1142
- var getCurrentUser = (0, import_toolkit6.createSelector)(
1143
- [getUsersById, getCurrentUserId],
1144
- (usersById, userId) => userId ? usersById[userId] ?? emptyObject : emptyObject
1145
- );
1146
- var getUserSettings = (state) => state.users.userSettings;
1147
- var getSelectedDeviceAttribute = (0, import_toolkit6.createSelector)(
1148
- [getUserSettings],
1149
- ({ columnSelection }) => columnSelection.map((attribute) => ({ attribute: attribute.key, scope: attribute.scope }))
1150
- );
1151
- var getIsDarkMode = (0, import_toolkit6.createSelector)([getUserSettings], ({ mode }) => isDarkMode(mode));
1152
- var getReadAllHelptips = (0, import_toolkit6.createSelector)(
1153
- [getTooltipsById],
1154
- (tooltips) => Object.values(tooltips).every(({ readState }) => readState === READ_STATES.read)
1155
- );
1156
- var getTooltipsState = (0, import_toolkit6.createSelector)(
1157
- [getTooltipsById, getUserSettings],
1158
- (byId, { tooltips = {} }) => Object.entries(byId).reduce(
1159
- (accu, [id, value]) => {
1160
- accu[id] = { ...accu[id], ...value };
1161
- return accu;
1162
- },
1163
- { ...tooltips }
1164
- )
1165
- );
1166
- var getHas2FA = (0, import_toolkit6.createSelector)(
1167
- [getCurrentUser],
1168
- (currentUser) => currentUser.hasOwnProperty("tfa_status") && currentUser.tfa_status === import_constants4.twoFAStates.enabled
1169
- );
1170
- var getIdAttribute = (0, import_toolkit6.createSelector)([getGlobalSettings], ({ id_attribute = { ...defaultIdAttribute } }) => id_attribute);
1171
- var getOfflineThresholdSettings = (0, import_toolkit6.createSelector)([getGlobalSettings], ({ offlineThreshold }) => ({
1172
- interval: offlineThreshold?.interval || DEVICE_ONLINE_CUTOFF.interval,
1173
- intervalUnit: offlineThreshold?.intervalUnit || DEVICE_ONLINE_CUTOFF.intervalName
1174
- }));
1175
- var getRolesList = (0, import_toolkit6.createSelector)([getRolesById], (rolesById2) => Object.entries(rolesById2).map(([value, role]) => ({ value, ...role })));
1176
- var getSecurityAlertDismissedTimestamp = (state) => state.users.userSettings.securityAlertDismissedTimestamp;
1177
-
1178
- // src/commonSelectors.ts
1179
- var getIsEnterprise = (0, import_toolkit7.createSelector)(
1180
- [getOrganization, getFeatures],
1181
- ({ plan = PLANS.os.id }, { isEnterprise, isHosted }) => isEnterprise || isHosted && plan === PLANS.enterprise.id
1182
- );
1183
- var getUserRoles = (0, import_toolkit7.createSelector)([getCurrentUser, getRolesById, getIsEnterprise], (currentUser, rolesById2, isEnterprise) => {
1184
- const isAdmin = currentUser.roles?.length ? currentUser.roles.some((role) => role === import_constants4.rolesByName.admin) : !isEnterprise;
1185
- const uiPermissions = isAdmin ? mapUserRolesToUiPermissions([import_constants4.rolesByName.admin], rolesById2) : mapUserRolesToUiPermissions(currentUser.roles || [], rolesById2);
1186
- return { isAdmin, uiPermissions };
1187
- });
1188
- var hasPermission = (thing, permission) => Object.values(thing).some((permissions) => permissions.includes(permission));
1189
- var getUserCapabilities = (0, import_toolkit7.createSelector)([getUserRoles, getIsServiceProvider], ({ uiPermissions }, isServiceProvider) => {
1190
- const canManageReleases = hasPermission(uiPermissions.releases, import_constants4.uiPermissionsById.manage.value);
1191
- const canReadReleases = canManageReleases || hasPermission(uiPermissions.releases, import_constants4.uiPermissionsById.read.value);
1192
- const canUploadReleases = canManageReleases || hasPermission(uiPermissions.releases, import_constants4.uiPermissionsById.upload.value);
1193
- const canAuditlog = uiPermissions.auditlog.includes(import_constants4.uiPermissionsById.read.value);
1194
- const canReadUsers = uiPermissions.userManagement.includes(import_constants4.uiPermissionsById.read.value);
1195
- const canManageUsers = uiPermissions.userManagement.includes(import_constants4.uiPermissionsById.manage.value);
1196
- const canReadDevices = hasPermission(uiPermissions.groups, import_constants4.uiPermissionsById.read.value);
1197
- const canWriteDevices = Object.values(uiPermissions.groups).some(
1198
- (groupPermissions) => groupPermissions.includes(import_constants4.uiPermissionsById.read.value) && groupPermissions.length > 1
1199
- );
1200
- const canTroubleshoot = hasPermission(uiPermissions.groups, import_constants4.uiPermissionsById.connect.value);
1201
- const canManageDevices = hasPermission(uiPermissions.groups, import_constants4.uiPermissionsById.manage.value);
1202
- const canConfigure = hasPermission(uiPermissions.groups, import_constants4.uiPermissionsById.configure.value);
1203
- const canDeploy = uiPermissions.deployments.includes(import_constants4.uiPermissionsById.deploy.value) || hasPermission(uiPermissions.groups, import_constants4.uiPermissionsById.deploy.value);
1204
- const canReadDeployments = uiPermissions.deployments.includes(import_constants4.uiPermissionsById.read.value);
1205
- return {
1206
- canAuditlog,
1207
- canConfigure,
1208
- canDeploy,
1209
- canManageDevices,
1210
- canManageReleases,
1211
- canManageUsers,
1212
- canReadDeployments,
1213
- canReadDevices,
1214
- canReadReleases,
1215
- canReadUsers,
1216
- canTroubleshoot,
1217
- canUploadReleases,
1218
- canWriteDevices,
1219
- groupsPermissions: uiPermissions.groups,
1220
- releasesPermissions: uiPermissions.releases,
1221
- SPTenant: isServiceProvider
1222
- };
1223
- });
1224
- var getTenantCapabilities = (0, import_toolkit7.createSelector)(
1225
- [getFeatures, getOrganization, getIsEnterprise],
1226
- ({
1227
- hasAuditlogs: isAuditlogEnabled,
1228
- hasDeviceConfig: isDeviceConfigEnabled,
1229
- hasDeviceConnect: isDeviceConnectEnabled,
1230
- hasMonitor: isMonitorEnabled,
1231
- isHosted
1232
- }, { addons = [], plan = PLANS.os.id }, isEnterprise) => {
1233
- const canDelta = isEnterprise || plan === PLANS.professional.id;
1234
- const hasAuditlogs = isAuditlogEnabled && isEnterprise;
1235
- const hasDeviceConfig = addons.some((addon) => addon.name === ADDONS.configure.id && addon.enabled) || isDeviceConfigEnabled && !isHosted;
1236
- const hasDeviceConnect = addons.some((addon) => addon.name === ADDONS.troubleshoot.id && addon.enabled) || isDeviceConnectEnabled && !isHosted;
1237
- const hasMonitor = isMonitorEnabled && addons.some((addon) => addon.name === ADDONS.monitor.id && addon.enabled);
1238
- return {
1239
- canDelta,
1240
- canRetry: canDelta,
1241
- canSchedule: canDelta,
1242
- hasAuditlogs,
1243
- hasDeviceConfig,
1244
- hasDeviceConnect,
1245
- hasFullFiltering: canDelta,
1246
- hasMonitor,
1247
- isEnterprise,
1248
- plan
1249
- };
1250
- }
1251
- );
1252
- var getFilterAttributes = (0, import_toolkit7.createSelector)(
1253
- [getGlobalSettings, getFilteringAttributes],
1254
- ({ previousFilters }, { identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }) => {
1255
- const deviceNameAttribute = { key: "name", value: "Name", scope: import_constants4.ATTRIBUTE_SCOPES.tags, category: import_constants4.ATTRIBUTE_SCOPES.tags, priority: 1 };
1256
- const deviceIdAttribute = { key: "id", value: "Device ID", scope: import_constants4.ATTRIBUTE_SCOPES.identity, category: import_constants4.ATTRIBUTE_SCOPES.identity, priority: 1 };
1257
- const checkInAttribute = { key: "check_in_time", value: "Latest activity", scope: import_constants4.ATTRIBUTE_SCOPES.system, category: import_constants4.ATTRIBUTE_SCOPES.system, priority: 4 };
1258
- const updateAttribute = { ...checkInAttribute, key: "updated_ts", value: "Last inventory update" };
1259
- const firstRequestAttribute = { key: "created_ts", value: "First request", scope: import_constants4.ATTRIBUTE_SCOPES.system, category: import_constants4.ATTRIBUTE_SCOPES.system, priority: 4 };
1260
- const attributes = [
1261
- ...previousFilters.map((item) => ({
1262
- ...item,
1263
- value: deviceIdAttribute.key === item.key ? deviceIdAttribute.value : item.key,
1264
- category: "recently used",
1265
- priority: 0
1266
- })),
1267
- deviceNameAttribute,
1268
- deviceIdAttribute,
1269
- ...identityAttributes.map((item) => ({ key: item, value: item, scope: import_constants4.ATTRIBUTE_SCOPES.identity, category: import_constants4.ATTRIBUTE_SCOPES.identity, priority: 1 })),
1270
- ...inventoryAttributes.map((item) => ({ key: item, value: item, scope: import_constants4.ATTRIBUTE_SCOPES.inventory, category: import_constants4.ATTRIBUTE_SCOPES.inventory, priority: 2 })),
1271
- ...tagAttributes.map((item) => ({ key: item, value: item, scope: import_constants4.ATTRIBUTE_SCOPES.tags, category: import_constants4.ATTRIBUTE_SCOPES.tags, priority: 3 })),
1272
- checkInAttribute,
1273
- updateAttribute,
1274
- firstRequestAttribute,
1275
- ...systemAttributes.map((item) => ({ key: item, value: item, scope: import_constants4.ATTRIBUTE_SCOPES.system, category: import_constants4.ATTRIBUTE_SCOPES.system, priority: 4 }))
1276
- ];
1277
- return (0, import_helpers4.attributeDuplicateFilter)(attributes, "key");
1278
- }
1279
- );
1280
- var getOnboardingState = (0, import_toolkit7.createSelector)([getOnboarding, getUserSettings], ({ complete, progress: progress2, showTips, ...remainder }, { onboarding = {} }) => ({
1281
- ...remainder,
1282
- ...onboarding,
1283
- complete: onboarding.complete || complete,
1284
- progress: Object.keys(onboardingSteps).findIndex((step) => step === progress2) > Object.keys(onboardingSteps).findIndex((step) => step === onboarding.progress) ? progress2 : onboarding.progress,
1285
- showTips: !onboarding.showTips ? onboarding.showTips : showTips
1286
- }));
1287
- var getDemoDeviceAddress = (0, import_toolkit7.createSelector)([getDevicesById, getOnboarding], (devicesById, { approach, demoArtifactPort }) => {
1288
- const demoDeviceAddress = `http://${(0, import_helpers4.getDemoDeviceAddress)(Object.values(devicesById), approach)}`;
1289
- return demoArtifactPort ? `${demoDeviceAddress}:${demoArtifactPort}` : demoDeviceAddress;
1290
- });
1291
- var getDeviceConfigDeployment = (0, import_toolkit7.createSelector)([getDeviceById, getDeploymentsById], (device, deploymentsById) => {
1292
- const { config = {} } = device;
1293
- const { deployment_id: configDeploymentId } = config;
1294
- const deviceConfigDeployment = deploymentsById[configDeploymentId] || {};
1295
- return { device, deviceConfigDeployment };
1296
- });
1297
- var getDeploymentRelease = (0, import_toolkit7.createSelector)(
1298
- [getDeploymentsById, getDeploymentsSelectionState, getReleasesById],
1299
- (deploymentsById, { selectedId }, releasesById) => {
1300
- const deployment = deploymentsById[selectedId] || {};
1301
- return deployment.artifact_name && releasesById[deployment.artifact_name] ? releasesById[deployment.artifact_name] : { device_types_compatible: [] };
1302
- }
1303
- );
1304
- var getSelectedDeploymentData = (0, import_toolkit7.createSelector)(
1305
- [getDeploymentsById, getDeploymentsSelectionState, getDevicesById, getSelectedDeploymentDeviceIds],
1306
- (deploymentsById, { selectedId }, devicesById, selectedDeviceIds) => {
1307
- const deployment = deploymentsById[selectedId] ?? {};
1308
- const { devices = {} } = deployment;
1309
- return {
1310
- deployment,
1311
- selectedDevices: selectedDeviceIds.map((deviceId) => ({ ...devicesById[deviceId], ...devices[deviceId] }))
1312
- };
1313
- }
1314
- );
1315
- var getAvailableIssueOptionsByType = (0, import_toolkit7.createSelector)(
1316
- [getTenantCapabilities, getIssueCountsByType],
1317
- ({ hasFullFiltering, hasMonitor }, issueCounts) => Object.values(import_constants4.DEVICE_ISSUE_OPTIONS).reduce((accu, { isCategory, key, needsFullFiltering, needsMonitor, title }) => {
1318
- if (isCategory || needsFullFiltering && !hasFullFiltering || needsMonitor && !hasMonitor) {
1319
- return accu;
1320
- }
1321
- accu[key] = { count: issueCounts[key].filtered, key, title };
1322
- return accu;
1323
- }, {})
1324
- );
1325
- var getGroupNames = (0, import_toolkit7.createSelector)([getGroupsById, getUserRoles], (groupsById, { uiPermissions }) => {
1326
- const { [UNGROUPED_GROUP.id]: ungrouped, ...groups } = groupsById;
1327
- return Object.keys(
1328
- Object.entries(groups).reduce((accu, [groupName, group]) => {
1329
- if (group.filterId || uiPermissions.groups[import_constants4.ALL_DEVICES]) {
1330
- accu[groupName] = group;
1331
- }
1332
- return accu;
1333
- }, uiPermissions.groups)
1334
- ).sort();
1335
- });
1336
- var getDeviceReportsForUser = (0, import_toolkit7.createSelector)(
1337
- [getUserSettings, getCurrentUser, getGlobalSettings, getDevicesById],
1338
- ({ reports }, { id: currentUserId }, globalSettings, devicesById) => reports || globalSettings[`${currentUserId}-reports`] || (Object.keys(devicesById).length ? defaultReports : [])
1339
- );
1340
- var listTypeDeviceIdMap = {
1341
- deviceList: getListedDevices,
1342
- search: getSearchedDevices
1343
- };
1344
- var deviceMapDefault = { defaultObject: { auth_sets: [] }, cutOffSize: DEVICE_LIST_MAXIMUM_LENGTH };
1345
- var getDeviceMappingDefaults = () => deviceMapDefault;
1346
- var getMappedDevicesList = (0, import_toolkit7.createSelector)(
1347
- [getDevicesById, (state, listType) => listTypeDeviceIdMap[listType](state), getDeviceMappingDefaults],
1348
- listItemMapper
1349
- );
1350
- var getAuditlogDevice = (0, import_toolkit7.createSelector)([getAuditLogEntry, getDevicesById], (auditlogEvent, devicesById) => {
1351
- let auditlogDevice = {};
1352
- if (auditlogEvent) {
1353
- const { object = {} } = auditlogEvent;
1354
- const { device = {}, id, type } = object;
1355
- auditlogDevice = type === "device" ? { id, ...device } : auditlogDevice;
1356
- }
1357
- return { ...auditlogDevice, ...devicesById[auditlogDevice.id] };
1358
- });
1359
- var getRelevantRoles = (0, import_toolkit7.createSelector)([getOrganization, getRolesList], ({ service_provider }, roles) => {
1360
- if (service_provider) {
1361
- return roles.reduce((accu, role) => {
1362
- if (import_constants4.rolesById[role.value]) {
1363
- return accu;
1364
- }
1365
- accu.push(role);
1366
- return accu;
1367
- }, Object.values(import_constants4.serviceProviderRolesById));
1368
- }
1369
- return Object.keys(import_constants4.rolesById).reverse().reduce((accu, key) => {
1370
- const index = accu.findIndex(({ value }) => value === key);
1371
- accu = [accu[index], ...accu.filter((item, itemIndex) => index !== itemIndex)];
1372
- return accu;
1373
- }, roles);
1374
- });
1375
- var getShowSecurityAlert = (0, import_toolkit7.createSelector)(
1376
- [getCurrentUser, getHas2FA, getFeatures, getIsEnterprise, getUserSettingsInitialized, getSecurityAlertDismissedTimestamp],
1377
- (currentUser, has2FA, features, isEnterprise, settingsInitialized, dismissedTimestamp) => {
1378
- const isOAuth2 = !!currentUser?.sso?.length;
1379
- const userVerified = !!currentUser.verified;
1380
- const isHosted = features?.isHosted;
1381
- const canHave2FA = isEnterprise || isHosted;
1382
- const secureOAuthUser = isOAuth2 && userVerified;
1383
- if (!currentUser || !settingsInitialized || has2FA || !canHave2FA || secureOAuthUser) {
1384
- return false;
1385
- }
1386
- if (dismissedTimestamp === null) {
1387
- return true;
1388
- }
1389
- const today = (0, import_dayjs.default)();
1390
- const dismissedMonthAgo = today.diff(dismissedTimestamp, "months");
1391
- return dismissedMonthAgo > 0;
1392
- }
1393
- );
1394
-
1395
- // src/store.ts
1396
- var import_react_redux = require("react-redux");
1397
- var import_helpers6 = require("@northern.tech/utils/helpers");
1398
- var import_toolkit16 = require("@reduxjs/toolkit");
1399
- var import_react = require("@sentry/react");
1400
-
1401
- // src/appSlice/index.ts
1402
- var import_toolkit8 = require("@reduxjs/toolkit");
1403
- var sliceName = "app";
1404
- var getYesterday = () => {
1405
- const today = /* @__PURE__ */ new Date();
1406
- today.setDate(today.getDate() - 1);
1407
- return today.toISOString();
1408
- };
1409
- var initialState = {
1410
- appInitDone: false,
1411
- cancelSource: void 0,
1412
- commit: "",
1413
- demoArtifactLink: "https://dgsbl4vditpls.cloudfront.net/mender-demo-artifact.mender",
1414
- hostAddress: null,
1415
- snackbar: {
1416
- action: void 0,
1417
- autoHideDuration: void 0,
1418
- message: "",
1419
- open: false,
1420
- preventClickToCopy: false
1421
- },
1422
- // return boolean rather than organization details
1423
- features: {
1424
- hasAiEnabled: false,
1425
- hasAuditlogs: false,
1426
- hasDeltaProgress: false,
1427
- hasMultitenancy: false,
1428
- hasDeviceConfig: false,
1429
- hasDeviceConnect: false,
1430
- hasFeedbackEnabled: false,
1431
- hasManifestsEnabled: false,
1432
- hasMonitor: false,
1433
- hasMCUEnabled: false,
1434
- isHosted: true,
1435
- isEnterprise: false
1436
- },
1437
- feedbackProbability: 0.3,
1438
- firstLoginAfterSignup: false,
1439
- hostedAnnouncement: "",
1440
- docsVersion: "",
1441
- recaptchaSiteKey: "",
1442
- searchState: {
1443
- deviceIds: [],
1444
- searchTerm: "",
1445
- searchTotal: 0,
1446
- isSearching: false,
1447
- sort: {
1448
- direction: import_constants4.SORTING_OPTIONS.desc
1449
- // key: null,
1450
- // scope: null
1451
- }
1452
- },
1453
- sentry: {
1454
- location: "",
1455
- replaysSessionSampleRate: 0.1,
1456
- tracesSampleRate: 1
1457
- },
1458
- stripeAPIKey: "",
1459
- trackerCode: "",
1460
- uploadsById: {
1461
- // id: { progress: 0, cancelSource: undefined }
1462
- },
1463
- newThreshold: getYesterday(),
1464
- offlineThreshold: getYesterday(),
1465
- versionInformation: {
1466
- Integration: "",
1467
- "Mender-Artifact": "",
1468
- "Meta-Mender": ""
1469
- },
1470
- yesterday: void 0
1471
- };
1472
- var appSlice = (0, import_toolkit8.createSlice)({
1473
- name: sliceName,
1474
- initialState,
1475
- reducers: {
1476
- setFeatures: (state, action) => {
1477
- state.features = {
1478
- ...state.features,
1479
- ...action.payload
1480
- };
1481
- },
1482
- setSnackbar: (state, { payload }) => {
1483
- if (typeof payload === "string" || payload instanceof String) {
1484
- state.snackbar = {
1485
- ...initialState.snackbar,
1486
- message: payload,
1487
- open: !!payload
1488
- };
1489
- return;
1490
- }
1491
- const { message, autoHideDuration, action, preventClickToCopy = false } = payload;
1492
- state.snackbar = {
1493
- message,
1494
- autoHideDuration,
1495
- action,
1496
- preventClickToCopy,
1497
- open: !!message
1498
- };
1499
- },
1500
- setFirstLoginAfterSignup: (state, action) => {
1501
- state.firstLoginAfterSignup = action.payload;
1502
- },
1503
- setAnnouncement: (state, action) => {
1504
- state.hostedAnnouncement = action.payload;
1505
- },
1506
- setSearchState: (state, action) => {
1507
- state.searchState = {
1508
- ...state.searchState,
1509
- ...action.payload
1510
- };
1511
- },
1512
- setOfflineThreshold: (state, action) => {
1513
- state.offlineThreshold = action.payload;
1514
- },
1515
- initUpload: (state, action) => {
1516
- const { id, upload } = action.payload;
1517
- state.uploadsById[id] = upload;
1518
- },
1519
- uploadProgress: (state, action) => {
1520
- const { id, progress: progress2 } = action.payload;
1521
- state.uploadsById[id] = {
1522
- ...state.uploadsById[id],
1523
- progress: progress2
1524
- };
1525
- },
1526
- cleanUpUpload: (state, action) => {
1527
- const { [action.payload]: current, ...remainder } = state.uploadsById;
1528
- state.uploadsById = remainder;
1529
- },
1530
- setVersionInformation: (state, action) => {
1531
- state.versionInformation = {
1532
- ...state.versionInformation,
1533
- ...action.payload
1534
- };
1535
- },
1536
- setEnvironmentData: (state, action) => ({ ...state, ...action.payload }),
1537
- setAppInitDone: (state) => {
1538
- state.appInitDone = true;
1539
- }
1540
- }
1541
- });
1542
- var actions = appSlice.actions;
1543
- var appSlice_default = appSlice.reducer;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_chunk = require("./chunk-CKQMccvm.cjs");
3
+ const require_devicesSlice_selectors = require("./devicesSlice/selectors.cjs");
4
+ const require_store = require("./store.cjs");
5
+ const require_thunks = require("./thunks.cjs");
6
+ let react = require("react");
7
+ let validator = require("validator");
8
+ validator = require_chunk.__toESM(validator);
9
+ //#region src/useDeploymentDevice.ts
10
+ const { isUUID } = validator.default;
11
+ const useDeploymentDevice = (deploymentName) => {
12
+ const isLoading = (0, react.useRef)(false);
13
+ const dispatch = require_store.useAppDispatch();
14
+ const hasDeviceInfo = !!require_store.useAppSelector(require_devicesSlice_selectors.getDevicesById)[deploymentName];
15
+ (0, react.useEffect)(() => {
16
+ if (isLoading.current) return;
17
+ isLoading.current = true;
18
+ if (isUUID(deploymentName) && !hasDeviceInfo) dispatch(require_thunks.getDeviceById(deploymentName)).unwrap().then(() => isLoading.current = false);
19
+ }, [
20
+ deploymentName,
21
+ dispatch,
22
+ hasDeviceInfo
23
+ ]);
24
+ };
25
+ //#endregion
26
+ exports.useDeploymentDevice = useDeploymentDevice;
1544
27
 
1545
- // src/deploymentsSlice/index.ts
1546
- var import_toolkit9 = require("@reduxjs/toolkit");
1547
- var sliceName2 = "deployments";
1548
- var initialState2 = {
1549
- byId: {
1550
- // [id]: { statistics: { status: {}, total_size }, devices: { [deploymentId]: { id, log } }, totalDeviceCount }
1551
- },
1552
- byStatus: {
1553
- finished: { deploymentIds: [], total: 0 },
1554
- inprogress: { deploymentIds: [], total: 0 },
1555
- pending: { deploymentIds: [], total: 0 },
1556
- scheduled: { deploymentIds: [], total: 0 }
1557
- },
1558
- config: {
1559
- binaryDelta: {
1560
- timeout: -1,
1561
- duplicatesWindow: -1,
1562
- compressionLevel: -1,
1563
- disableChecksum: false,
1564
- disableDecompression: false,
1565
- inputWindow: -1,
1566
- instructionBuffer: -1,
1567
- sourceWindow: -1
1568
- },
1569
- binaryDeltaLimits: {
1570
- timeout: { ...import_constants4.limitDefault, default: 60, max: 3600, min: 60 },
1571
- sourceWindow: import_constants4.limitDefault,
1572
- inputWindow: import_constants4.limitDefault,
1573
- duplicatesWindow: import_constants4.limitDefault,
1574
- instructionBuffer: import_constants4.limitDefault
1575
- }
1576
- },
1577
- deploymentDeviceLimit: 5e3,
1578
- selectedDeviceIds: [],
1579
- selectionState: {
1580
- finished: { ...import_constants4.DEVICE_LIST_DEFAULTS, endDate: void 0, search: "", selection: [], startDate: void 0, total: 0, type: "" },
1581
- inprogress: { ...import_constants4.DEVICE_LIST_DEFAULTS, perPage: DEFAULT_PENDING_INPROGRESS_COUNT, selection: [] },
1582
- pending: { ...import_constants4.DEVICE_LIST_DEFAULTS, perPage: DEFAULT_PENDING_INPROGRESS_COUNT, selection: [] },
1583
- scheduled: { ...import_constants4.DEVICE_LIST_DEFAULTS, selection: [] },
1584
- general: {
1585
- state: DEPLOYMENT_ROUTES.active.key,
1586
- showCreationDialog: false,
1587
- showReportDialog: false,
1588
- reportType: null
1589
- // DeploymentConstants.DEPLOYMENT_TYPES.configuration|DeploymentConstants.DEPLOYMENT_TYPES.software
1590
- },
1591
- selectedId: void 0
1592
- }
1593
- };
1594
- var deploymentsSlice = (0, import_toolkit9.createSlice)({
1595
- name: sliceName2,
1596
- initialState: initialState2,
1597
- reducers: {
1598
- createdDeployment: (state, action) => {
1599
- state.byId[action.payload.id] = {
1600
- ...deploymentPrototype,
1601
- ...action.payload
1602
- };
1603
- state.byStatus[DEPLOYMENT_STATES.pending].total = state.byStatus[DEPLOYMENT_STATES.pending].total + 1;
1604
- state.byStatus[DEPLOYMENT_STATES.pending].deploymentIds = [...state.byStatus.pending.deploymentIds, action.payload.id];
1605
- state.selectionState[DEPLOYMENT_STATES.pending].selection = [action.payload.id, ...state.selectionState[DEPLOYMENT_STATES.pending].selection];
1606
- state.selectionState[DEPLOYMENT_STATES.pending].total = (state.selectionState[DEPLOYMENT_STATES.pending].total || 0) + 1;
1607
- },
1608
- removedDeployment: (state, action) => {
1609
- const { [action.payload]: removedDeployment, ...remainder } = state.byId;
1610
- state.byId = remainder;
1611
- },
1612
- receivedDeployment: (state, action) => {
1613
- state.byId[action.payload.id] = {
1614
- ...state.byId[action.payload.id] || {},
1615
- ...action.payload
1616
- };
1617
- },
1618
- receivedDeploymentDeviceLog: (state, action) => {
1619
- const { id, deviceId, log } = action.payload;
1620
- const deployment = {
1621
- ...deploymentPrototype,
1622
- ...state.byId[id]
1623
- };
1624
- state.byId[id] = {
1625
- ...deployment,
1626
- devices: {
1627
- ...deployment.devices,
1628
- [deviceId]: {
1629
- ...deployment.devices[deviceId],
1630
- log
1631
- }
1632
- }
1633
- };
1634
- },
1635
- receivedDeploymentDevices: (state, action) => {
1636
- const { id, devices, selectedDeviceIds, totalDeviceCount } = action.payload;
1637
- state.byId[id] = {
1638
- ...state.byId[id],
1639
- devices,
1640
- totalDeviceCount
1641
- };
1642
- state.selectedDeviceIds = selectedDeviceIds;
1643
- },
1644
- receivedDeployments: (state, action) => {
1645
- state.byId = {
1646
- ...state.byId,
1647
- ...action.payload
1648
- };
1649
- },
1650
- receivedDeploymentsForStatus: (state, action) => {
1651
- const { status, deploymentIds, total } = action.payload;
1652
- state.byStatus[status].deploymentIds = deploymentIds;
1653
- state.byStatus[status].total = total;
1654
- },
1655
- selectDeploymentsForStatus: (state, action) => {
1656
- const { status, deploymentIds, total } = action.payload;
1657
- state.selectionState[status].selection = deploymentIds;
1658
- state.selectionState[status].total = total;
1659
- },
1660
- setDeploymentsState: (state, action) => {
1661
- state.selectionState = action.payload;
1662
- },
1663
- setDeploymentsConfig: (state, action) => {
1664
- state.config = action.payload;
1665
- }
1666
- }
1667
- });
1668
- var actions2 = deploymentsSlice.actions;
1669
- var deploymentsSlice_default = deploymentsSlice.reducer;
1670
-
1671
- // src/devicesSlice/index.ts
1672
- var import_helpers5 = require("@northern.tech/utils/helpers");
1673
- var import_toolkit10 = require("@reduxjs/toolkit");
1674
- var sliceName3 = "devices";
1675
- var initialState3 = {
1676
- byId: {
1677
- // [deviceId]: {
1678
- // ...,
1679
- // twinsByIntegration: { [external.provider.id]: twinData }
1680
- // }
1681
- },
1682
- byStatus: {
1683
- [import_constants4.DEVICE_STATES.accepted]: { deviceIds: [], counts: { standard: 0, micro: 0, system: 0, total: 0 } },
1684
- [import_constants4.DEVICE_STATES.pending]: { deviceIds: [], counts: { standard: 0, micro: 0, system: 0, total: 0 } },
1685
- [import_constants4.DEVICE_STATES.preauth]: { deviceIds: [], counts: { standard: 0, micro: 0, system: 0, total: 0 } },
1686
- [import_constants4.DEVICE_STATES.rejected]: { deviceIds: [], counts: { standard: 0, micro: 0, system: 0, total: 0 } }
1687
- },
1688
- deviceList: {
1689
- deviceIds: [],
1690
- ...import_constants4.DEVICE_LIST_DEFAULTS,
1691
- selectedAttributes: [],
1692
- selectedIssues: [],
1693
- selection: [],
1694
- sort: {
1695
- direction: import_constants4.SORTING_OPTIONS.desc
1696
- // key: null,
1697
- // scope: null
1698
- },
1699
- state: import_constants4.DEVICE_STATES.accepted,
1700
- total: 0,
1701
- refreshTrigger: false,
1702
- isLoading: false,
1703
- detailsTab: "",
1704
- open: false
1705
- },
1706
- filters: [
1707
- // { key: 'device_type', value: 'raspberry', operator: '$eq', scope: 'inventory' }
1708
- ],
1709
- filteringAttributes: { identityAttributes: [], inventoryAttributes: [], systemAttributes: [], tagAttributes: [] },
1710
- filteringAttributesLimit: 10,
1711
- filteringAttributesConfig: {
1712
- attributes: {
1713
- // inventory: ['some_attribute']
1714
- },
1715
- count: 0,
1716
- limit: 100
1717
- },
1718
- reports: [
1719
- // { items: [{ key: "someKey", count: 42 }], otherCount: 123, total: <otherCount + itemsCount> }
1720
- ],
1721
- total: 0,
1722
- limits: {
1723
- standard: 0,
1724
- micro: 0,
1725
- system: 0
1726
- },
1727
- groups: {
1728
- byId: {
1729
- // groupName: { deviceIds: [], total: 0, filters: [] },
1730
- // dynamo: { deviceIds: [], total: 3, filters: [{ a: 1 }] }
1731
- },
1732
- selectedGroup: void 0
1733
- }
1734
- };
1735
- var devicesSlice = (0, import_toolkit10.createSlice)({
1736
- name: sliceName3,
1737
- initialState: initialState3,
1738
- reducers: {
1739
- receivedGroups: (state, action) => {
1740
- state.groups.byId = action.payload;
1741
- },
1742
- addToGroup: (state, action) => {
1743
- const { group, deviceIds } = action.payload;
1744
- const maybeExistingGroup = {
1745
- filters: [],
1746
- deviceIds: [],
1747
- ...state.groups.byId[group]
1748
- };
1749
- state.groups.byId[group] = {
1750
- ...maybeExistingGroup,
1751
- deviceIds: [...maybeExistingGroup.deviceIds, ...deviceIds].filter(import_helpers5.duplicateFilter),
1752
- total: (maybeExistingGroup.total || 0) + 1
1753
- };
1754
- },
1755
- removeFromGroup: (state, action) => {
1756
- const { group, deviceIds: removedIds } = action.payload;
1757
- const { deviceIds = [], total = 0, ...maybeExistingGroup } = state.groups.byId[group] || {};
1758
- const changedGroup = {
1759
- ...maybeExistingGroup,
1760
- deviceIds: deviceIds.filter((id) => !removedIds.includes(id)),
1761
- total: Math.max(total - removedIds.length, 0)
1762
- };
1763
- if (changedGroup.total || changedGroup.deviceIds.length) {
1764
- state.groups.byId[group] = changedGroup;
1765
- return;
1766
- } else if (state.groups.selectedGroup === group) {
1767
- state.groups.selectedGroup = void 0;
1768
- }
1769
- const { [group]: removal, ...remainingById } = state.groups.byId;
1770
- state.groups.byId = remainingById;
1771
- },
1772
- addGroup: (state, action) => {
1773
- const { groupName, group } = action.payload;
1774
- state.groups.byId[groupName] = {
1775
- ...state.groups.byId[groupName],
1776
- ...group
1777
- };
1778
- },
1779
- selectGroup: (state, { payload: group }) => {
1780
- state.deviceList.deviceIds = group && state.groups.byId[group] && state.groups.byId[group].deviceIds && state.groups.byId[group].deviceIds.length > 0 ? state.groups.byId[group].deviceIds : [];
1781
- state.groups.selectedGroup = group;
1782
- },
1783
- removeGroup: (state, action) => {
1784
- const { [action.payload]: removal, ...remainingById } = state.groups.byId;
1785
- state.groups.byId = remainingById;
1786
- state.groups.selectedGroup = state.groups.selectedGroup === action.payload ? void 0 : state.groups.selectedGroup;
1787
- },
1788
- setDeviceListState: (state, action) => {
1789
- state.deviceList = {
1790
- ...state.deviceList,
1791
- ...action.payload,
1792
- sort: {
1793
- ...state.deviceList.sort,
1794
- ...action.payload.sort
1795
- }
1796
- };
1797
- },
1798
- setFilterAttributes: (state, action) => {
1799
- state.filteringAttributes = action.payload;
1800
- },
1801
- setFilterablesConfig: (state, action) => {
1802
- state.filteringAttributesConfig = action.payload;
1803
- },
1804
- receivedDevices: (state, action) => {
1805
- state.byId = {
1806
- ...state.byId,
1807
- ...action.payload
1808
- };
1809
- },
1810
- setDeviceFilters: (state, action) => {
1811
- if ((0, import_helpers5.deepCompare)(action.payload, state.filters)) {
1812
- return;
1813
- }
1814
- state.filters = action.payload.filter((filter) => filter.key && filter.operator && filter.scope && typeof filter.value !== "undefined");
1815
- },
1816
- setDeviceReports: (state, action) => {
1817
- state.reports = action.payload;
1818
- },
1819
- setDevicesByStatus: (state, action) => {
1820
- const { status, total, deviceIds } = action.payload;
1821
- if (total) {
1822
- state.byStatus[status].deviceIds = deviceIds;
1823
- state.byStatus[status].counts.total = total;
1824
- }
1825
- },
1826
- setDevicesCountByStatus: (state, action) => {
1827
- const { countsPerTier, status } = action.payload;
1828
- state.byStatus[status].counts = { ...countsPerTier, total: Object.values(countsPerTier).reduce((accu, tieredCount) => accu += tieredCount, 0) };
1829
- },
1830
- setDeviceLimits: (state, action) => {
1831
- state.limits = action.payload;
1832
- },
1833
- receivedDevice: (state, action) => {
1834
- state.byId[action.payload.id] = {
1835
- ...state.byId[action.payload.id],
1836
- ...action.payload
1837
- };
1838
- },
1839
- maybeUpdateDevicesByStatus: (state, action) => {
1840
- const { deviceId, authId } = action.payload;
1841
- const device = state.byId[deviceId];
1842
- const hasMultipleAuthSets = authId && device.auth_sets ? device.auth_sets.filter((authset) => authset.id !== authId).length > 0 : false;
1843
- if (!hasMultipleAuthSets && Object.values(import_constants4.DEVICE_STATES).includes(device.status)) {
1844
- const deviceIds = state.byStatus[device.status].deviceIds.filter((id) => id !== deviceId);
1845
- const deviceTier = device.attributes.tier || "standard";
1846
- state.byStatus[device.status] = {
1847
- deviceIds,
1848
- counts: {
1849
- ...state.byStatus[device.status].counts,
1850
- [deviceTier]: Math.max(0, state.byStatus[device.status].counts[deviceTier] - 1),
1851
- total: Math.max(0, state.byStatus[device.status].counts.total - 1)
1852
- }
1853
- };
1854
- }
1855
- }
1856
- }
1857
- });
1858
- var actions3 = devicesSlice.actions;
1859
- var devicesSlice_default = devicesSlice.reducer;
1860
-
1861
- // src/monitorSlice/index.ts
1862
- var import_toolkit11 = require("@reduxjs/toolkit");
1863
- var sliceName4 = "monitor";
1864
- var initialState4 = {
1865
- alerts: {
1866
- alertList: { ...import_constants4.DEVICE_LIST_DEFAULTS, total: 0 },
1867
- byDeviceId: {}
1868
- },
1869
- issueCounts: {
1870
- byType: Object.keys(import_constants4.DEVICE_ISSUE_OPTIONS).reduce((accu, key) => ({ ...accu, [key]: { filtered: 0, total: 0 } }), {})
1871
- },
1872
- settings: {
1873
- global: {
1874
- channels: {
1875
- ...Object.keys(import_constants4.alertChannels).reduce((accu, item) => ({ ...accu, [item]: { enabled: true } }), {})
1876
- }
1877
- }
1878
- }
1879
- };
1880
- var monitorSlice = (0, import_toolkit11.createSlice)({
1881
- name: sliceName4,
1882
- initialState: initialState4,
1883
- reducers: {
1884
- changeAlertChannel: (state, action) => {
1885
- const { channel, enabled } = action.payload;
1886
- state.settings.global.channels[channel] = { enabled };
1887
- },
1888
- receiveDeviceAlerts: (state, action) => {
1889
- const { deviceId, alerts } = action.payload;
1890
- state.alerts.byDeviceId[deviceId] = { alerts };
1891
- },
1892
- receiveLatestDeviceAlerts: (state, action) => {
1893
- const { deviceId, alerts } = action.payload;
1894
- state.alerts.byDeviceId[deviceId] = { ...state.alerts.byDeviceId[deviceId], latest: alerts };
1895
- },
1896
- receiveDeviceIssueCounts: (state, action) => {
1897
- const { issueType, counts } = action.payload;
1898
- state.issueCounts.byType[issueType] = counts;
1899
- },
1900
- setAlertListState: (state, action) => {
1901
- state.alerts.alertList = { ...state.alerts.alertList, ...action.payload };
1902
- }
1903
- }
1904
- });
1905
- var actions4 = monitorSlice.actions;
1906
- var monitorSlice_default = monitorSlice.reducer;
1907
-
1908
- // src/onboardingSlice/index.ts
1909
- var import_toolkit12 = require("@reduxjs/toolkit");
1910
- var sliceName5 = "onboarding";
1911
- var initialState5 = {
1912
- approach: null,
1913
- complete: false,
1914
- deviceType: null,
1915
- demoArtifactPort: 85,
1916
- progress: null,
1917
- showTips: null,
1918
- showTipsDialog: false
1919
- };
1920
- var onboardingSlice = (0, import_toolkit12.createSlice)({
1921
- name: sliceName5,
1922
- initialState: initialState5,
1923
- reducers: {
1924
- setOnboardingState: (state, action) => ({ ...state, ...action.payload }),
1925
- setDemoArtifactPort: (state, action) => {
1926
- state.demoArtifactPort = action.payload;
1927
- },
1928
- setShowOnboardingHelp: (state, action) => {
1929
- state.showTips = action.payload;
1930
- },
1931
- setShowDismissOnboardingTipsDialog: (state, action) => {
1932
- state.showTipsDialog = action.payload;
1933
- },
1934
- setOnboardingComplete: (state, action) => {
1935
- state.complete = action.payload;
1936
- },
1937
- setOnboardingProgress: (state, action) => {
1938
- state.progress = action.payload;
1939
- },
1940
- setOnboardingDeviceType: (state, action) => {
1941
- state.deviceType = action.payload;
1942
- },
1943
- setOnboardingApproach: (state, action) => {
1944
- state.approach = action.payload;
1945
- }
1946
- }
1947
- });
1948
- var actions5 = onboardingSlice.actions;
1949
- var onboardingSlice_default = onboardingSlice.reducer;
1950
-
1951
- // src/organizationSlice/index.ts
1952
- var import_toolkit13 = require("@reduxjs/toolkit");
1953
- var sliceName6 = "organization";
1954
- var initialState6 = {
1955
- card: {
1956
- last4: "",
1957
- expiration: { month: 1, year: 2020 },
1958
- brand: ""
1959
- },
1960
- intentId: null,
1961
- tenantList: {
1962
- ...TENANT_LIST_DEFAULT,
1963
- total: 0,
1964
- tenants: [],
1965
- selectedTenant: null,
1966
- sort: {
1967
- direction: import_constants4.SORTING_OPTIONS.desc,
1968
- key: "name"
1969
- }
1970
- },
1971
- organization: {
1972
- // id, name, status, tenant_token, plan
1973
- },
1974
- auditlog: {
1975
- events: [],
1976
- selectionState: {
1977
- ...import_constants4.DEVICE_LIST_DEFAULTS,
1978
- detail: void 0,
1979
- endDate: void 0,
1980
- selectedIssue: void 0,
1981
- sort: { direction: import_constants4.SORTING_OPTIONS.desc },
1982
- startDate: void 0,
1983
- total: 0,
1984
- type: void 0,
1985
- user: void 0,
1986
- isLoading: false
1987
- }
1988
- },
1989
- externalDeviceIntegrations: [
1990
- // { <connection_string|x509|...>, id, provider }
1991
- ],
1992
- ssoConfigs: [],
1993
- webhooks: {
1994
- // [id]: { events: [] }
1995
- // for now:
1996
- events: [],
1997
- eventsTotal: 0
1998
- }
1999
- };
2000
- var organizationSlice = (0, import_toolkit13.createSlice)({
2001
- name: sliceName6,
2002
- initialState: initialState6,
2003
- reducers: {
2004
- receiveAuditLogs: (state, action) => {
2005
- const { events, total } = action.payload;
2006
- state.auditlog.events = events;
2007
- state.auditlog.selectionState.total = total;
2008
- },
2009
- setAuditLogState: (state, action) => {
2010
- state.auditlog.selectionState = {
2011
- ...state.auditlog.selectionState,
2012
- ...action.payload
2013
- };
2014
- },
2015
- receiveCurrentCard: (state, action) => {
2016
- state.card = action.payload;
2017
- },
2018
- receiveSetupIntent: (state, action) => {
2019
- state.intentId = action.payload;
2020
- },
2021
- setOrganization: (state, action) => {
2022
- state.organization = { ...state.organization, ...action.payload };
2023
- },
2024
- setSubscription: (state, action) => {
2025
- state.organization.subscription = { ...state.organization.subscription, ...action.payload };
2026
- },
2027
- setProducts: (state, action) => {
2028
- state.products = action.payload;
2029
- },
2030
- setBillingProfile: (state, action) => {
2031
- state.organization.billing_profile = action.payload;
2032
- },
2033
- setTenantListState: (state, action) => {
2034
- state.tenantList = action.payload;
2035
- },
2036
- receiveExternalDeviceIntegrations: (state, action) => {
2037
- state.externalDeviceIntegrations = action.payload;
2038
- },
2039
- receiveSsoConfigs: (state, action) => {
2040
- state.ssoConfigs = action.payload;
2041
- },
2042
- receiveWebhookEvents: (state, action) => {
2043
- const { value, total } = action.payload;
2044
- state.webhooks.events = value;
2045
- state.webhooks.eventsTotal = total;
2046
- }
2047
- }
2048
- });
2049
- var actions6 = organizationSlice.actions;
2050
- var organizationSlice_default = organizationSlice.reducer;
2051
-
2052
- // src/releasesSlice/index.ts
2053
- var import_toolkit14 = require("@reduxjs/toolkit");
2054
- var sliceName7 = "releases";
2055
- var initialState7 = {
2056
- /*
2057
- * Return list of saved artifacts objects
2058
- */
2059
- /*
2060
- * return list of artifacts where duplicate names are collated with device compatibility lists combined
2061
- */
2062
- // artifacts: AppStore.getCollatedArtifacts(AppStore.getArtifactsRepo()),
2063
- artifacts: [],
2064
- /*
2065
- * Return list of saved release objects
2066
- */
2067
- byId: {
2068
- /*
2069
- [releaseName]: {
2070
- artifacts: [
2071
- {
2072
- id: '',
2073
- name: '',
2074
- description: '',
2075
- device_types_compatible: [],
2076
- ...
2077
- updates: [{
2078
- files: [
2079
- { size: 123, name: '' }
2080
- ],
2081
- type_info: { type: '' }
2082
- }],
2083
- url: '' // optional
2084
- }
2085
- ],
2086
- modified: ''
2087
- device_types_compatible,
2088
- name: '',
2089
- tags: ['something'],
2090
- notes: ''
2091
- }
2092
- */
2093
- },
2094
- deltaJobs: {
2095
- /*
2096
- [jobId]: {
2097
- id: '',
2098
- ...
2099
- }
2100
- */
2101
- },
2102
- deltaJobsList: {
2103
- ...import_constants4.DEVICE_LIST_DEFAULTS,
2104
- jobIds: [],
2105
- total: 0,
2106
- sort: {
2107
- direction: import_constants4.SORTING_OPTIONS.desc,
2108
- key: "started"
2109
- }
2110
- },
2111
- releasesList: {
2112
- ...import_constants4.DEVICE_LIST_DEFAULTS,
2113
- searchedIds: [],
2114
- releaseIds: [],
2115
- selection: [],
2116
- sort: {
2117
- direction: import_constants4.SORTING_OPTIONS.desc,
2118
- key: "modified"
2119
- },
2120
- isLoading: void 0,
2121
- searchTerm: "",
2122
- searchTotal: 0,
2123
- selectedTags: [],
2124
- total: 0,
2125
- type: ""
2126
- },
2127
- tags: [],
2128
- updateTypes: [],
2129
- selectedJob: null,
2130
- /*
2131
- * Return single release with corresponding Artifacts
2132
- */
2133
- selectedRelease: null
2134
- };
2135
- var releaseSlice = (0, import_toolkit14.createSlice)({
2136
- name: sliceName7,
2137
- initialState: initialState7,
2138
- reducers: {
2139
- receiveRelease: (state, action) => {
2140
- const { name } = action.payload;
2141
- state.byId[name] = action.payload;
2142
- },
2143
- receiveReleases: (state, action) => {
2144
- state.byId = action.payload;
2145
- },
2146
- receiveReleaseTags: (state, action) => {
2147
- state.tags = action.payload;
2148
- },
2149
- receiveReleaseTypes: (state, action) => {
2150
- state.updateTypes = action.payload;
2151
- },
2152
- removeRelease: (state, action) => {
2153
- const { [action.payload]: toBeRemoved, ...byId } = state.byId;
2154
- state.byId = byId;
2155
- state.selectedRelease = action.payload === state.selectedRelease ? null : state.selectedRelease;
2156
- },
2157
- selectedRelease: (state, action) => {
2158
- state.selectedRelease = action.payload;
2159
- },
2160
- setReleaseListState: (state, action) => {
2161
- state.releasesList = action.payload;
2162
- },
2163
- receivedDeltaJobs: (state, action) => {
2164
- const { jobs, total } = action.payload;
2165
- state.deltaJobs = jobs.reduce(
2166
- (accu, job) => {
2167
- accu[job.id] = {
2168
- ...accu[job.id],
2169
- ...job
2170
- };
2171
- return accu;
2172
- },
2173
- { ...state.deltaJobs }
2174
- );
2175
- state.deltaJobsList.jobIds = jobs.map((job) => job.id);
2176
- state.deltaJobsList.total = total;
2177
- },
2178
- receivedDeltaJobDetails: (state, action) => {
2179
- const job = action.payload;
2180
- state.deltaJobs[job.id] = {
2181
- ...state.deltaJobs[job.id],
2182
- ...job
2183
- };
2184
- },
2185
- setDeltaJobsListState: (state, action) => {
2186
- state.deltaJobsList = { ...state.deltaJobsList, ...action.payload };
2187
- },
2188
- setSelectedJob: (state, action) => {
2189
- state.selectedJob = action.payload;
2190
- }
2191
- }
2192
- });
2193
- var actions7 = releaseSlice.actions;
2194
- var releasesSlice_default = releaseSlice.reducer;
2195
-
2196
- // src/usersSlice/index.ts
2197
- var import_toolkit15 = require("@reduxjs/toolkit");
2198
- var sliceName8 = "users";
2199
- var initialState8 = {
2200
- byId: {},
2201
- currentUser: null,
2202
- currentSession: {
2203
- // { token: window.localStorage.getItem('JWT'), expiresAt: '2023-01-01T00:15:00.000Z' | undefined }, // expiresAt depending on the stay logged in setting
2204
- },
2205
- customColumns: [],
2206
- qrCode: null,
2207
- globalSettings: {
2208
- id_attribute: void 0,
2209
- previousFilters: [],
2210
- previousPhases: [],
2211
- retries: 0
2212
- },
2213
- permissionSetsById: {
2214
- ...import_constants4.defaultPermissionSets
2215
- },
2216
- rolesById: {
2217
- ...import_constants4.rolesById
2218
- },
2219
- rolesInitialized: false,
2220
- settingsInitialized: false,
2221
- showConnectDeviceDialog: false,
2222
- showFeedbackDialog: false,
2223
- showStartupNotification: false,
2224
- tooltips: {
2225
- byId: {
2226
- // <id>: { readState: <read|unread> } // this object is getting enhanced by the tooltip texts in the app constants
2227
- }
2228
- },
2229
- userSettings: {
2230
- columnSelection: [],
2231
- onboarding: {},
2232
- firstLoginTimestamp: null,
2233
- securityAlertDismissedTimestamp: null
2234
- },
2235
- userSettingsInitialized: false
2236
- };
2237
- var usersSlice = (0, import_toolkit15.createSlice)({
2238
- name: sliceName8,
2239
- initialState: initialState8,
2240
- reducers: {
2241
- receivedQrCode: (state, action) => {
2242
- state.qrCode = action.payload;
2243
- },
2244
- successfullyLoggedIn: (state, action) => {
2245
- state.currentSession = action.payload;
2246
- },
2247
- receivedUserList: (state, action) => {
2248
- state.byId = action.payload;
2249
- },
2250
- receivedUser: (state, action) => {
2251
- state.byId[action.payload.id] = action.payload;
2252
- state.currentUser = action.payload.id;
2253
- },
2254
- removedUser: (state, action) => {
2255
- const { [action.payload]: removedUser, ...byId } = state.byId;
2256
- state.byId = byId;
2257
- state.currentUser = state.currentUser === action.payload ? null : state.currentUser;
2258
- },
2259
- updatedUser: (state, action) => {
2260
- state.byId[action.payload.id] = {
2261
- ...state.byId[action.payload.id],
2262
- ...action.payload
2263
- };
2264
- },
2265
- receivedPermissionSets: (state, action) => {
2266
- state.permissionSetsById = action.payload;
2267
- },
2268
- receivedRoles: (state, action) => {
2269
- state.rolesById = action.payload;
2270
- state.rolesInitialized = true;
2271
- },
2272
- finishedRoleInitialization: (state, action) => {
2273
- state.rolesInitialized = action.payload;
2274
- },
2275
- createdRole: (state, action) => {
2276
- state.rolesById[action.payload.name] = {
2277
- ...state.rolesById[action.payload.name],
2278
- ...action.payload
2279
- };
2280
- },
2281
- removedRole: (state, action) => {
2282
- const { [action.payload]: toBeRemoved, ...rolesById2 } = state.rolesById;
2283
- state.rolesById = rolesById2;
2284
- },
2285
- setCustomColumns: (state, action) => {
2286
- state.customColumns = action.payload;
2287
- },
2288
- setGlobalSettings: (state, action) => {
2289
- state.settingsInitialized = true;
2290
- state.globalSettings = {
2291
- ...state.globalSettings,
2292
- ...action.payload
2293
- };
2294
- },
2295
- setUserSettings: (state, action) => {
2296
- state.userSettingsInitialized = true;
2297
- state.userSettings = {
2298
- ...state.userSettings,
2299
- ...action.payload
2300
- };
2301
- },
2302
- setTooltipState: (state, action) => {
2303
- const { id, readState = READ_STATES.read } = action.payload;
2304
- state.tooltips.byId[id] = { ...state.tooltips.byId[id], readState };
2305
- },
2306
- setTooltipsState: (state, action) => {
2307
- state.tooltips.byId = {
2308
- ...state.tooltips.byId,
2309
- ...action.payload
2310
- };
2311
- },
2312
- setShowFeedbackDialog: (state, action) => {
2313
- state.showFeedbackDialog = action.payload;
2314
- },
2315
- setShowConnectingDialog: (state, action) => {
2316
- state.showConnectDeviceDialog = action.payload;
2317
- },
2318
- setShowStartupNotification: (state, action) => {
2319
- state.showStartupNotification = action.payload;
2320
- }
2321
- }
2322
- });
2323
- var actions8 = usersSlice.actions;
2324
- var usersSlice_default = usersSlice.reducer;
2325
-
2326
- // src/actions.ts
2327
- var actions_default = {
2328
- ...actions,
2329
- ...actions2,
2330
- ...actions3,
2331
- ...actions4,
2332
- ...actions5,
2333
- ...actions6,
2334
- ...actions7,
2335
- ...actions8
2336
- };
2337
-
2338
- // src/auth.ts
2339
- var import_universal_cookie = __toESM(require("universal-cookie"), 1);
2340
- var cookies = new import_universal_cookie.default();
2341
- var emptySession = Object.freeze({ token: "", expiresAt: void 0 });
2342
- var tokenCache = "";
2343
- var getSessionInfo = () => {
2344
- let sessionInfo = { ...emptySession };
2345
- try {
2346
- sessionInfo = JSON.parse(window.localStorage.getItem("JWT") ?? "");
2347
- } catch {
2348
- }
2349
- const jwtTokenFromCookie = cookies.get("JWT", { doNotParse: true }) ?? "";
2350
- if (jwtTokenFromCookie) {
2351
- setSessionInfo({ token: jwtTokenFromCookie });
2352
- cookies.remove("JWT");
2353
- cookies.remove("JWT", { path: "/" });
2354
- return { token: jwtTokenFromCookie, expiresAt: void 0 };
2355
- }
2356
- if (sessionInfo.expiresAt && new Date(sessionInfo.expiresAt) < /* @__PURE__ */ new Date()) {
2357
- cleanUp();
2358
- return { ...emptySession };
2359
- }
2360
- sessionInfo.token = sessionInfo.token || "";
2361
- tokenCache = sessionInfo.token;
2362
- return sessionInfo;
2363
- };
2364
- var getToken = () => tokenCache ? tokenCache : getSessionInfo().token;
2365
- var setSessionInfo = ({ token, expiresAt }) => {
2366
- tokenCache = token;
2367
- window.localStorage.setItem("JWT", JSON.stringify({ token, expiresAt }));
2368
- };
2369
- var cleanUp = () => {
2370
- tokenCache = "";
2371
- cookies.remove("JWT");
2372
- cookies.remove("JWT", { path: "/" });
2373
- window.localStorage.removeItem("JWT");
2374
- window.localStorage.removeItem("oauth");
2375
- };
2376
-
2377
- // src/store.ts
2378
- var { setSnackbar, uploadProgress } = actions_default;
2379
- var keys = ["sessionDeploymentChecker", settingsKeys.initialized];
2380
- var resetEnvironment = () => keys.forEach((key) => window.sessionStorage.removeItem(key));
2381
- resetEnvironment();
2382
- var commonErrorFallback = "Please check your connection.";
2383
- var commonErrorHandler = (err, errorContext, dispatch, fallback, mightBeAuthRelated = false) => {
2384
- const errMsg = (0, import_helpers6.extractErrorMessage)(err, fallback);
2385
- if (mightBeAuthRelated || getToken()) {
2386
- dispatch(setSnackbar({ message: (0, import_helpers6.preformatWithRequestID)(err.response, `${errorContext} ${errMsg}`), action: "Copy to clipboard" }));
2387
- }
2388
- return Promise.reject(err);
2389
- };
2390
- var rootReducer = (0, import_toolkit16.combineReducers)({
2391
- app: appSlice_default,
2392
- devices: devicesSlice_default,
2393
- deployments: deploymentsSlice_default,
2394
- monitor: monitorSlice_default,
2395
- onboarding: onboardingSlice_default,
2396
- organization: organizationSlice_default,
2397
- releases: releasesSlice_default,
2398
- users: usersSlice_default
2399
- });
2400
- var sessionReducer = (state, action) => {
2401
- if (action.type === USER_LOGOUT) {
2402
- state = void 0;
2403
- }
2404
- return rootReducer(state, action);
2405
- };
2406
- var rejectionLoggerMiddleware = () => (next) => (action) => {
2407
- if (action.type.endsWith("/rejected")) {
2408
- const { error } = action;
2409
- console.error("Rejection in action:", action);
2410
- console.error(error.stack);
2411
- }
2412
- return next(action);
2413
- };
2414
- var tracingActionIgnoreList = [actions8.successfullyLoggedIn.type, "users/loginUser/pending", "users/loginUser/fulfilled", "users/loginUser/rejected"];
2415
- var sentryReduxEnhancer = (0, import_react.createReduxEnhancer)({
2416
- actionTransformer: (action) => {
2417
- if (tracingActionIgnoreList.includes(action.type)) {
2418
- return null;
2419
- }
2420
- return action;
2421
- },
2422
- // Transform the state to remove sensitive information
2423
- stateTransformer: (state) => {
2424
- const transformedState = {
2425
- ...state,
2426
- users: { ...state.users, currentSession: null },
2427
- organization: {
2428
- ...state.organization,
2429
- organization: {
2430
- ...state.organization.organization,
2431
- tenant_token: null
2432
- }
2433
- }
2434
- };
2435
- return transformedState;
2436
- }
2437
- });
2438
- var getConfiguredStore = (options = {}) => {
2439
- const { preloadedState = {}, ...config } = options;
2440
- return (0, import_toolkit16.configureStore)({
2441
- ...config,
2442
- preloadedState,
2443
- enhancers: (getDefaultEnhancers) => {
2444
- if (window.mender_environment?.sentry?.isReduxEnabled) {
2445
- return getDefaultEnhancers().concat(sentryReduxEnhancer);
2446
- }
2447
- return getDefaultEnhancers();
2448
- },
2449
- reducer: sessionReducer,
2450
- middleware: (getDefaultMiddleware) => getDefaultMiddleware({
2451
- immutableCheck: {
2452
- ignoredPaths: ["app.uploadsById"]
2453
- },
2454
- serializableCheck: {
2455
- ignoredActions: [actions6.receiveExternalDeviceIntegrations.name, uploadProgress.name],
2456
- ignoredActionPaths: ["uploads", /payload\..*$/, "meta.arg.file", "meta.arg.integration.configHint"],
2457
- ignoredPaths: ["app.uploadsById", "organization.externalDeviceIntegrations"]
2458
- }
2459
- }).concat(rejectionLoggerMiddleware)
2460
- });
2461
- };
2462
- var store = getConfiguredStore({
2463
- preloadedState: {}
2464
- });
2465
- var useAppDispatch = import_react_redux.useDispatch;
2466
- var createAppAsyncThunk = import_toolkit16.createAsyncThunk.withTypes();
2467
-
2468
- // src/appSlice/thunks.ts
2469
- var import_helpers7 = require("@northern.tech/utils/helpers");
2470
- var import_universal_cookie3 = __toESM(require("universal-cookie"), 1);
2471
-
2472
- // src/api/general-api.ts
2473
- var import_axios = __toESM(require("axios"), 1);
2474
- var import_universal_cookie2 = __toESM(require("universal-cookie"), 1);
2475
- var cookies2 = new import_universal_cookie2.default();
2476
- var unauthorizedRedirect = (error) => {
2477
- if (!(0, import_axios.isCancel)(error) && error.response?.status === 401 && getToken() && !window.location.pathname.endsWith("/subscription")) {
2478
- if (cookies2.get("JWT", { doNotParse: true })) {
2479
- window.location.reload();
2480
- return Promise.reject(error);
2481
- }
2482
- cleanUp();
2483
- window.location.replace("/ui/");
2484
- }
2485
- return Promise.reject(error);
2486
- };
2487
- var commonRequestConfig = { timeout: TIMEOUTS.refreshDefault, headers: { "Content-Type": "application/json" } };
2488
- var authenticatedRequest = import_axios.default.create(commonRequestConfig);
2489
- authenticatedRequest.interceptors.response.use((res) => res, unauthorizedRedirect);
2490
- authenticatedRequest.interceptors.request.use(
2491
- (config) => ({ ...config, headers: { ...config.headers, Authorization: `Bearer ${getToken()}` } }),
2492
- (error) => Promise.reject(error)
2493
- );
2494
- var Api = {
2495
- get: authenticatedRequest.get,
2496
- delete: (url, data) => authenticatedRequest.request({ method: "delete", url, data }),
2497
- patch: authenticatedRequest.patch,
2498
- post: authenticatedRequest.post,
2499
- postUnauthorized: (url, data, config = {}) => import_axios.default.post(url, data, { ...commonRequestConfig, ...config }),
2500
- put: authenticatedRequest.put,
2501
- upload: (url, formData, progress2, cancelSignal) => authenticatedRequest.post(url, formData, {
2502
- headers: { "Content-Type": "multipart/form-data" },
2503
- onUploadProgress: progress2,
2504
- timeout: 0,
2505
- signal: cancelSignal
2506
- }),
2507
- uploadPut: (url, formData, progress2, cancelSignal) => authenticatedRequest.put(url, formData, {
2508
- headers: { "Content-Type": "multipart/form-data" },
2509
- onUploadProgress: progress2,
2510
- timeout: 0,
2511
- signal: cancelSignal
2512
- })
2513
- };
2514
- var general_api_default = Api;
2515
-
2516
- // src/appSlice/thunks.ts
2517
- var cookies3 = new import_universal_cookie3.default();
2518
- var setFirstLoginAfterSignup = createAppAsyncThunk(`${sliceName}/setFirstLoginAfterSignup`, (firstLoginAfterSignup, { dispatch }) => {
2519
- cookies3.set("firstLoginAfterSignup", !!firstLoginAfterSignup, { maxAge: 60, path: "/", domain: ".mender.io", sameSite: false });
2520
- dispatch(actions.setFirstLoginAfterSignup(!!firstLoginAfterSignup));
2521
- });
2522
- var dateFunctionMap = {
2523
- getDays: "getDate",
2524
- setDays: "setDate"
2525
- };
2526
- var setOfflineThreshold = createAppAsyncThunk(`${sliceName}/setOfflineThreshold`, (_, { dispatch, getState }) => {
2527
- const { interval, intervalUnit } = getOfflineThresholdSettings(getState());
2528
- const today = /* @__PURE__ */ new Date();
2529
- const intervalName = `${intervalUnit.charAt(0).toUpperCase()}${intervalUnit.substring(1)}`;
2530
- const setter = dateFunctionMap[`set${intervalName}`] ?? `set${intervalName}`;
2531
- const getter = dateFunctionMap[`get${intervalName}`] ?? `get${intervalName}`;
2532
- today[setter](today[getter]() - interval);
2533
- let value;
2534
- try {
2535
- value = today.toISOString();
2536
- } catch {
2537
- return Promise.resolve(dispatch(actions.setSnackbar("There was an error saving the offline threshold, please check your settings.")));
2538
- }
2539
- return Promise.resolve(dispatch(actions.setOfflineThreshold(value)));
2540
- });
2541
- var versionRegex = new RegExp(/\d+\.\d+/);
2542
- var getLatestRelease = (thing) => {
2543
- const latestKey = Object.keys(thing).filter((key) => versionRegex.test(key)).sort().reverse()[0];
2544
- return thing[latestKey];
2545
- };
2546
- var repoKeyMap = {
2547
- integration: "Integration",
2548
- "mender-artifact": "Mender-Artifact"
2549
- };
2550
- var deductSaasState = (latestRelease, guiTags) => {
2551
- const latestGuiTag = guiTags.length ? guiTags[0].name : "";
2552
- return latestGuiTag ? latestGuiTag : latestRelease.release;
2553
- };
2554
- var getLatestReleaseInfo = createAppAsyncThunk(`${sliceName}/getLatestReleaseInfo`, (_, { dispatch, getState }) => {
2555
- if (!getFeatures(getState()).isHosted) {
2556
- return Promise.resolve();
2557
- }
2558
- return Promise.all([general_api_default.get("/versions.json"), general_api_default.get("/tags.json")]).catch((err) => {
2559
- console.log("init error:", (0, import_helpers7.extractErrorMessage)(err));
2560
- return Promise.resolve([{ data: {} }, { data: [] }]);
2561
- }).then(([{ data }, { data: guiTags }]) => {
2562
- if (!guiTags.length) {
2563
- return Promise.resolve();
2564
- }
2565
- const { releases } = data;
2566
- const latestRelease = getLatestRelease(getLatestRelease(releases));
2567
- const { latestRepos, latestVersions } = latestRelease.repos.reduce(
2568
- (accu, item) => {
2569
- if (repoKeyMap[item.name]) {
2570
- accu.latestVersions[repoKeyMap[item.name]] = getComparisonCompatibleVersion(item.version);
2571
- }
2572
- accu.latestRepos[item.name] = getComparisonCompatibleVersion(item.version);
2573
- return accu;
2574
- },
2575
- { latestVersions: { ...getState().app.versionInformation }, latestRepos: {} }
2576
- );
2577
- const info = deductSaasState(latestRelease, guiTags);
2578
- return Promise.resolve(
2579
- dispatch(
2580
- actions.setVersionInformation({
2581
- ...latestVersions,
2582
- Server: info,
2583
- latestRelease: {
2584
- releaseDate: latestRelease.release_date,
2585
- repos: latestRepos
2586
- }
2587
- })
2588
- )
2589
- );
2590
- });
2591
- });
2592
- var setSearchState = createAppAsyncThunk(`${sliceName}/setSearchState`, (searchState, { dispatch, getState }) => {
2593
- const currentState = getSearchState(getState());
2594
- const nextState = {
2595
- ...currentState,
2596
- ...searchState,
2597
- sort: {
2598
- ...currentState.sort,
2599
- ...searchState.sort
2600
- }
2601
- };
2602
- const tasks = [];
2603
- const { isSearching: currentSearching, deviceIds: currentDevices, searchTotal: currentTotal, ...currentRequestState } = currentState;
2604
- const { isSearching: nextSearching, deviceIds: nextDevices, searchTotal: nextTotal, ...nextRequestState } = nextState;
2605
- if (nextRequestState.searchTerm && !(0, import_helpers7.deepCompare)(currentRequestState, nextRequestState)) {
2606
- nextState.isSearching = true;
2607
- tasks.push(
2608
- dispatch(searchDevices(nextState)).unwrap().then((results) => {
2609
- const searchResult = results[results.length - 1];
2610
- return dispatch(actions.setSearchState({ ...searchResult, isSearching: false }));
2611
- }).catch(() => dispatch(actions.setSearchState({ isSearching: false, searchTotal: 0 })))
2612
- );
2613
- }
2614
- tasks.push(dispatch(actions.setSearchState(nextState)));
2615
- return Promise.all(tasks);
2616
- });
2617
-
2618
- // src/deploymentsSlice/thunks.ts
2619
- var import_helpers8 = require("@northern.tech/utils/helpers");
2620
- var import_tracking = __toESM(require("@northern.tech/utils/tracking"), 1);
2621
- var import_validator = __toESM(require("validator"), 1);
2622
- var { isUUID } = import_validator.default;
2623
- var { receivedDevice, setSnackbar: setSnackbar2 } = actions_default;
2624
- var { page: defaultPage, perPage: defaultPerPage } = import_constants4.DEVICE_LIST_DEFAULTS;
2625
- var deriveDeploymentGroup = ({ filter, group, groups = [], name }) => group || groups.length === 1 && !isUUID(name) ? groups[0] : filter?.name;
2626
- var transformDeployments = (deployments, deploymentsById) => deployments.sort((0, import_helpers8.customSort)(true, "created")).reduce(
2627
- (accu, item) => {
2628
- const filter = item.filter;
2629
- let deployment = {
2630
- ...deploymentPrototype,
2631
- ...deploymentsById[item.id],
2632
- ...item,
2633
- // TODO: explicitly set filter term types to address scope type mismatch in deployment specs
2634
- // @ts-expect-error: type misalignment in filter terms type
2635
- filter: filter ? { ...filter, name: filter.name ?? filter.id, filters: mapTermsToFilters(filter.terms) } : void 0,
2636
- name: decodeURIComponent(item.name)
2637
- };
2638
- deployment = { ...deployment, group: deriveDeploymentGroup(deployment) };
2639
- accu.deployments[item.id] = deployment;
2640
- accu.deploymentIds.push(item.id);
2641
- return accu;
2642
- },
2643
- { deployments: {}, deploymentIds: [] }
2644
- );
2645
- var getDeploymentsByStatus2 = createAppAsyncThunk(
2646
- `${sliceName2}/getDeploymentsByStatus`,
2647
- (options, { dispatch, getState }) => {
2648
- const { status, page = defaultPage, perPage = defaultPerPage, startDate, endDate, group, type, shouldSelect = true, sort = import_constants4.SORTING_OPTIONS.desc } = options;
2649
- const created_after = startDate ? `&created_after=${startDate}` : "";
2650
- const created_before = endDate ? `&created_before=${endDate}` : "";
2651
- const { attribute, scope } = getIdAttribute(getState());
2652
- const attributeHint = `&id_attribute=${attribute}&id_scope=${scope}`;
2653
- const search = group ? `&name=${group}${attributeHint}` : "";
2654
- const typeFilter = type ? `&type=${type}` : "";
2655
- return general_api_default.get(
2656
- `${import_constants4.deploymentsApiUrlV2}/deployments?status=${status}&per_page=${perPage}&page=${page}${created_after}${created_before}${search}${typeFilter}&sort=${sort}`
2657
- ).then((res) => {
2658
- const { deployments, deploymentIds } = transformDeployments(res.data, getState().deployments.byId);
2659
- const total = Number(res.headers[import_constants4.headerNames.total]);
2660
- let tasks = [
2661
- dispatch(actions2.receivedDeployments(deployments)),
2662
- dispatch(
2663
- actions2.receivedDeploymentsForStatus({
2664
- deploymentIds,
2665
- status,
2666
- total: !(startDate || endDate || group || type) ? total : getState().deployments.byStatus[status].total
2667
- })
2668
- )
2669
- ];
2670
- tasks = deploymentIds.reduce((accu, deploymentId) => {
2671
- if (deployments[deploymentId].type === DEPLOYMENT_TYPES.configuration) {
2672
- accu.push(dispatch(getSingleDeployment(deploymentId)));
2673
- }
2674
- return accu;
2675
- }, tasks);
2676
- if (shouldSelect) {
2677
- tasks.push(dispatch(actions2.selectDeploymentsForStatus({ deploymentIds, status, total })));
2678
- }
2679
- tasks.push({ deploymentIds, total });
2680
- return Promise.all(tasks);
2681
- });
2682
- }
2683
- );
2684
- var isWithinFirstMonth = (expirationDate) => {
2685
- if (!expirationDate) {
2686
- return false;
2687
- }
2688
- const endOfFirstMonth = new Date(expirationDate);
2689
- endOfFirstMonth.setMonth(endOfFirstMonth.getMonth() - 11);
2690
- return endOfFirstMonth > /* @__PURE__ */ new Date();
2691
- };
2692
- var trackDeploymentCreation = (totalDeploymentCount, hasDeployments, trial_expiration) => {
2693
- import_tracking.default.event({ category: "deployments", action: "create" });
2694
- if (!totalDeploymentCount) {
2695
- if (!hasDeployments) {
2696
- import_tracking.default.event({ category: "deployments", action: "create_initial_deployment" });
2697
- if (isWithinFirstMonth(trial_expiration)) {
2698
- import_tracking.default.event({ category: "deployments", action: "create_initial_deployment_first_month" });
2699
- }
2700
- }
2701
- import_tracking.default.event({ category: "deployments", action: "create_initial_deployment_user" });
2702
- }
2703
- };
2704
- var MAX_PREVIOUS_PHASES_COUNT = 5;
2705
- var createDeployment = createAppAsyncThunk(
2706
- `${sliceName2}/createDeployment`,
2707
- ({
2708
- newDeployment,
2709
- hasNewRetryDefault = false
2710
- }, { dispatch, getState }) => {
2711
- let request;
2712
- if ("filter_id" in newDeployment && newDeployment.filter_id) {
2713
- request = general_api_default.post(`${import_constants4.deploymentsApiUrlV2}/deployments`, newDeployment);
2714
- } else if ("group" in newDeployment && newDeployment.group) {
2715
- request = general_api_default.post(`${import_constants4.deploymentsApiUrl}/deployments/group/${newDeployment.group}`, newDeployment);
2716
- } else {
2717
- request = general_api_default.post(`${import_constants4.deploymentsApiUrl}/deployments`, newDeployment);
2718
- }
2719
- const totalDeploymentCount = Object.values(getDeploymentsByStatus(getState())).reduce(
2720
- (accu, item) => accu + item.total,
2721
- 0
2722
- );
2723
- const { hasDeployments } = getGlobalSettings(getState());
2724
- const { trial_expiration } = getOrganization(getState());
2725
- return request.catch((err) => commonErrorHandler(err, "Error creating deployment.", dispatch)).then((data) => {
2726
- const lastslashindex = data.headers.location.lastIndexOf("/");
2727
- const deploymentId = data.headers.location.substring(lastslashindex + 1);
2728
- const deployment = {
2729
- ...newDeployment,
2730
- id: deploymentId,
2731
- devices: "devices" in newDeployment && newDeployment.devices ? newDeployment.devices.map((id) => ({ id, status: "pending" })) : [],
2732
- statistics: { status: {} }
2733
- };
2734
- const tasks = [
2735
- dispatch(actions2.createdDeployment(deployment)),
2736
- dispatch(getSingleDeployment(deploymentId)),
2737
- dispatch(setSnackbar2({ message: "Deployment created successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))
2738
- ];
2739
- trackDeploymentCreation(totalDeploymentCount, hasDeployments, trial_expiration);
2740
- const { canManageUsers } = getUserCapabilities(getState());
2741
- if (canManageUsers) {
2742
- const { phases, retries } = newDeployment;
2743
- const { previousPhases = [], retries: previousRetries = 0 } = getGlobalSettings(getState());
2744
- const newSettings = { retries: hasNewRetryDefault ? retries : previousRetries, hasDeployments: true };
2745
- if (phases) {
2746
- const standardPhases = (0, import_helpers8.standardizePhases)(phases);
2747
- const prevPhases = previousPhases.map(import_helpers8.standardizePhases);
2748
- if (!prevPhases.find((previousPhaseList) => previousPhaseList.every((oldPhase) => standardPhases.find((phase) => (0, import_helpers8.deepCompare)(phase, oldPhase))))) {
2749
- prevPhases.push(standardPhases);
2750
- }
2751
- newSettings.previousPhases = prevPhases.slice(-1 * MAX_PREVIOUS_PHASES_COUNT);
2752
- }
2753
- tasks.push(dispatch(saveGlobalSettings(newSettings)));
2754
- }
2755
- return Promise.all(tasks);
2756
- });
2757
- }
2758
- );
2759
- var getDeploymentDevices = createAppAsyncThunk(
2760
- `${sliceName2}/getDeploymentDevices`,
2761
- (options, { dispatch, getState }) => {
2762
- const { id, page = defaultPage, perPage = defaultPerPage } = options;
2763
- return general_api_default.get(`${import_constants4.deploymentsApiUrl}/deployments/${id}/devices/list?&page=${page}&per_page=${perPage}`).then((response) => {
2764
- const { devices: deploymentDevices = {} } = getState().deployments.byId[id] || {};
2765
- const devices = response.data.reduce((accu, item) => {
2766
- accu[item.id] = item;
2767
- const log = (deploymentDevices[item.id] || {}).log;
2768
- if (log) {
2769
- accu[item.id].log = log;
2770
- }
2771
- return accu;
2772
- }, {});
2773
- const selectedDeviceIds = Object.keys(devices);
2774
- let tasks = [
2775
- dispatch(
2776
- actions2.receivedDeploymentDevices({
2777
- id,
2778
- devices,
2779
- selectedDeviceIds,
2780
- totalDeviceCount: Number(response.headers[import_constants4.headerNames.total])
2781
- })
2782
- )
2783
- ];
2784
- const devicesById = getDevicesById(getState());
2785
- const lackingData = selectedDeviceIds.reduce((accu, deviceId) => {
2786
- const device = devicesById[deviceId];
2787
- if (!device || !device.identity_data || !device.attributes || Object.keys(device.attributes).length === 0) {
2788
- accu.push(deviceId);
2789
- }
2790
- return accu;
2791
- }, []);
2792
- tasks = lackingData.reduce((accu, deviceId) => [...accu, dispatch(getDeviceById2(deviceId)), dispatch(getDeviceAuth(deviceId))], tasks);
2793
- return Promise.all(tasks);
2794
- });
2795
- }
2796
- );
2797
- var parseDeviceDeployment = ({
2798
- deployment: { id, artifact_name: release, status: deploymentStatus },
2799
- device: { created, deleted, id: deviceId, finished, status, log }
2800
- }) => ({
2801
- id,
2802
- release,
2803
- created,
2804
- deleted,
2805
- deviceId,
2806
- finished,
2807
- status,
2808
- log,
2809
- route: Object.values(DEPLOYMENT_ROUTES).reduce((accu, { key, states }) => {
2810
- if (!accu) {
2811
- return states.includes(deploymentStatus) ? key : accu;
2812
- }
2813
- return accu;
2814
- }, "")
2815
- });
2816
- var getDeviceDeployments = createAppAsyncThunk(`${sliceName2}/getDeviceDeployments`, (options, { dispatch }) => {
2817
- const { deviceId, filterSelection = [], page = defaultPage, perPage = defaultPerPage } = options;
2818
- const filters = filterSelection.map((item) => `&status=${item}`).join("");
2819
- return general_api_default.get(`${import_constants4.deploymentsApiUrl}/deployments/devices/${deviceId}?page=${page}&per_page=${perPage}${filters}`).then(
2820
- ({ data, headers }) => Promise.resolve(
2821
- dispatch(
2822
- receivedDevice({
2823
- id: deviceId,
2824
- deviceDeployments: data.map(parseDeviceDeployment),
2825
- deploymentsCount: Number(headers[import_constants4.headerNames.total])
2826
- })
2827
- )
2828
- )
2829
- ).catch((err) => commonErrorHandler(err, "There was an error retrieving the device deployment history:", dispatch));
2830
- });
2831
- var resetDeviceDeployments = createAppAsyncThunk(
2832
- `${sliceName2}/resetDeviceDeployments`,
2833
- (deviceId, { dispatch }) => general_api_default.delete(`${import_constants4.deploymentsApiUrl}/deployments/devices/${deviceId}/history`).then(() => Promise.resolve(dispatch(getDeviceDeployments({ deviceId })))).catch((err) => commonErrorHandler(err, "There was an error resetting the device deployment history:", dispatch))
2834
- );
2835
- var getSingleDeployment = createAppAsyncThunk(
2836
- `${sliceName2}/getSingleDeployment`,
2837
- (id, { dispatch, getState }) => general_api_default.get(`${import_constants4.deploymentsApiUrl}/deployments/${id}`).then(({ data }) => {
2838
- const { deployments } = transformDeployments([data], getState().deployments.byId);
2839
- return Promise.resolve(dispatch(actions2.receivedDeployment(deployments[id])));
2840
- })
2841
- );
2842
- var getDeviceLog = createAppAsyncThunk(
2843
- `${sliceName2}/getDeviceLog`,
2844
- ({ deploymentId, deviceId }, { dispatch }) => general_api_default.get(`${import_constants4.deploymentsApiUrl}/deployments/${deploymentId}/devices/${deviceId}/log`).catch((e) => {
2845
- console.log("no log here", e);
2846
- return Promise.reject();
2847
- }).then(
2848
- ({ data: log }) => Promise.all([Promise.resolve(dispatch(actions2.receivedDeploymentDeviceLog({ id: deploymentId, deviceId, log }))), Promise.resolve(log)])
2849
- )
2850
- );
2851
- var abortDeployment = createAppAsyncThunk(
2852
- `${sliceName2}/abortDeployment`,
2853
- (deploymentId, { dispatch, getState }) => general_api_default.put(`${import_constants4.deploymentsApiUrl}/deployments/${deploymentId}/status`, { status: "aborted" }).then(() => {
2854
- const deploymentsByStatus = getDeploymentsByStatus(getState());
2855
- let status = DEPLOYMENT_STATES.pending;
2856
- let index = deploymentsByStatus.pending.deploymentIds.findIndex((id) => id === deploymentId);
2857
- if (index < 0) {
2858
- status = DEPLOYMENT_STATES.inprogress;
2859
- index = deploymentsByStatus.inprogress.deploymentIds.findIndex((id) => id === deploymentId);
2860
- }
2861
- const deploymentIds = [...deploymentsByStatus[status].deploymentIds.slice(0, index), ...deploymentsByStatus[status].deploymentIds.slice(index + 1)];
2862
- const deploymentsById = getDeploymentsById(getState());
2863
- const deployments = deploymentIds.reduce((accu, id) => {
2864
- accu[id] = deploymentsById[id];
2865
- return accu;
2866
- }, {});
2867
- const total = Math.max(deploymentsByStatus[status].total - 1, 0);
2868
- return Promise.all([
2869
- dispatch(actions2.receivedDeployments(deployments)),
2870
- dispatch(actions2.receivedDeploymentsForStatus({ deploymentIds, status, total })),
2871
- dispatch(actions2.removedDeployment(deploymentId)),
2872
- dispatch(setSnackbar2("The deployment was successfully aborted"))
2873
- ]);
2874
- }).catch((err) => commonErrorHandler(err, "There was an error while aborting the deployment:", dispatch))
2875
- );
2876
- var updateDeploymentControlMap = createAppAsyncThunk(
2877
- `${sliceName2}/updateDeploymentControlMap`,
2878
- ({ deploymentId, updateControlMap }, { dispatch }) => general_api_default.patch(`${import_constants4.deploymentsApiUrl}/deployments/${deploymentId}`, { update_control_map: updateControlMap }).catch((err) => commonErrorHandler(err, "There was an error while updating the deployment status:", dispatch)).then(() => Promise.resolve(dispatch(getSingleDeployment(deploymentId))))
2879
- );
2880
- var setDeploymentsState = createAppAsyncThunk(`${sliceName2}/setDeploymentsState`, (selection, { dispatch, getState }) => {
2881
- const { page, perPage, ...selectionState } = selection;
2882
- const currentState = getState().deployments.selectionState;
2883
- const nextState = {
2884
- ...currentState,
2885
- ...selectionState,
2886
- ...Object.keys(DEPLOYMENT_STATES).reduce((accu, item) => {
2887
- accu[item] = {
2888
- ...currentState[item],
2889
- ...selectionState[item]
2890
- };
2891
- return accu;
2892
- }, {}),
2893
- general: {
2894
- ...currentState.general,
2895
- ...selectionState.general
2896
- }
2897
- };
2898
- const tasks = [dispatch(actions2.setDeploymentsState(nextState))];
2899
- if (nextState.selectedId && currentState.selectedId !== nextState.selectedId) {
2900
- tasks.push(dispatch(getSingleDeployment(nextState.selectedId)));
2901
- }
2902
- return Promise.all(tasks);
2903
- });
2904
- var deltaAttributeMappings = [
2905
- { here: "compressionLevel", there: "compression_level" },
2906
- { here: "disableChecksum", there: "disable_checksum" },
2907
- { here: "disableDecompression", there: "disable_external_decompression" },
2908
- { here: "sourceWindow", there: "source_window_size" },
2909
- { here: "inputWindow", there: "input_window_size" },
2910
- { here: "duplicatesWindow", there: "compression_duplicates_window" },
2911
- { here: "instructionBuffer", there: "instruction_buffer_size" }
2912
- ];
2913
- var mapExternalDeltaConfig = (config = {}) => deltaAttributeMappings.reduce((accu, { here, there }) => {
2914
- if (config[there] !== void 0) {
2915
- accu[here] = config[there];
2916
- }
2917
- return accu;
2918
- }, {});
2919
- var getDeploymentsConfig = createAppAsyncThunk(
2920
- `${sliceName2}/getDeploymentsConfig`,
2921
- (_, { dispatch, getState }) => general_api_default.get(`${import_constants4.deploymentsApiUrl}/config`).then(({ data }) => {
2922
- const oldConfig = getState().deployments.config;
2923
- const { delta = {} } = data;
2924
- const { binary_delta = {}, binary_delta_limits = {} } = delta;
2925
- const { xdelta_args = {} } = binary_delta;
2926
- const { xdelta_args_limits = {} } = binary_delta_limits;
2927
- const config = {
2928
- ...oldConfig,
2929
- hasDelta: Boolean(delta.enabled),
2930
- binaryDelta: {
2931
- ...oldConfig.binaryDelta,
2932
- ...mapExternalDeltaConfig(xdelta_args)
2933
- },
2934
- binaryDeltaLimits: {
2935
- ...oldConfig.binaryDeltaLimits,
2936
- ...mapExternalDeltaConfig(xdelta_args_limits)
2937
- }
2938
- };
2939
- return Promise.resolve(dispatch(actions2.setDeploymentsConfig(config)));
2940
- })
2941
- );
2942
- var deepClean = (source) => Object.entries(source).reduce((accu, [key, value]) => {
2943
- if (value !== void 0) {
2944
- const cleanedValue = typeof value === "object" ? deepClean(value) : value;
2945
- if (cleanedValue === void 0 || typeof cleanedValue === "object" && (0, import_helpers8.isEmpty)(cleanedValue)) {
2946
- return accu;
2947
- }
2948
- accu = { ...accu ?? {}, [key]: cleanedValue };
2949
- }
2950
- return accu;
2951
- }, void 0);
2952
- var saveDeltaDeploymentsConfig = createAppAsyncThunk(
2953
- `${sliceName2}/saveDeltaDeploymentsConfig`,
2954
- (config, { dispatch, getState }) => {
2955
- const configChange = {
2956
- xdelta_args: deltaAttributeMappings.reduce((accu, { here, there }) => {
2957
- if (config[here] !== void 0) {
2958
- accu[there] = config[here];
2959
- }
2960
- return accu;
2961
- }, {})
2962
- };
2963
- const result = deepClean(configChange);
2964
- if (!result) {
2965
- return Promise.resolve();
2966
- }
2967
- return general_api_default.put(`${import_constants4.deploymentsApiUrl}/config/binary_delta`, result).catch((err) => commonErrorHandler(err, "There was a problem storing your delta artifact generation configuration.", dispatch)).then(() => {
2968
- const oldConfig = getState().deployments.config;
2969
- const newConfig = {
2970
- ...oldConfig,
2971
- binaryDelta: {
2972
- ...oldConfig.binaryDelta,
2973
- ...config
2974
- }
2975
- };
2976
- return Promise.all([dispatch(actions2.setDeploymentsConfig(newConfig)), dispatch(setSnackbar2("Settings saved successfully"))]);
2977
- });
2978
- }
2979
- );
2980
- var generateDeploymentLogAnalysis = createAppAsyncThunk(
2981
- `${sliceName2}/generateDeploymentLogAnalysis`,
2982
- ({ deploymentId, deviceId }, { dispatch, rejectWithValue }) => general_api_default.get(`${import_constants4.apiRoot}/v1alpha1/deployments/deployments/${deploymentId}/devices/${deviceId}/log/explain`, { timeout: 60 * TIMEOUTS.oneSecond }).then(({ data: result }) => Promise.resolve(result)).catch((err) => {
2983
- if (err.response.status === 429) {
2984
- return rejectWithValue(err.response);
2985
- }
2986
- commonErrorHandler(err, "There was an error analysing the deployment log:", dispatch);
2987
- })
2988
- );
2989
-
2990
- // src/devicesSlice/thunks.tsx
2991
- var import_react_router_dom = require("react-router-dom");
2992
- var import_helpers9 = require("@northern.tech/utils/helpers");
2993
- var import_axios2 = require("axios");
2994
- var import_pluralize = __toESM(require("pluralize"), 1);
2995
- var import_uuid = require("uuid");
2996
- var import_jsx_runtime2 = require("react/jsx-runtime");
2997
- var { cleanUpUpload, initUpload, setSnackbar: setSnackbar3, uploadProgress: uploadProgress2 } = actions_default;
2998
- var { page: defaultPage2, perPage: defaultPerPage2 } = import_constants4.DEVICE_LIST_DEFAULTS;
2999
- var defaultAttributes = [
3000
- { scope: "identity", attribute: "status" },
3001
- { scope: "inventory", attribute: "artifact_name" },
3002
- { scope: "inventory", attribute: "device_type" },
3003
- { scope: "inventory", attribute: "mender_is_gateway" },
3004
- { scope: "inventory", attribute: "mender_gateway_system_id" },
3005
- { scope: "inventory", attribute: rootfsImageVersion },
3006
- { scope: "monitor", attribute: "alerts" },
3007
- { scope: "system", attribute: "created_ts" },
3008
- { scope: "system", attribute: "updated_ts" },
3009
- { scope: "system", attribute: "check_in_time" },
3010
- { scope: "system", attribute: "group" },
3011
- { scope: "tags", attribute: "name" }
3012
- ];
3013
- var getGroups2 = createAppAsyncThunk(
3014
- `${sliceName3}/getGroups`,
3015
- (_, { dispatch, getState }) => general_api_default.get(`${import_constants4.inventoryApiUrl}/groups`).then((res) => {
3016
- const state = getGroupsById(getState());
3017
- const dynamicGroups = Object.entries(state).reduce((accu, [id, group]) => {
3018
- if (group.id || group.filters?.length && id !== UNGROUPED_GROUP.id) {
3019
- accu[id] = group;
3020
- }
3021
- return accu;
3022
- }, {});
3023
- const groups = res.data.reduce((accu, group) => {
3024
- accu[group] = { deviceIds: [], filters: [], total: 0, ...state[group] };
3025
- return accu;
3026
- }, dynamicGroups);
3027
- const filters = [{ key: "group", value: res.data, operator: import_constants4.DEVICE_FILTERING_OPTIONS.$nin.key, scope: "system" }];
3028
- return Promise.all([
3029
- dispatch(actions3.receivedGroups(groups)),
3030
- dispatch(getDevicesByStatus2({ filterSelection: filters, group: "", page: 1, perPage: 1, status: void 0 }))
3031
- ]).then((promises) => {
3032
- const devicesRetrieval = promises[promises.length - 1] || [];
3033
- const { payload } = devicesRetrieval || {};
3034
- const result = payload[payload.length - 1] || {};
3035
- if (!result.total) {
3036
- return Promise.resolve();
3037
- }
3038
- return Promise.resolve(
3039
- dispatch(
3040
- actions3.addGroup({
3041
- groupName: UNGROUPED_GROUP.id,
3042
- group: { filters: [{ key: "group", value: res.data, operator: import_constants4.DEVICE_FILTERING_OPTIONS.$nin.key, scope: "system" }] }
3043
- })
3044
- )
3045
- );
3046
- });
3047
- })
3048
- );
3049
- var addDevicesToGroup = createAppAsyncThunk(
3050
- `${sliceName3}/addDevicesToGroup`,
3051
- ({ group, deviceIds, isCreation }, { dispatch }) => general_api_default.patch(`${import_constants4.inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(() => dispatch(actions3.addToGroup({ group, deviceIds }))).finally(() => isCreation ? Promise.resolve(dispatch(getGroups2())) : {})
3052
- );
3053
- var removeDevicesFromGroup = createAppAsyncThunk(
3054
- `${sliceName3}/removeDevicesFromGroup`,
3055
- ({ group, deviceIds }, { dispatch }) => general_api_default.delete(`${import_constants4.inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(
3056
- () => Promise.all([
3057
- dispatch(actions3.removeFromGroup({ group, deviceIds })),
3058
- dispatch(
3059
- setSnackbar3({
3060
- message: `The ${(0, import_pluralize.default)("devices", deviceIds.length)} ${(0, import_pluralize.default)("were", deviceIds.length)} removed from the group`,
3061
- autoHideDuration: TIMEOUTS.fiveSeconds
3062
- })
3063
- )
3064
- ])
3065
- )
3066
- );
3067
- var getGroupNotification = (newGroup, selectedGroup) => {
3068
- const successMessage = "The group was updated successfully";
3069
- if (newGroup === selectedGroup) {
3070
- return { message: successMessage, autoHideDuration: TIMEOUTS.fiveSeconds };
3071
- }
3072
- return {
3073
- action: "",
3074
- autoHideDuration: TIMEOUTS.fiveSeconds,
3075
- message: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
3076
- successMessage,
3077
- " - ",
3078
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_router_dom.Link, { to: `/devices?inventory=group:eq:${newGroup}`, children: "click here" }),
3079
- " to see it."
3080
- ] }),
3081
- preventClickToCopy: true
3082
- };
3083
- };
3084
- var addStaticGroup = createAppAsyncThunk(
3085
- `${sliceName3}/addStaticGroup`,
3086
- ({ group, devices }, { dispatch, getState }) => Promise.resolve(dispatch(addDevicesToGroup({ group, deviceIds: devices.map(({ id }) => id), isCreation: true }))).then(
3087
- () => Promise.resolve(
3088
- dispatch(
3089
- actions3.addGroup({
3090
- group: { deviceIds: [], total: 0, filters: [], ...getState().devices.groups.byId[group] },
3091
- groupName: group
3092
- })
3093
- )
3094
- ).then(
3095
- () => Promise.all([
3096
- dispatch(setDeviceListState({ setOnly: true })),
3097
- dispatch(getGroups2()),
3098
- dispatch(setSnackbar3(getGroupNotification(group, getState().devices.groups.selectedGroup)))
3099
- ])
3100
- )
3101
- ).catch((err) => commonErrorHandler(err, `Group could not be updated:`, dispatch))
3102
- );
3103
- var removeReportsByGroupName = createAppAsyncThunk(`${sliceName3}/removeReportsByGroupName`, (groupName, { dispatch, getState }) => {
3104
- if (!groupName) return Promise.resolve();
3105
- const reports = getDeviceReportsForUser(getState());
3106
- const filteredReports = reports.filter((report) => report.group !== groupName);
3107
- dispatch(saveUserSettings({ reports: filteredReports }));
3108
- });
3109
- var removeStaticGroup = createAppAsyncThunk(
3110
- `${sliceName3}/removeStaticGroup`,
3111
- (groupName, { dispatch }) => general_api_default.delete(`${import_constants4.inventoryApiUrl}/groups/${groupName}`).then(
3112
- () => Promise.all([
3113
- dispatch(actions3.removeGroup(groupName)),
3114
- dispatch(removeReportsByGroupName(groupName)),
3115
- dispatch(getGroups2()),
3116
- dispatch(setSnackbar3({ message: "Group was removed successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))
3117
- ])
3118
- )
3119
- );
3120
- var getDynamicGroup = createAppAsyncThunk(
3121
- `${sliceName3}/getDynamicGroupById`,
3122
- (id, { dispatch }) => general_api_default.get(`${import_constants4.inventoryApiUrlV2}/filters/${id}`).catch((err) => {
3123
- if (err.response && err.response.status === 404) {
3124
- throw new Error("Request failed with status code 404");
3125
- }
3126
- return commonErrorHandler(err, `Error retrieving the group: `, dispatch, commonErrorFallback);
3127
- })
3128
- );
3129
- var getDynamicGroups = createAppAsyncThunk(
3130
- `${sliceName3}/getDynamicGroups`,
3131
- (_, { dispatch, getState }) => general_api_default.get(`${import_constants4.inventoryApiUrlV2}/filters?per_page=${MAX_PAGE_SIZE}`).then(({ data: filters }) => {
3132
- const state = getGroupsById(getState());
3133
- const staticGroups = Object.entries(state).reduce((accu, [id, group]) => {
3134
- if (!(group.id || group.filters?.length)) {
3135
- accu[id] = group;
3136
- }
3137
- return accu;
3138
- }, {});
3139
- const groups = (filters || []).reduce((accu, filter) => {
3140
- accu[filter.name] = {
3141
- deviceIds: [],
3142
- total: 0,
3143
- ...state[filter.name],
3144
- id: filter.id,
3145
- filters: mapTermsToFilters(filter.terms)
3146
- };
3147
- return accu;
3148
- }, staticGroups);
3149
- return Promise.resolve(dispatch(actions3.receivedGroups(groups)));
3150
- }).catch(() => console.log("Dynamic group retrieval failed - likely accessing a non-enterprise backend"))
3151
- );
3152
- var addDynamicGroup = createAppAsyncThunk(
3153
- `${sliceName3}/addDynamicGroup`,
3154
- ({ groupName, filterPredicates }, { dispatch, getState }) => general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters`, { name: groupName, terms: mapFiltersToTerms(filterPredicates) }).then(
3155
- (res) => Promise.resolve(
3156
- dispatch(
3157
- actions3.addGroup({
3158
- groupName,
3159
- group: {
3160
- id: res.headers[import_constants4.headerNames.location].substring(res.headers[import_constants4.headerNames.location].lastIndexOf("/") + 1),
3161
- filters: filterPredicates
3162
- }
3163
- })
3164
- )
3165
- ).then(() => {
3166
- const { cleanedFilters } = getGroupFilters(groupName, getState().devices.groups);
3167
- return Promise.all([
3168
- dispatch(actions3.setDeviceFilters(cleanedFilters)),
3169
- dispatch(setSnackbar3(getGroupNotification(groupName, getState().devices.groups.selectedGroup))),
3170
- dispatch(getDynamicGroups())
3171
- ]);
3172
- })
3173
- ).catch((err) => commonErrorHandler(err, `Group could not be updated:`, dispatch))
3174
- );
3175
- var updateDynamicGroup = createAppAsyncThunk(
3176
- `${sliceName3}/updateDynamicGroup`,
3177
- ({ groupName, filterPredicates }, { dispatch, getState }) => {
3178
- const filterId = getState().devices.groups.byId[groupName].id;
3179
- return general_api_default.delete(`${import_constants4.inventoryApiUrlV2}/filters/${filterId}`).then(
3180
- () => Promise.resolve(dispatch(addDynamicGroup({ groupName, filterPredicates })))
3181
- );
3182
- }
3183
- );
3184
- var removeDynamicGroup = createAppAsyncThunk(`${sliceName3}/removeDynamicGroup`, (groupName, { dispatch, getState }) => {
3185
- const filterId = getState().devices.groups.byId[groupName].id;
3186
- return general_api_default.delete(`${import_constants4.inventoryApiUrlV2}/filters/${filterId}`).then(
3187
- () => Promise.all([
3188
- dispatch(actions3.removeGroup(groupName)),
3189
- dispatch(removeReportsByGroupName(groupName)),
3190
- dispatch(setSnackbar3({ message: "Group was removed successfully", autoHideDuration: TIMEOUTS.fiveSeconds }))
3191
- ])
3192
- );
3193
- });
3194
- var getGroupFilters = (group, groupsState, filters = []) => {
3195
- const groupName = group === UNGROUPED_GROUP.id || group === UNGROUPED_GROUP.name ? UNGROUPED_GROUP.id : group;
3196
- const selectedGroup = groupsState.byId[groupName];
3197
- const groupFilterLength = selectedGroup?.filters?.length || 0;
3198
- const cleanedFilters = groupFilterLength ? [...filters, ...selectedGroup.filters || []].filter(filtersFilter) : filters;
3199
- return { cleanedFilters, groupName, selectedGroup, groupFilterLength };
3200
- };
3201
- var selectGroup = createAppAsyncThunk(
3202
- `${sliceName3}/selectGroup`,
3203
- ({ group, filters = [] }, { dispatch, getState }) => {
3204
- const { cleanedFilters, groupName, selectedGroup, groupFilterLength } = getGroupFilters(group, getState().devices.groups, filters);
3205
- if (getSelectedGroup(getState()) === groupName && (filters.length === 0 && !groupFilterLength || filters.length === cleanedFilters.length)) {
3206
- return Promise.resolve();
3207
- }
3208
- const tasks = [];
3209
- if (groupFilterLength) {
3210
- tasks.push(dispatch(actions3.setDeviceFilters(cleanedFilters)));
3211
- } else {
3212
- tasks.push(dispatch(actions3.setDeviceFilters(filters)));
3213
- tasks.push(dispatch(getGroupDevices({ group: groupName, perPage: 1, shouldIncludeAllStates: true })));
3214
- }
3215
- const selectedGroupName = selectedGroup || !Object.keys(getGroupsById(getState())).length ? groupName : void 0;
3216
- tasks.push(dispatch(actions3.selectGroup(selectedGroupName)));
3217
- return Promise.all(tasks);
3218
- }
3219
- );
3220
- var getEarliestTs = (dateA = "", dateB = "") => !dateA || !dateB ? dateA || dateB : dateA < dateB ? dateA : dateB;
3221
- var reduceReceivedDevices = (devices, ids, state, status) => devices.reduce(
3222
- (accu, device) => {
3223
- const stateDevice = getDeviceById(state, device.id);
3224
- const {
3225
- attributes: storedAttributes = {},
3226
- identity_data: storedIdentity = {},
3227
- monitor: storedMonitor = {},
3228
- tags: storedTags = {},
3229
- group: storedGroup
3230
- } = stateDevice;
3231
- const { identity, inventory, monitor, system = {}, tags } = mapDeviceAttributes(device.attributes);
3232
- device.tags = { ...storedTags, ...tags };
3233
- device.group = system.group ?? storedGroup;
3234
- device.monitor = { ...storedMonitor, ...monitor };
3235
- device.identity_data = { ...storedIdentity, ...identity, ...device.identity_data ? device.identity_data : {} };
3236
- device.status = status ? status : device.status || identity.status;
3237
- device.check_in_time_rounded = system.check_in_time ?? stateDevice.check_in_time_rounded;
3238
- device.check_in_time_exact = device.check_in_time ?? stateDevice.check_in_time_exact;
3239
- device.created_ts = getEarliestTs(getEarliestTs(system.created_ts, device.created_ts), stateDevice.created_ts);
3240
- device.updated_ts = device.attributes ? device.updated_ts : stateDevice.updated_ts;
3241
- device.isNew = new Date(device.created_ts) > new Date(state.app.newThreshold);
3242
- device.isOffline = new Date(device.check_in_time_rounded) < new Date(state.app.offlineThreshold) || device.check_in_time_rounded === void 0;
3243
- device.attributes = device.attributes ? { ...storedAttributes, ...inventory } : storedAttributes;
3244
- accu.devicesById[device.id] = { ...stateDevice, ...device };
3245
- accu.ids.push(device.id);
3246
- return accu;
3247
- },
3248
- { ids, devicesById: {} }
3249
- );
3250
- var getGroupDevices = createAppAsyncThunk(`${sliceName3}/getGroupDevices`, (options, { dispatch, getState }) => {
3251
- const { group, shouldIncludeAllStates, ...remainder } = options;
3252
- const { cleanedFilters: filterSelection } = getGroupFilters(group, getState().devices.groups);
3253
- return dispatch(
3254
- getDevicesByStatus2({
3255
- ...remainder,
3256
- filterSelection,
3257
- group,
3258
- status: shouldIncludeAllStates ? void 0 : import_constants4.DEVICE_STATES.accepted
3259
- })
3260
- ).unwrap().then((results) => {
3261
- if (!group) {
3262
- return Promise.resolve();
3263
- }
3264
- const { deviceAccu, total } = results[results.length - 1];
3265
- const stateGroup = getState().devices.groups.byId[group];
3266
- if (!stateGroup && !total && !deviceAccu.ids.length) {
3267
- return Promise.resolve();
3268
- }
3269
- return Promise.resolve(
3270
- dispatch(
3271
- actions3.addGroup({
3272
- group: {
3273
- deviceIds: deviceAccu.ids.length === total || stateGroup && stateGroup.deviceIds && deviceAccu.ids.length > stateGroup.deviceIds ? deviceAccu.ids : stateGroup.deviceIds,
3274
- total
3275
- },
3276
- groupName: group
3277
- })
3278
- )
3279
- );
3280
- });
3281
- });
3282
- var getAllGroupDevices = createAppAsyncThunk(
3283
- `${sliceName3}/getAllGroupDevices`,
3284
- ({ group, attribute }, { dispatch, getState }) => {
3285
- if (!group || !!group && (!getGroupsById(getState())[group] || getGroupsById(getState())[group].filters.length)) {
3286
- return Promise.resolve();
3287
- }
3288
- const { attributes, filterTerms } = prepareSearchArguments({
3289
- filters: [],
3290
- group,
3291
- state: getState(),
3292
- status: import_constants4.DEVICE_STATES.accepted
3293
- });
3294
- const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage2, devices = []) => general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3295
- page,
3296
- per_page: perPage,
3297
- filters: filterTerms,
3298
- attributes: [...attributes, { scope: "inventory", attribute }]
3299
- }).then((res) => {
3300
- const state = getState();
3301
- const deviceAccu = reduceReceivedDevices(res.data, devices, state);
3302
- dispatch(actions3.receivedDevices(deviceAccu.devicesById));
3303
- const total = Number(res.headers[import_constants4.headerNames.total]);
3304
- if (total > perPage * page) {
3305
- return getAllDevices(perPage, page + 1, deviceAccu.ids);
3306
- }
3307
- return Promise.resolve(dispatch(actions3.addGroup({ group: { deviceIds: deviceAccu.ids, total: deviceAccu.ids.length }, groupName: group })));
3308
- });
3309
- return getAllDevices();
3310
- }
3311
- );
3312
- var getAllDynamicGroupDevices = createAppAsyncThunk(
3313
- `${sliceName3}/getAllDynamicGroupDevices`,
3314
- ({ group, attribute }, { dispatch, getState }) => {
3315
- if (!!group && (!getGroupsById(getState())[group] || !getGroupsById(getState())[group].filters.length)) {
3316
- return Promise.resolve();
3317
- }
3318
- const { attributes, filterTerms: filters } = prepareSearchArguments({
3319
- filters: getState().devices.groups.byId[group].filters,
3320
- state: getState(),
3321
- status: import_constants4.DEVICE_STATES.accepted
3322
- });
3323
- const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage2, devices = []) => general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3324
- page,
3325
- per_page: perPage,
3326
- filters,
3327
- attributes: [...attributes, { scope: "inventory", attribute }]
3328
- }).then((res) => {
3329
- const state = getState();
3330
- const deviceAccu = reduceReceivedDevices(res.data, devices, state);
3331
- dispatch(actions3.receivedDevices(deviceAccu.devicesById));
3332
- const total = Number(res.headers[import_constants4.headerNames.total]);
3333
- if (total > deviceAccu.ids.length) {
3334
- return getAllDevices(perPage, page + 1, deviceAccu.ids);
3335
- }
3336
- return Promise.resolve(dispatch(actions3.addGroup({ group: { deviceIds: deviceAccu.ids, total }, groupName: group })));
3337
- });
3338
- return getAllDevices();
3339
- }
3340
- );
3341
- var getDeviceById2 = createAppAsyncThunk(
3342
- `${sliceName3}/getDeviceById`,
3343
- (id, { dispatch, getState }) => general_api_default.get(`${import_constants4.inventoryApiUrl}/devices/${id}`).then((res) => {
3344
- const device = reduceReceivedDevices([res.data], [], getState()).devicesById[id];
3345
- device.etag = res.headers.etag;
3346
- dispatch(actions3.receivedDevice(device));
3347
- return Promise.resolve(device);
3348
- }).catch((err) => {
3349
- const errMsg = extractErrorMessage(err);
3350
- if (errMsg.includes("Not Found")) {
3351
- console.log(`${id} does not have any inventory information`);
3352
- const device = reduceReceivedDevices(
3353
- [
3354
- {
3355
- id,
3356
- attributes: [
3357
- { name: "status", value: "decomissioned", scope: "identity" },
3358
- { name: "decomissioned", value: "true", scope: "inventory" }
3359
- ],
3360
- log: false
3361
- }
3362
- ],
3363
- [],
3364
- getState()
3365
- ).devicesById[id];
3366
- dispatch(actions3.receivedDevice(device));
3367
- }
3368
- })
3369
- );
3370
- var getDeviceInfo = createAppAsyncThunk(`${sliceName3}/getDeviceInfo`, (deviceId, { dispatch, getState }) => {
3371
- const device = getDeviceById(getState(), deviceId);
3372
- const { hasDeviceConfig, hasDeviceConnect, hasMonitor } = getTenantCapabilities(getState());
3373
- const { canConfigure } = getUserCapabilities(getState());
3374
- const integrations = getDeviceTwinIntegrations(getState());
3375
- const tasks = [
3376
- dispatch(getDeviceAuth(deviceId)),
3377
- dispatch(getDeviceById2(deviceId)),
3378
- ...integrations.map((integration) => dispatch(getDeviceTwin({ deviceId, integration })))
3379
- ];
3380
- if (hasDeviceConfig && canConfigure && (device.status === import_constants4.DEVICE_STATES.accepted || device.status === import_constants4.DEVICE_STATES.preauth)) {
3381
- tasks.push(dispatch(getDeviceConfig(deviceId)));
3382
- }
3383
- if (device.status === import_constants4.DEVICE_STATES.accepted) {
3384
- if (hasDeviceConnect) {
3385
- tasks.push(dispatch(getDeviceConnect(deviceId)));
3386
- }
3387
- if (hasMonitor) {
3388
- tasks.push(dispatch(getLatestDeviceAlerts({ id: deviceId })));
3389
- tasks.push(dispatch(getDeviceMonitorConfig(deviceId)));
3390
- }
3391
- }
3392
- return Promise.all(tasks);
3393
- });
3394
- var getAllDeviceCounts = createAppAsyncThunk(
3395
- `${sliceName3}/getAllDeviceCounts`,
3396
- (_, { dispatch }) => general_api_default.get(`${import_constants4.inventoryApiUrlV2}/statistics`).then(({ data }) => {
3397
- const { devices_by_status } = data;
3398
- Object.entries(devices_by_status).map(([status, countsPerTier]) => dispatch(actions3.setDevicesCountByStatus({ countsPerTier, status })));
3399
- return;
3400
- })
3401
- );
3402
- var getDeviceLimits2 = createAppAsyncThunk(
3403
- `${sliceName3}/getDeviceLimit`,
3404
- (_, { dispatch }) => general_api_default.get(`${import_constants4.deviceAuthV2}/limits/devices`).then((res) => dispatch(actions3.setDeviceLimits(res.data)))
3405
- );
3406
- var setDeviceListState = createAppAsyncThunk(
3407
- `${sliceName3}/setDeviceListState`,
3408
- ({ shouldSelectDevices = true, forceRefresh, fetchAuth = true, ...selectionState }, { dispatch, getState }) => {
3409
- const currentState = getDeviceListState(getState());
3410
- const refreshTrigger = forceRefresh ? !currentState.refreshTrigger : selectionState.refreshTrigger;
3411
- const nextState = {
3412
- ...currentState,
3413
- setOnly: false,
3414
- refreshTrigger,
3415
- ...selectionState,
3416
- sort: { ...currentState.sort, ...selectionState.sort }
3417
- };
3418
- const tasks = [];
3419
- const { isLoading: currentLoading, deviceIds: currentDevices, selection: currentSelection, ...currentRequestState } = currentState;
3420
- const { isLoading: nextLoading, deviceIds: nextDevices, selection: nextSelection, ...nextRequestState } = nextState;
3421
- if (!nextState.setOnly && !(0, import_helpers9.deepCompare)(currentRequestState, nextRequestState)) {
3422
- const { direction: sortDown = import_constants4.SORTING_OPTIONS.desc, key: sortCol, scope: sortScope = "" } = nextState.sort ?? {};
3423
- const sortBy = sortCol ? [{ attribute: sortCol, order: sortDown, scope: sortScope }] : void 0;
3424
- const applicableSelectedState = nextState.state === import_constants4.ALL_DEVICE_STATES ? void 0 : nextState.state;
3425
- nextState.isLoading = true;
3426
- tasks.push(
3427
- dispatch(getDevicesByStatus2({ ...nextState, status: applicableSelectedState, sortOptions: sortBy, fetchAuth })).unwrap().then((results) => {
3428
- const { deviceAccu, total } = results[results.length - 1];
3429
- const devicesState = shouldSelectDevices ? { deviceIds: deviceAccu.ids, total, isLoading: false } : { isLoading: false };
3430
- return Promise.resolve(dispatch(actions3.setDeviceListState(devicesState)));
3431
- }).catch(() => Promise.resolve({ isLoading: false }))
3432
- );
3433
- }
3434
- if (currentState.page !== nextState.page || currentState.perPage > nextState.perPage || currentState.state !== nextState.state || !(0, import_helpers9.deepCompare)(currentState.sort, nextState.sort)) {
3435
- nextState.selection = [];
3436
- }
3437
- tasks.push(dispatch(actions3.setDeviceListState(nextState)));
3438
- return Promise.all(tasks);
3439
- }
3440
- );
3441
- var getDevicesByStatus2 = createAppAsyncThunk(
3442
- `${sliceName3}/getDevicesByStatus`,
3443
- (options, { dispatch, getState }) => {
3444
- const {
3445
- status,
3446
- fetchAuth = true,
3447
- filterSelection,
3448
- group,
3449
- selectedIssues = [],
3450
- page = defaultPage2,
3451
- perPage = defaultPerPage2,
3452
- sortOptions = [],
3453
- selectedAttributes = getSelectedDeviceAttribute(getState())
3454
- } = options;
3455
- const state = getState();
3456
- const { applicableFilters, filterTerms } = convertDeviceListStateToFilters({
3457
- filters: filterSelection ?? getDeviceFilters(state),
3458
- group: group ?? getSelectedGroup(state),
3459
- groups: state.devices.groups,
3460
- offlineThreshold: state.app.offlineThreshold,
3461
- selectedIssues,
3462
- status
3463
- });
3464
- const attributes = [...defaultAttributes, getIdAttribute(getState()), ...selectedAttributes];
3465
- return general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3466
- page,
3467
- per_page: perPage,
3468
- filters: filterTerms,
3469
- sort: sortOptions,
3470
- attributes
3471
- }).then((response) => {
3472
- const state2 = getState();
3473
- const deviceAccu = reduceReceivedDevices(response.data, [], state2, status);
3474
- let total = !applicableFilters.length ? Number(response.headers[import_constants4.headerNames.total]) : 0;
3475
- if (status && state2.devices.byStatus[status].counts.total === deviceAccu.ids.length) {
3476
- total = deviceAccu.ids.length;
3477
- }
3478
- const tasks = [dispatch(actions3.receivedDevices(deviceAccu.devicesById))];
3479
- if (status) {
3480
- tasks.push(dispatch(actions3.setDevicesByStatus({ deviceIds: deviceAccu.ids, status, total })));
3481
- }
3482
- const receivedDevices = Object.values(deviceAccu.devicesById);
3483
- if (receivedDevices.length && fetchAuth) {
3484
- tasks.push(dispatch(getDevicesWithAuth(receivedDevices)));
3485
- }
3486
- tasks.push(Promise.resolve({ deviceAccu, total: Number(response.headers[import_constants4.headerNames.total]) }));
3487
- return Promise.all(tasks);
3488
- }).catch((err) => commonErrorHandler(err, `${status} devices couldn't be loaded.`, dispatch, commonErrorFallback));
3489
- }
3490
- );
3491
- var getAllDevicesByStatus = createAppAsyncThunk(
3492
- `${sliceName3}/getAllDevicesByStatus`,
3493
- ({ status, attribute }, { dispatch, getState }) => {
3494
- const attributes = [...defaultAttributes, getIdAttribute(getState())];
3495
- const getAllDevices = (perPage = MAX_PAGE_SIZE, page = 1, devices = []) => general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3496
- page,
3497
- per_page: perPage,
3498
- filters: mapFiltersToTerms([{ key: "status", value: status, operator: import_constants4.DEVICE_FILTERING_OPTIONS.$eq.key, scope: "identity" }]),
3499
- attributes: [...attributes, { scope: "inventory", attribute }]
3500
- }).then((res) => {
3501
- const state = getState();
3502
- const deviceAccu = reduceReceivedDevices(res.data, devices, state, status);
3503
- dispatch(actions3.receivedDevices(deviceAccu.devicesById));
3504
- const total = Number(res.headers[import_constants4.headerNames.total]);
3505
- if (total > state.deployments.deploymentDeviceLimit) {
3506
- return Promise.resolve();
3507
- }
3508
- if (total > perPage * page) {
3509
- return getAllDevices(perPage, page + 1, deviceAccu.ids);
3510
- }
3511
- return Promise.resolve();
3512
- });
3513
- return getAllDevices();
3514
- }
3515
- );
3516
- var searchDevices = createAppAsyncThunk(`${sliceName3}/searchDevices`, (passedOptions = {}, { dispatch, getState }) => {
3517
- const state = getState();
3518
- const options = { ...state.app.searchState, ...passedOptions };
3519
- const { page = defaultPage2, searchTerm, sortOptions = [] } = options;
3520
- const { columnSelection = [] } = getUserSettings(state);
3521
- const selectedAttributes = columnSelection.map((column) => ({ attribute: column.key, scope: column.scope }));
3522
- const attributes = (0, import_helpers9.attributeDuplicateFilter)([...defaultAttributes, getIdAttribute(state), ...selectedAttributes], "attribute");
3523
- return general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3524
- page,
3525
- per_page: 10,
3526
- filters: [],
3527
- sort: sortOptions,
3528
- text: searchTerm,
3529
- attributes
3530
- }).then((response) => {
3531
- const deviceAccu = reduceReceivedDevices(response.data, [], getState());
3532
- return Promise.all([
3533
- dispatch(actions3.receivedDevices(deviceAccu.devicesById)),
3534
- Promise.resolve({ deviceIds: deviceAccu.ids, searchTotal: Number(response.headers[import_constants4.headerNames.total]) })
3535
- ]);
3536
- }).catch((err) => commonErrorHandler(err, `devices couldn't be searched.`, dispatch, commonErrorFallback));
3537
- });
3538
- var ATTRIBUTE_LIST_CUTOFF = 100;
3539
- var attributeReducer = (attributes = []) => attributes.slice(0, ATTRIBUTE_LIST_CUTOFF).reduce(
3540
- (accu, { name, scope }) => {
3541
- if (!accu[scope]) {
3542
- accu[scope] = [];
3543
- }
3544
- accu[scope].push(name);
3545
- return accu;
3546
- },
3547
- { identity: [], inventory: [], system: [], tags: [] }
3548
- );
3549
- var getDeviceAttributes = createAppAsyncThunk(
3550
- `${sliceName3}/getDeviceAttributes`,
3551
- (_, { dispatch }) => general_api_default.get(`${import_constants4.inventoryApiUrlV2}/filters/attributes`).then(({ data }) => {
3552
- const { identity: identityAttributes, inventory: inventoryAttributes, system: systemAttributes, tags: tagAttributes } = attributeReducer(data || []);
3553
- return dispatch(actions3.setFilterAttributes({ identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }));
3554
- })
3555
- );
3556
- var initializeDistributionData = (report, groups, devices, totalDeviceCount) => {
3557
- const { attribute, group = "", software = "" } = report;
3558
- const effectiveAttribute = software ? software : attribute;
3559
- const { deviceIds, total = 0 } = groups[group] || {};
3560
- const relevantDevices = deviceIds ? deviceIds.map((id) => devices[id]) : Object.values(devices);
3561
- const distributionByAttribute = relevantDevices.reduce((accu, item) => {
3562
- if (!item.attributes || item.status !== import_constants4.DEVICE_STATES.accepted) return accu;
3563
- const attributeValue = item.attributes[effectiveAttribute];
3564
- if (!accu[attributeValue]) {
3565
- accu[attributeValue] = 0;
3566
- }
3567
- accu[attributeValue] = accu[attributeValue] + 1;
3568
- return accu;
3569
- }, {});
3570
- const distributionByAttributeSorted = Object.entries(distributionByAttribute).sort((pairA, pairB) => pairB[1] - pairA[1]);
3571
- const items = distributionByAttributeSorted.map(([key, count]) => ({ key, count }));
3572
- const dataCount = items.reduce((accu, item) => accu + item.count, 0);
3573
- const otherCount = (groups[group] ? total : totalDeviceCount) - dataCount;
3574
- return { items, otherCount, total: otherCount + dataCount };
3575
- };
3576
- var updateReportData = createAppAsyncThunk(`${sliceName3}/updateReportData`, (reportIndex, { dispatch, getState }) => {
3577
- const reports = getDeviceReportsForUser(getState());
3578
- const report = reports[reportIndex];
3579
- const { group = "" } = report;
3580
- const devicesById = getDevicesById(getState());
3581
- const groups = getGroupsById(getState());
3582
- const { accepted: acceptedDevicesCount } = getDeviceCountsByStatus(getState());
3583
- const totalDeviceCount = groups[group] ? groups[group].total : acceptedDevicesCount;
3584
- const reportsData = getDeviceReports(getState());
3585
- const newReports = [...reportsData];
3586
- newReports[reportIndex] = initializeDistributionData(report, groups, devicesById, totalDeviceCount);
3587
- return Promise.resolve(dispatch(actions3.setDeviceReports(newReports)));
3588
- });
3589
- var getReportDataWithoutBackendSupport = createAppAsyncThunk(
3590
- `${sliceName3}/getReportDataWithoutBackendSupport`,
3591
- (reportIndex, { dispatch, getState }) => {
3592
- const reports = getDeviceReportsForUser(getState());
3593
- const report = reports[reportIndex];
3594
- if (!report) {
3595
- return;
3596
- }
3597
- const { attribute, group = "", software = "" } = report;
3598
- const effectiveAttribute = software ? software : attribute;
3599
- const devicesById = getDevicesById(getState());
3600
- const acceptedDevices = getAcceptedDevices(getState());
3601
- const { accepted: acceptedDevicesCount } = getDeviceCountsByStatus(getState());
3602
- const groups = getGroupsById(getState());
3603
- const { deviceIds = [], filters = [], total = 0 } = groups[group] || {};
3604
- let groupDevicesRequest = Promise.resolve({
3605
- payload: { groupName: "", group: { deviceIds: Object.keys(devicesById), total: Object.keys(devicesById).length } }
3606
- });
3607
- if (group && (!(deviceIds.length && total) || deviceIds.length !== total || !deviceIds.every((id) => !!devicesById[id]))) {
3608
- groupDevicesRequest = filters.length ? dispatch(getAllDynamicGroupDevices({ group, attribute: effectiveAttribute })).unwrap() : dispatch(getAllGroupDevices({ group, attribute: effectiveAttribute })).unwrap();
3609
- } else if (!group && (acceptedDevices.deviceIds.length !== acceptedDevicesCount || !acceptedDevices.deviceIds.every((id) => !!devicesById[id]))) {
3610
- groupDevicesRequest = dispatch(getAllDevicesByStatus({ status: import_constants4.DEVICE_STATES.accepted, attribute: effectiveAttribute })).unwrap();
3611
- }
3612
- return groupDevicesRequest.then(() => dispatch(updateReportData(reportIndex)));
3613
- }
3614
- );
3615
- var getDeviceConnect = createAppAsyncThunk(
3616
- `${sliceName3}/getDeviceConnect`,
3617
- (id, { dispatch }) => general_api_default.get(`${import_constants4.deviceConnect}/devices/${id}`).then(
3618
- ({ data }) => Promise.all([dispatch(actions3.receivedDevice({ connect_status: data.status, connect_updated_ts: data.updated_ts, id })), Promise.resolve(data)])
3619
- )
3620
- );
3621
- var updateTypeMap = { deploymentUpdate: "check-update", inventoryUpdate: "send-inventory" };
3622
- var triggerDeviceUpdate = createAppAsyncThunk(
3623
- `${sliceName3}/triggerDeviceUpdate`,
3624
- ({ id, type }, { dispatch }) => general_api_default.post(`${import_constants4.deviceConnect}/devices/${id}/${updateTypeMap[type] ?? updateTypeMap.deploymentUpdate}`).catch((err) => commonErrorHandler(err, `The request couldn\u2019t be sent.`, dispatch)).then(() => {
3625
- dispatch(setSnackbar3("Request has been sent."));
3626
- return new Promise((resolve) => setTimeout(() => resolve(dispatch(getDeviceById2(id))), TIMEOUTS.threeSeconds));
3627
- })
3628
- );
3629
- var getSessionDetails = createAppAsyncThunk(
3630
- `${sliceName3}/getSessionDetails`,
3631
- ({ sessionId, deviceId, userId, startDate, endDate }) => {
3632
- const { start: startUnix, end: endUnix } = (0, import_helpers9.dateRangeToUnix)(startDate, endDate);
3633
- const createdAfter = startDate ? `&created_after=${startUnix}` : "";
3634
- const createdBefore = endDate ? `&created_before=${endUnix}` : "";
3635
- const objectSearch = `&object_id=${deviceId}`;
3636
- return general_api_default.get(`${import_constants4.auditLogsApiUrl}/logs?per_page=500${createdAfter}${createdBefore}&actor_id=${userId}${objectSearch}`).then(
3637
- ({ data: auditLogEntries }) => {
3638
- const { start, end } = auditLogEntries.reduce(
3639
- (accu, item) => {
3640
- if (item.meta?.session_id?.includes(sessionId)) {
3641
- accu.start = new Date(item.action.startsWith("open") ? item.time : accu.start);
3642
- accu.end = new Date(item.action.startsWith("close") ? item.time : accu.end);
3643
- }
3644
- return accu;
3645
- },
3646
- { start: startDate || endDate, end: endDate || startDate }
3647
- );
3648
- return Promise.resolve({ start, end });
3649
- }
3650
- );
3651
- }
3652
- );
3653
- var getDeviceFileDownloadLink = createAppAsyncThunk(
3654
- `${sliceName3}/getDeviceFileDownloadLink`,
3655
- ({ deviceId, path }) => Promise.resolve(`${window.location.origin}${import_constants4.deviceConnect}/devices/${deviceId}/download?path=${encodeURIComponent(path)}`)
3656
- );
3657
- var deviceFileUpload = createAppAsyncThunk(
3658
- `${sliceName3}/deviceFileUpload`,
3659
- ({ deviceId, path, file }, { dispatch }) => {
3660
- const formData = new FormData();
3661
- formData.append("path", path);
3662
- formData.append("file", file);
3663
- const uploadId = (0, import_uuid.v4)();
3664
- const cancelSource = new AbortController();
3665
- return Promise.all([
3666
- dispatch(setSnackbar3("Uploading file")),
3667
- dispatch(initUpload({ id: uploadId, upload: { progress: 0, cancelSource } })),
3668
- general_api_default.uploadPut(
3669
- `${import_constants4.deviceConnect}/devices/${deviceId}/upload`,
3670
- formData,
3671
- (e) => dispatch(uploadProgress2({ id: uploadId, progress: progress(e) })),
3672
- cancelSource.signal
3673
- )
3674
- ]).then(() => Promise.resolve(dispatch(setSnackbar3({ message: "Upload successful", autoHideDuration: TIMEOUTS.fiveSeconds })))).catch((err) => {
3675
- if ((0, import_axios2.isCancel)(err)) {
3676
- return dispatch(setSnackbar3({ message: "The upload has been cancelled", autoHideDuration: TIMEOUTS.fiveSeconds }));
3677
- }
3678
- return commonErrorHandler(err, `Error uploading file to device.`, dispatch);
3679
- }).finally(() => dispatch(cleanUpUpload(uploadId)));
3680
- }
3681
- );
3682
- var getDeviceAuth = createAppAsyncThunk(
3683
- `${sliceName3}/getDeviceAuth`,
3684
- (id, { dispatch }) => dispatch(getDevicesWithAuth([{ id }])).unwrap().then((results) => {
3685
- if (results[results.length - 1]) {
3686
- return Promise.resolve(results[results.length - 1][0]);
3687
- }
3688
- return Promise.resolve();
3689
- })
3690
- );
3691
- var getDevicesWithAuth = createAppAsyncThunk(
3692
- `${sliceName3}/getDevicesWithAuth`,
3693
- (devices, { dispatch, getState }) => devices.length ? general_api_default.get(`${import_constants4.deviceAuthV2}/devices?id=${devices.map((device) => device.id).join("&id=")}`).then(({ data: receivedDevices }) => {
3694
- const { devicesById } = reduceReceivedDevices(receivedDevices, [], getState());
3695
- return Promise.all([dispatch(actions3.receivedDevices(devicesById)), Promise.resolve(receivedDevices)]);
3696
- }).catch((err) => commonErrorHandler(err, `Error: ${err}`, dispatch)) : Promise.resolve([[], []])
3697
- );
3698
- var updateDeviceAuth = createAppAsyncThunk(
3699
- `${sliceName3}/updateDeviceAuth`,
3700
- ({ deviceId, authId, status }, { dispatch, getState }) => general_api_default.put(`${import_constants4.deviceAuthV2}/devices/${deviceId}/auth/${authId}/status`, { status }).then(() => Promise.all([dispatch(getDeviceAuth(deviceId)), dispatch(setSnackbar3("Device authorization status was updated successfully"))])).catch((err) => commonErrorHandler(err, "There was a problem updating the device authorization status:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getDeviceListState(getState()).refreshTrigger })))
3701
- );
3702
- var updateDevicesAuth = createAppAsyncThunk(
3703
- `${sliceName3}/updateDevicesAuth`,
3704
- ({ deviceIds, status }, { dispatch, getState }) => {
3705
- let devices = getDevicesById(getState());
3706
- const deviceIdsWithoutAuth = deviceIds.reduce((accu, id) => devices[id].auth_sets ? accu : [...accu, { id }], []);
3707
- return dispatch(getDevicesWithAuth(deviceIdsWithoutAuth)).then(() => {
3708
- devices = getDevicesById(getState());
3709
- const deviceAuthUpdates = deviceIds.map((id) => {
3710
- const device = devices[id];
3711
- if (device.auth_sets && device.auth_sets.length !== 1) {
3712
- return Promise.reject();
3713
- }
3714
- return dispatch(updateDeviceAuth({ authId: device.auth_sets[0].id, deviceId: device.id, status })).unwrap().catch((err) => commonErrorHandler(err, "The action was stopped as there was a problem updating a device authorization status: ", dispatch, "", false));
3715
- });
3716
- return Promise.allSettled(deviceAuthUpdates).then((results) => {
3717
- const { skipped, count } = results.reduce(
3718
- (accu, item) => {
3719
- if (item.status === "rejected") {
3720
- accu.skipped = accu.skipped + 1;
3721
- } else {
3722
- accu.count = accu.count + 1;
3723
- }
3724
- return accu;
3725
- },
3726
- { skipped: 0, count: 0 }
3727
- );
3728
- const message = (0, import_helpers9.getSnackbarMessage)(skipped, count);
3729
- return dispatch(setSnackbar3(message));
3730
- });
3731
- });
3732
- }
3733
- );
3734
- var deleteAuthset = createAppAsyncThunk(
3735
- `${sliceName3}/deleteAuthset`,
3736
- ({ deviceId, authId }, { dispatch, getState }) => general_api_default.delete(`${import_constants4.deviceAuthV2}/devices/${deviceId}/auth/${authId}`).then(() => Promise.all([dispatch(setSnackbar3("Device authorization status was updated successfully"))])).catch((err) => commonErrorHandler(err, "There was a problem updating the device authorization status:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })))
3737
- );
3738
- var preauthDevice = createAppAsyncThunk(
3739
- `${sliceName3}/preauthDevice`,
3740
- (authset, { dispatch, rejectWithValue }) => general_api_default.post(`${import_constants4.deviceAuthV2}/devices`, authset).then(
3741
- () => Promise.resolve(dispatch(setSnackbar3({ message: "Device was successfully added to the preauthorization list", autoHideDuration: TIMEOUTS.fiveSeconds })))
3742
- ).catch((err) => {
3743
- if (err.response.status === 409) {
3744
- return rejectWithValue("A device with a matching identity data set already exists");
3745
- }
3746
- return commonErrorHandler(err, "The device could not be added:", dispatch);
3747
- })
3748
- );
3749
- var decommissionDevice = createAppAsyncThunk(
3750
- `${sliceName3}/decommissionDevice`,
3751
- ({ deviceId, authId }, { dispatch, getState }) => general_api_default.delete(`${import_constants4.deviceAuthV2}/devices/${deviceId}`).then(() => Promise.resolve(dispatch(setSnackbar3("Device was decommissioned successfully")))).catch((err) => commonErrorHandler(err, "There was a problem decommissioning the device:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })))
3752
- );
3753
- var getDeviceConfig = createAppAsyncThunk(
3754
- `${sliceName3}/getDeviceConfig`,
3755
- (deviceId, { dispatch }) => general_api_default.get(`${import_constants4.deviceConfig}/${deviceId}`).then(({ data }) => Promise.all([dispatch(actions3.receivedDevice({ id: deviceId, config: data })), Promise.resolve(data)])).catch((err) => {
3756
- if (err.response?.data?.error.status_code !== 404) {
3757
- return commonErrorHandler(err, `There was an error retrieving the configuration for device ${deviceId}.`, dispatch, commonErrorFallback);
3758
- }
3759
- })
3760
- );
3761
- var setDeviceConfig = createAppAsyncThunk(
3762
- `${sliceName3}/setDeviceConfig`,
3763
- ({ deviceId, config }, { dispatch }) => general_api_default.put(`${import_constants4.deviceConfig}/${deviceId}`, config).catch((err) => commonErrorHandler(err, `There was an error setting the configuration for device ${deviceId}.`, dispatch, commonErrorFallback)).then(() => Promise.resolve(dispatch(getDeviceConfig(deviceId))))
3764
- );
3765
- var applyDeviceConfig = createAppAsyncThunk(
3766
- `${sliceName3}/applyDeviceConfig`,
3767
- ({ deviceId, configDeploymentConfiguration, isDefault, config }, { dispatch, getState }) => general_api_default.post(`${import_constants4.deviceConfig}/${deviceId}/deploy`, configDeploymentConfiguration).catch((err) => commonErrorHandler(err, `There was an error deploying the configuration to device ${deviceId}.`, dispatch, commonErrorFallback)).then(({ data }) => {
3768
- const device = getDeviceById(getState(), deviceId);
3769
- const { canManageUsers } = getUserCapabilities(getState());
3770
- const tasks = [
3771
- dispatch(actions3.receivedDevice({ ...device, config: { ...device.config, deployment_id: data.deployment_id } })),
3772
- new Promise((resolve) => setTimeout(() => resolve(dispatch(getSingleDeployment(data.deployment_id))), TIMEOUTS.oneSecond))
3773
- ];
3774
- if (isDefault && canManageUsers) {
3775
- const { previous } = getGlobalSettings(getState()).defaultDeviceConfig ?? {};
3776
- tasks.push(dispatch(saveGlobalSettings({ defaultDeviceConfig: { current: config, previous } })));
3777
- }
3778
- return Promise.all(tasks);
3779
- })
3780
- );
3781
- var setDeviceTags = createAppAsyncThunk(
3782
- `${sliceName3}/setDeviceTags`,
3783
- ({ deviceId, tags }, { dispatch }) => (
3784
- // to prevent tag set failures, retrieve the device & use the freshest etag we can get
3785
- dispatch(getDeviceById2(deviceId)).unwrap().then((device) => {
3786
- const headers = device.etag ? { "If-Match": device.etag } : {};
3787
- const tagList = Object.entries(tags).map(([name, value]) => ({ name, value }));
3788
- const isNameChange = tagList.some(({ name }) => name === "name");
3789
- return general_api_default.put(`${import_constants4.inventoryApiUrl}/devices/${deviceId}/tags`, tagList, { headers }).catch((err) => commonErrorHandler(err, `There was an error setting tags for device ${deviceId}.`, dispatch, "Please check your connection.")).then(
3790
- () => Promise.all([
3791
- dispatch(actions3.receivedDevice({ ...device, id: deviceId, tags })),
3792
- dispatch(setSnackbar3(`Device ${tagList.length === 1 && isNameChange ? "name" : "tags"} changed`))
3793
- ])
3794
- );
3795
- })
3796
- )
3797
- );
3798
- var getDeviceTwin = createAppAsyncThunk(`${sliceName3}/getDeviceTwin`, ({ deviceId, integration }, { dispatch, getState }) => {
3799
- let providerResult = {};
3800
- return general_api_default.get(`${import_constants4.iotManagerBaseURL}/devices/${deviceId}/state`).then(({ data }) => {
3801
- providerResult = { ...data, twinError: "" };
3802
- }).catch((err) => {
3803
- providerResult = {
3804
- twinError: `There was an error getting the ${EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}. ${err}`
3805
- };
3806
- }).finally(() => {
3807
- const device = getDeviceById(getState(), deviceId);
3808
- Promise.resolve(dispatch(actions3.receivedDevice({ ...device, twinsByIntegration: { ...device.twinsByIntegration, ...providerResult } })));
3809
- });
3810
- });
3811
- var setDeviceTwin = createAppAsyncThunk(
3812
- `${sliceName3}/setDeviceTwin`,
3813
- ({ deviceId, integration, settings }, { dispatch, getState }) => general_api_default.put(`${import_constants4.iotManagerBaseURL}/devices/${deviceId}/state/${integration.id}`, { desired: settings }).catch(
3814
- (err) => commonErrorHandler(
3815
- err,
3816
- `There was an error updating the ${EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}.`,
3817
- dispatch
3818
- )
3819
- ).then(() => {
3820
- const device = getDeviceById(getState(), deviceId);
3821
- const { twinsByIntegration = {} } = device;
3822
- const { [integration.id]: currentState = {} } = twinsByIntegration;
3823
- return Promise.resolve(
3824
- dispatch(
3825
- actions3.receivedDevice({ ...device, twinsByIntegration: { ...twinsByIntegration, [integration.id]: { ...currentState, desired: settings } } })
3826
- )
3827
- );
3828
- })
3829
- );
3830
- var prepareSearchArguments = ({ filters, group, state, status }) => {
3831
- const { filterTerms } = convertDeviceListStateToFilters({ filters, group, offlineThreshold: state.app.offlineThreshold, selectedIssues: [], status });
3832
- const { columnSelection = [] } = getUserSettings(state);
3833
- const selectedAttributes = columnSelection.map((column) => ({ attribute: column.key, scope: column.scope }));
3834
- const attributes = [...defaultAttributes, getIdAttribute(state), ...selectedAttributes];
3835
- return { attributes, filterTerms };
3836
- };
3837
- var getSystemDevices = createAppAsyncThunk(`${sliceName3}/getSystemDevices`, (options, { dispatch, getState }) => {
3838
- const { id, page = defaultPage2, perPage = defaultPerPage2, sortOptions = [] } = options;
3839
- const state = getState();
3840
- const { hasFullFiltering } = getTenantCapabilities(state);
3841
- if (!hasFullFiltering) {
3842
- return Promise.resolve();
3843
- }
3844
- const { attributes: deviceAttributes = {} } = getDeviceById(state, id);
3845
- const { mender_gateway_system_id = "" } = deviceAttributes;
3846
- const filters = [
3847
- { ...emptyFilter, key: "mender_is_gateway", operator: import_constants4.DEVICE_FILTERING_OPTIONS.$ne.key, value: "true", scope: "inventory" },
3848
- { ...emptyFilter, key: "mender_gateway_system_id", value: mender_gateway_system_id, scope: "inventory" }
3849
- ];
3850
- const { attributes, filterTerms } = prepareSearchArguments({ filters, state });
3851
- return general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3852
- page,
3853
- per_page: perPage,
3854
- filters: filterTerms,
3855
- sort: sortOptions,
3856
- attributes
3857
- }).catch((err) => commonErrorHandler(err, `There was an error getting system devices device ${id}.`, dispatch, "Please check your connection.")).then(({ data, headers }) => {
3858
- const state2 = getState();
3859
- const { devicesById, ids } = reduceReceivedDevices(data, [], state2);
3860
- const device = {
3861
- ...getDeviceById(state2, id),
3862
- systemDeviceIds: ids,
3863
- systemDeviceTotal: Number(headers[import_constants4.headerNames.total])
3864
- };
3865
- return Promise.resolve(dispatch(actions3.receivedDevices({ ...devicesById, [id]: device })));
3866
- });
3867
- });
3868
- var getGatewayDevices = createAppAsyncThunk(`${sliceName3}/getGatewayDevices`, (deviceId, { dispatch, getState }) => {
3869
- const state = getState();
3870
- const { attributes = {} } = getDeviceById(state, deviceId);
3871
- const { mender_gateway_system_id = "" } = attributes;
3872
- const filters = [
3873
- { ...emptyFilter, key: "id", operator: import_constants4.DEVICE_FILTERING_OPTIONS.$ne.key, value: deviceId, scope: "identity" },
3874
- { ...emptyFilter, key: "mender_is_gateway", value: "true", scope: "inventory" },
3875
- { ...emptyFilter, key: "mender_gateway_system_id", value: mender_gateway_system_id, scope: "inventory" }
3876
- ];
3877
- const { attributes: attributeSelection, filterTerms } = prepareSearchArguments({ filters, state });
3878
- return general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3879
- page: 1,
3880
- per_page: MAX_PAGE_SIZE,
3881
- filters: filterTerms,
3882
- attributes: attributeSelection
3883
- }).then(({ data }) => {
3884
- const { ids } = reduceReceivedDevices(data, [], getState());
3885
- const tasks = ids.map((deviceId2) => dispatch(getDeviceInfo(deviceId2)));
3886
- tasks.push(dispatch(actions3.receivedDevice({ id: deviceId, gatewayIds: ids })));
3887
- return Promise.all(tasks);
3888
- });
3889
- });
3890
-
3891
- // src/monitorSlice/thunks.ts
3892
- var { page: defaultPage3, perPage: defaultPerPage3 } = import_constants4.DEVICE_LIST_DEFAULTS;
3893
- var cutoffLength = 75;
3894
- var ellipsis = "...";
3895
- var longTextTrimmer = (text) => text.length >= cutoffLength + ellipsis.length ? `${text.substring(0, cutoffLength + ellipsis.length)}${ellipsis}` : text;
3896
- var sanitizeDeviceAlerts = (alerts) => alerts.map((alert) => ({ ...alert, fullName: alert.name, name: longTextTrimmer(alert.name || "") }));
3897
- var getDeviceAlerts = createAppAsyncThunk(`${sliceName4}/getDeviceAlerts`, ({ id, config = {} }, { dispatch }) => {
3898
- const { page = defaultPage3, perPage = defaultPerPage3, issuedBefore, issuedAfter, sortAscending = false } = config;
3899
- const issued_after = issuedAfter ? `&issued_after=${issuedAfter}` : "";
3900
- const issued_before = issuedBefore ? `&issued_before=${issuedBefore}` : "";
3901
- return general_api_default.get(
3902
- `${import_constants4.monitorApiUrlv1}/devices/${id}/alerts?page=${page}&per_page=${perPage}${issued_after}${issued_before}&sort_ascending=${sortAscending}`
3903
- ).catch((err) => commonErrorHandler(err, `Retrieving device alerts for device ${id} failed:`, dispatch)).then(
3904
- (res) => Promise.all([
3905
- dispatch(actions4.receiveDeviceAlerts({ deviceId: id, alerts: sanitizeDeviceAlerts(res.data) })),
3906
- dispatch(actions4.setAlertListState({ total: Number(res.headers[import_constants4.headerNames.total]) }))
3907
- ])
3908
- );
3909
- });
3910
- var getLatestDeviceAlerts = createAppAsyncThunk(
3911
- `${sliceName4}/getLatestDeviceAlerts`,
3912
- ({ id, config = {} }, { dispatch }) => {
3913
- const { page = defaultPage3, perPage = 10 } = config;
3914
- return general_api_default.get(`${import_constants4.monitorApiUrlv1}/devices/${id}/alerts/latest?page=${page}&per_page=${perPage}`).catch((err) => commonErrorHandler(err, `Retrieving device alerts for device ${id} failed:`, dispatch)).then((res) => Promise.resolve(dispatch(actions4.receiveLatestDeviceAlerts({ deviceId: id, alerts: sanitizeDeviceAlerts(res.data) }))));
3915
- }
3916
- );
3917
- var getIssueCountsByType2 = createAppAsyncThunk(
3918
- `${sliceName4}/getIssueCountsByType`,
3919
- ({ type, options = {} }, { dispatch, getState }) => {
3920
- const state = getState();
3921
- const { filters = getDeviceFilters(state), group, status, ...remainder } = options;
3922
- const { applicableFilters: nonMonitorFilters, filterTerms } = convertDeviceListStateToFilters({
3923
- ...remainder,
3924
- filters,
3925
- group,
3926
- offlineThreshold: state.app.offlineThreshold,
3927
- selectedIssues: [type],
3928
- status
3929
- });
3930
- return general_api_default.post(`${import_constants4.inventoryApiUrlV2}/filters/search`, {
3931
- page: 1,
3932
- per_page: 1,
3933
- filters: filterTerms,
3934
- attributes: [{ scope: "identity", attribute: "status" }]
3935
- }).catch((err) => commonErrorHandler(err, `Retrieving issue counts failed:`, dispatch, commonErrorFallback)).then((res) => {
3936
- const total = nonMonitorFilters.length ? state.monitor.issueCounts.byType[type].total : Number(res.headers[import_constants4.headerNames.total]);
3937
- const filtered = nonMonitorFilters.length ? Number(res.headers[import_constants4.headerNames.total]) : total;
3938
- if (total === state.monitor.issueCounts.byType[type].total && filtered === state.monitor.issueCounts.byType[type].filtered) {
3939
- return Promise.resolve();
3940
- }
3941
- return Promise.resolve(dispatch(actions4.receiveDeviceIssueCounts({ counts: { filtered, total }, issueType: type })));
3942
- });
3943
- }
3944
- );
3945
- var getDeviceMonitorConfig = createAppAsyncThunk(
3946
- `${sliceName4}/getDeviceMonitorConfig`,
3947
- (id, { dispatch }) => general_api_default.get(`${import_constants4.monitorApiUrlv1}/devices/${id}/config`).catch((err) => commonErrorHandler(err, `Retrieving device monitor config for device ${id} failed:`, dispatch)).then(({ data }) => Promise.all([dispatch(actions_default.receivedDevice({ id, monitors: data }), Promise.resolve(data))]))
3948
- );
3949
- var changeNotificationSetting = createAppAsyncThunk(
3950
- `${sliceName4}/changeNotificationSetting`,
3951
- ({ enabled, channel = import_constants4.alertChannels.email }, { dispatch }) => general_api_default.put(`${import_constants4.monitorApiUrlv1}/settings/global/channel/alerts/${channel}/status`, { enabled }).catch((err) => commonErrorHandler(err, `${enabled ? "En" : "Dis"}abling ${channel} alerts failed:`, dispatch)).then(
3952
- () => Promise.all([
3953
- dispatch(actions4.changeAlertChannel({ channel, enabled })),
3954
- dispatch(
3955
- actions_default.setSnackbar({ message: `Successfully ${enabled ? "en" : "dis"}abled ${channel} alerts`, autoHideDuration: TIMEOUTS.fiveSeconds })
3956
- )
3957
- ])
3958
- )
3959
- );
3960
-
3961
- // src/usersSlice/thunks.ts
3962
- var import_helpers10 = require("@northern.tech/utils/helpers");
3963
- var import_retrytimer = require("@northern.tech/utils/retrytimer");
3964
- var import_dayjs2 = __toESM(require("dayjs"), 1);
3965
- var import_md5 = __toESM(require("md5"), 1);
3966
- var import_universal_cookie4 = __toESM(require("universal-cookie"), 1);
3967
-
3968
- // src/api/users-api.ts
3969
- var import_axios3 = __toESM(require("axios"), 1);
3970
- var Api2 = {
3971
- postLogin: (url, { email: username, password, ...body }) => import_axios3.default.post(url, body, { ...commonRequestConfig, auth: { username, password } }).then((res) => ({ text: res.data, code: res.status, contentType: res.headers?.["content-type"] })),
3972
- putVerifyTFA: (url, userData) => {
3973
- let body = {};
3974
- if (userData.hasOwnProperty("token2fa")) {
3975
- body = { token2fa: userData.token2fa };
3976
- }
3977
- return import_axios3.default.put(url, body, { ...commonRequestConfig, headers: { ...commonRequestConfig.headers, Authorization: `Bearer ${getToken()}` } });
3978
- }
3979
- };
3980
- var users_api_default = Api2;
3981
-
3982
- // src/usersSlice/thunks.ts
3983
- var cookies4 = new import_universal_cookie4.default();
3984
- var { setAnnouncement, setSnackbar: setSnackbar4 } = actions_default;
3985
- var handleLoginError = (err, { token2fa: has2FA, password }, rejectWithValue) => () => {
3986
- const errorText = (0, import_helpers10.extractErrorMessage)(err);
3987
- const is2FABackend = errorText.includes("2fa");
3988
- if (is2FABackend && !has2FA) {
3989
- return rejectWithValue({ error: "2fa code missing" });
3990
- }
3991
- if (password === void 0) {
3992
- return Promise.reject();
3993
- }
3994
- const twoFAError = is2FABackend ? " and verification code" : "";
3995
- const errorMessage = `There was a problem logging in. Please check your email${twoFAError ? "," : " and"} password${twoFAError}. If you still have problems, contact an administrator.`;
3996
- return rejectWithValue({ error: errorMessage });
3997
- };
3998
- var loginUser = createAppAsyncThunk(
3999
- `${sliceName8}/loginUser`,
4000
- ({ stayLoggedIn, ...userData }, { dispatch, rejectWithValue }) => users_api_default.postLogin(`${import_constants4.useradmApiUrl}/auth/login`, { ...userData, no_expiry: stayLoggedIn }).catch((err) => {
4001
- cleanUp();
4002
- return Promise.reject(dispatch(handleLoginError(err, userData, rejectWithValue)));
4003
- }).then(({ text: token, contentType }) => {
4004
- if (contentType.includes(import_constants4.APPLICATION_JSON_CONTENT_TYPE)) {
4005
- const { id, kind } = token;
4006
- const type = kind.split("/")[1];
4007
- const ssoLoginUrl = SSO_TYPES[type].getStartUrl(id);
4008
- window.location.replace(ssoLoginUrl);
4009
- return;
4010
- }
4011
- if (contentType !== import_constants4.APPLICATION_JWT_CONTENT_TYPE || !token) {
4012
- return;
4013
- }
4014
- const now = /* @__PURE__ */ new Date();
4015
- now.setSeconds(now.getSeconds() + import_constants4.maxSessionAge);
4016
- const expiresAt = stayLoggedIn ? void 0 : now.toISOString();
4017
- setSessionInfo({ token, expiresAt });
4018
- cookies4.remove("JWT", { path: "/" });
4019
- return dispatch(getUser(OWN_USER_ID)).unwrap().catch((e) => {
4020
- cleanUp();
4021
- return Promise.reject(dispatch(setSnackbar4((0, import_helpers10.extractErrorMessage)(e))));
4022
- }).then(() => {
4023
- window.sessionStorage.removeItem("pendings-redirect");
4024
- if (window.location.pathname !== "/ui/") {
4025
- window.location.replace("/ui/");
4026
- }
4027
- return Promise.resolve(dispatch(actions8.successfullyLoggedIn({ expiresAt, token })));
4028
- });
4029
- })
4030
- );
4031
- var logoutUser = createAppAsyncThunk(`${sliceName8}/logoutUser`, (_, { dispatch, getState }) => {
4032
- if (Object.keys(getState().app.uploadsById).length) {
4033
- return Promise.reject();
4034
- }
4035
- return general_api_default.post(`${import_constants4.useradmApiUrl}/auth/logout`).finally(() => {
4036
- cleanUp();
4037
- (0, import_retrytimer.clearAllRetryTimers)(setSnackbar4);
4038
- return Promise.resolve(dispatch({ type: USER_LOGOUT }));
4039
- });
4040
- });
4041
- var switchUserOrganization = createAppAsyncThunk(`${sliceName8}/switchUserOrganization`, (tenantId, { getState }) => {
4042
- if (Object.keys(getState().app.uploadsById).length) {
4043
- return Promise.reject();
4044
- }
4045
- return general_api_default.get(`${import_constants4.useradmApiUrl}/users/tenants/${tenantId}/token`).then(({ data: token }) => {
4046
- window.sessionStorage.setItem("tenantChanged", "true");
4047
- setSessionInfo({ ...getSessionInfo(), token });
4048
- window.location.reload();
4049
- });
4050
- });
4051
- var passwordResetStart = createAppAsyncThunk(
4052
- `${sliceName8}/passwordResetStart`,
4053
- (email, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrl}/auth/password-reset/start`, { email }).catch(
4054
- (err) => commonErrorHandler(err, `The password reset request cannot be processed:`, dispatch, void 0, true)
4055
- )
4056
- );
4057
- var passwordResetComplete = createAppAsyncThunk(
4058
- `${sliceName8}/passwordResetComplete`,
4059
- ({ secretHash, newPassword }, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrl}/auth/password-reset/complete`, { secret_hash: secretHash, password: newPassword }).catch((err = {}) => {
4060
- const { error, response = {} } = err;
4061
- let errorMsg = "";
4062
- if (response.status == 400) {
4063
- errorMsg = "the link you are using expired or the request is not valid, please try again.";
4064
- } else {
4065
- errorMsg = error;
4066
- }
4067
- dispatch(setSnackbar4("The password reset request cannot be processed: " + errorMsg));
4068
- return Promise.reject(err);
4069
- })
4070
- );
4071
- var verifyEmailStart = createAppAsyncThunk(
4072
- `${sliceName8}/verifyEmailStart`,
4073
- (_, { dispatch, getState }) => general_api_default.post(`${import_constants4.useradmApiUrl}/auth/verify-email/start`, { email: getCurrentUser(getState()).email }).catch((err) => commonErrorHandler(err, "An error occured starting the email verification process:", dispatch)).finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
4074
- );
4075
- var verifyEmailComplete = createAppAsyncThunk(
4076
- `${sliceName8}/verifyEmailComplete`,
4077
- (secret_hash, { dispatch, rejectWithValue }) => general_api_default.post(`${import_constants4.useradmApiUrl}/auth/verify-email/complete`, { secret_hash }).catch((err) => rejectWithValue({ status: err.response?.status, data: err.response?.data })).finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
4078
- );
4079
- var verify2FA = createAppAsyncThunk(
4080
- `${sliceName8}/verify2FA`,
4081
- (tfaData, { dispatch }) => users_api_default.putVerifyTFA(`${import_constants4.useradmApiUrl}/2faverify`, tfaData).then(() => Promise.resolve(dispatch(getUser(OWN_USER_ID)))).catch(
4082
- (err) => commonErrorHandler(err, "An error occured validating the verification code: failed to verify token, please try again.", dispatch, void 0, true)
4083
- )
4084
- );
4085
- var getUserList = createAppAsyncThunk(
4086
- `${sliceName8}/getUserList`,
4087
- (_, { dispatch, getState }) => general_api_default.get(`${import_constants4.useradmApiUrl}/users`).then((res) => {
4088
- const currentUsersById = getUsersById(getState());
4089
- const users = res.data.reduce(
4090
- (accu, item) => {
4091
- accu[item.id] = {
4092
- ...accu[item.id],
4093
- ...item
4094
- };
4095
- return accu;
4096
- },
4097
- { ...currentUsersById }
4098
- );
4099
- return dispatch(actions8.receivedUserList(users));
4100
- }).catch((err) => commonErrorHandler(err, `Users couldn't be loaded.`, dispatch, commonErrorFallback))
4101
- );
4102
- var getUser = createAppAsyncThunk(
4103
- `${sliceName8}/getUser`,
4104
- (id, { dispatch, rejectWithValue }) => general_api_default.get(`${import_constants4.useradmApiUrl}/users/${id}`).then(
4105
- ({ data: user }) => Promise.all([
4106
- dispatch(actions8.receivedUser(user)),
4107
- dispatch(setHideAnnouncement({ shouldHide: false, userId: user.id })),
4108
- dispatch(updateUserColumnSettings({ currentUserId: user.id })),
4109
- user
4110
- ])
4111
- ).catch((e) => rejectWithValue(e))
4112
- );
4113
- var initializeSelf = createAppAsyncThunk(`${sliceName8}/initializeSelf`, (_, { dispatch }) => dispatch(getUser(OWN_USER_ID)));
4114
- var updateUserColumnSettings = createAppAsyncThunk(
4115
- `${sliceName8}/updateUserColumnSettings`,
4116
- ({ columns, currentUserId }, { dispatch, getState }) => {
4117
- const userId = currentUserId ?? getCurrentUser(getState()).id;
4118
- const storageKey = `${userId}-column-widths`;
4119
- let customColumns = [];
4120
- if (!columns) {
4121
- try {
4122
- customColumns = JSON.parse(window.localStorage.getItem(storageKey) || "") || customColumns;
4123
- } catch {
4124
- }
4125
- } else {
4126
- customColumns = columns;
4127
- }
4128
- window.localStorage.setItem(storageKey, JSON.stringify(customColumns));
4129
- return Promise.resolve(dispatch(actions8.setCustomColumns(customColumns)));
4130
- }
4131
- );
4132
- var userActions = {
4133
- add: {
4134
- successMessage: "The user was added successfully.",
4135
- errorMessage: "adding"
4136
- },
4137
- create: {
4138
- successMessage: "The user was created successfully.",
4139
- errorMessage: "creating"
4140
- },
4141
- edit: {
4142
- successMessage: "The user has been updated.",
4143
- errorMessage: "editing"
4144
- },
4145
- remove: {
4146
- successMessage: "The user was removed from the system.",
4147
- errorMessage: "removing"
4148
- }
4149
- };
4150
- var userActionErrorHandler = (err, type, dispatch) => commonErrorHandler(err, `There was an error ${userActions[type].errorMessage} the user.`, dispatch);
4151
- var createUser = createAppAsyncThunk(
4152
- `${sliceName8}/createUser`,
4153
- ({ shouldResetPassword, ...userData }, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrl}/users`, { ...userData, send_reset_password: shouldResetPassword }).then(() => Promise.all([dispatch(getUserList()), dispatch(setSnackbar4(userActions.create.successMessage))])).catch((err) => userActionErrorHandler(err, "create", dispatch))
4154
- );
4155
- var removeUser = createAppAsyncThunk(
4156
- `${sliceName8}/removeUser`,
4157
- (userId, { dispatch }) => general_api_default.delete(`${import_constants4.useradmApiUrl}/users/${userId}`).then(() => Promise.all([dispatch(actions8.removedUser(userId)), dispatch(getUserList()), dispatch(setSnackbar4(userActions.remove.successMessage))])).catch((err) => userActionErrorHandler(err, "remove", dispatch))
4158
- );
4159
- var editUser = createAppAsyncThunk(
4160
- `${sliceName8}/editUser`,
4161
- ({ id, ...userData }, { dispatch, getState }) => general_api_default.put(`${import_constants4.useradmApiUrl}/users/${id}`, userData).then(
4162
- () => Promise.all([
4163
- dispatch(actions8.updatedUser({ ...userData, id: id === OWN_USER_ID ? getCurrentUser(getState()).id : id })),
4164
- dispatch(setSnackbar4(userActions.edit.successMessage))
4165
- ])
4166
- ).catch((err) => userActionErrorHandler(err, "edit", dispatch))
4167
- );
4168
- var checkEmailExists = createAppAsyncThunk(`${sliceName8}/checkEmailExists`, async (email) => {
4169
- const response = await general_api_default.get(`${import_constants4.useradmApiUrl}/users/exists?email=${encodeURIComponent(email)}`);
4170
- return response.data.exists;
4171
- });
4172
- var addUserToCurrentTenant = createAppAsyncThunk(`${sliceName8}/addUserToTenant`, (userId, { dispatch, getState }) => {
4173
- const { id } = getOrganization(getState());
4174
- return general_api_default.post(`${import_constants4.useradmApiUrl}/users/${userId}/assign`, { tenant_ids: [id] }).catch((err) => commonErrorHandler(err, `There was an error adding the user to your organization:`, dispatch)).then(() => Promise.all([dispatch(setSnackbar4(userActions.add.successMessage)), dispatch(getUserList())]));
4175
- });
4176
- var enableUser2fa = createAppAsyncThunk(
4177
- `${sliceName8}/enableUser2fa`,
4178
- (userId = OWN_USER_ID, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrl}/users/${userId}/2fa/enable`).catch((err) => commonErrorHandler(err, `There was an error enabling Two Factor authentication for the user.`, dispatch)).then(() => Promise.resolve(dispatch(getUser(userId))))
4179
- );
4180
- var disableUser2fa = createAppAsyncThunk(
4181
- `${sliceName8}/disableUser2fa`,
4182
- (userId = OWN_USER_ID, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrl}/users/${userId}/2fa/disable`).catch((err) => commonErrorHandler(err, `There was an error disabling Two Factor authentication for the user.`, dispatch)).then(() => Promise.all([dispatch(getUser(userId)), dispatch(actions8.receivedQrCode(null))]))
4183
- );
4184
- var mapHttpPermission = (permission) => Object.entries(import_constants4.uiPermissionsByArea).reduce(
4185
- (accu, [area, definition]) => {
4186
- const endpointMatches = definition.endpoints.filter(
4187
- (endpoint) => endpoint.path.test(permission.value) && (endpoint.types.includes(permission.type) || permission.type === import_constants4.PermissionTypes.Any)
4188
- );
4189
- if (permission.value === import_constants4.PermissionTypes.Any || permission.value.includes(import_constants4.apiRoot) && endpointMatches.length) {
4190
- const endpointUiPermission = endpointMatches.reduce((endpointAccu, endpoint) => [...endpointAccu, ...endpoint.uiPermissions], []);
4191
- const collector = (endpointUiPermission || definition.uiPermissions).reduce((permissionsAccu, uiPermission) => {
4192
- if (permission.type === import_constants4.PermissionTypes.Any || !endpointMatches.length && uiPermission.verbs.some((verb) => verb === permission.type)) {
4193
- permissionsAccu.push(uiPermission.value);
4194
- }
4195
- return permissionsAccu;
4196
- }, []).filter(import_helpers10.duplicateFilter);
4197
- if (Array.isArray(accu[area])) {
4198
- accu[area] = [...accu[area], ...collector].filter(import_helpers10.duplicateFilter);
4199
- } else {
4200
- accu[area] = mergePermissions(accu[area], { [import_constants4.scopedPermissionAreas[area].excessiveAccessSelector]: collector });
4201
- }
4202
- }
4203
- return accu;
4204
- },
4205
- { ...import_constants4.emptyUiPermissions }
4206
- );
4207
- var permissionActionTypes = {
4208
- any: mapHttpPermission,
4209
- CREATE_DEPLOYMENT: (permission) => permission.type === import_constants4.PermissionTypes.DeviceGroup ? {
4210
- deployments: [import_constants4.uiPermissionsById.deploy.value],
4211
- groups: { [permission.value]: [import_constants4.uiPermissionsById.deploy.value] }
4212
- } : {},
4213
- http: mapHttpPermission,
4214
- REMOTE_TERMINAL: (permission) => permission.type === import_constants4.PermissionTypes.DeviceGroup ? {
4215
- groups: { [permission.value]: [import_constants4.uiPermissionsById.connect.value] }
4216
- } : {},
4217
- VIEW_DEVICE: (permission) => permission.type === import_constants4.PermissionTypes.DeviceGroup ? {
4218
- groups: { [permission.value]: [import_constants4.uiPermissionsById.read.value] }
4219
- } : {}
4220
- };
4221
- var combinePermissions = (existingPermissions, additionalPermissions = {}) => Object.entries(additionalPermissions).reduce((accu, [name, permissions]) => {
4222
- const maybeExistingPermissions = accu[name] || [];
4223
- accu[name] = [...permissions, ...maybeExistingPermissions].filter(import_helpers10.duplicateFilter);
4224
- return accu;
4225
- }, existingPermissions);
4226
- var tryParseCustomPermission = (permission) => {
4227
- const uiPermissions = permissionActionTypes[permission.action](permission.object);
4228
- const result = mergePermissions({ ...import_constants4.emptyUiPermissions }, uiPermissions);
4229
- return { isCustom: true, permission, result };
4230
- };
4231
- var customPermissionHandler = (accu, permission) => {
4232
- const processor = tryParseCustomPermission(permission);
4233
- return {
4234
- ...accu,
4235
- isCustom: accu.isCustom || processor.isCustom,
4236
- uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
4237
- };
4238
- };
4239
- var mapPermissionSet = (permissionSetName, names, scope, existingGroupsPermissions = {}) => {
4240
- const permission = Object.values(import_constants4.uiPermissionsById).find((permission2) => permission2.permissionSets[scope] === permissionSetName)?.value;
4241
- const scopedPermissions = names.reduce((accu, name) => combinePermissions(accu, { [name]: [permission] }), existingGroupsPermissions);
4242
- return Object.entries(scopedPermissions).reduce((accu, [key, permissions]) => ({ ...accu, [key]: deriveImpliedAreaPermissions(scope, permissions) }), {});
4243
- };
4244
- var isEmptyPermissionSet = (permissionSet) => !Object.values(permissionSet).reduce((accu, permissions) => {
4245
- if (Array.isArray(permissions)) {
4246
- return accu || !!permissions.length;
4247
- }
4248
- return accu || !(0, import_helpers10.isEmpty)(permissions);
4249
- }, false);
4250
- var parseRolePermissions = ({ permission_sets_with_scope = [], permissions = [] }, permissionSets) => {
4251
- const preliminaryResult = permission_sets_with_scope.reduce(
4252
- (accu, permissionSet) => {
4253
- if (!permissionSet.name) {
4254
- return accu;
4255
- }
4256
- const processor = permissionSets[permissionSet.name];
4257
- if (!processor) {
4258
- return accu;
4259
- }
4260
- const scope = Object.keys(import_constants4.scopedPermissionAreas).find((scope2) => import_constants4.uiPermissionsByArea[scope2].scope === permissionSet.scope?.type);
4261
- if (scope) {
4262
- const result = mapPermissionSet(
4263
- permissionSet.name,
4264
- permissionSet.scope?.value ?? [],
4265
- scope,
4266
- accu.uiPermissions[scope]
4267
- );
4268
- return { ...accu, uiPermissions: { ...accu.uiPermissions, [scope]: result } };
4269
- } else if (isEmptyPermissionSet(processor.result)) {
4270
- return processor.permissions?.reduce(customPermissionHandler, accu);
4271
- }
4272
- return {
4273
- ...accu,
4274
- isCustom: accu.isCustom || processor.isCustom,
4275
- uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
4276
- };
4277
- },
4278
- { isCustom: false, uiPermissions: { ...import_constants4.emptyUiPermissions, groups: {}, releases: {} } }
4279
- );
4280
- return permissions.reduce(customPermissionHandler, preliminaryResult);
4281
- };
4282
- var normalizeRbacRoles = (roles, rolesById2, permissionSets) => roles.reduce(
4283
- (accu, role) => {
4284
- let normalizedPermissions;
4285
- let isCustom = false;
4286
- if (rolesById2[role.name]) {
4287
- normalizedPermissions = {
4288
- ...rolesById2[role.name].uiPermissions,
4289
- groups: { ...rolesById2[role.name].uiPermissions.groups },
4290
- releases: { ...rolesById2[role.name].uiPermissions.releases }
4291
- };
4292
- } else {
4293
- const result = parseRolePermissions(role, permissionSets);
4294
- normalizedPermissions = result.uiPermissions;
4295
- isCustom = result.isCustom;
4296
- }
4297
- const roleState = accu[role.name] ?? { ...import_constants4.emptyRole };
4298
- accu[role.name] = {
4299
- ...roleState,
4300
- ...role,
4301
- description: roleState.description ? roleState.description : role.description,
4302
- editable: !import_constants4.rolesById[role.name] && !isCustom && (typeof roleState.editable !== "undefined" ? roleState.editable : true),
4303
- isCustom,
4304
- name: roleState.name ? roleState.name : role.name,
4305
- uiPermissions: normalizedPermissions
4306
- };
4307
- return accu;
4308
- },
4309
- { ...rolesById2 }
4310
- );
4311
- var getPermissionSets = createAppAsyncThunk(
4312
- `${sliceName8}/getPermissionSets`,
4313
- (_, { dispatch, getState }) => general_api_default.get(`${import_constants4.useradmApiUrlv2}/permission_sets?per_page=500`).then(({ data }) => {
4314
- const permissionSets = data.reduce(
4315
- (accu, permissionSet) => {
4316
- const permissionSetState = accu[permissionSet.name] ?? {};
4317
- let permissionSetObject = { ...permissionSetState, ...permissionSet };
4318
- permissionSetObject.result = Object.values(import_constants4.uiPermissionsById).reduce(
4319
- (accu2, item) => Object.entries(item.permissionSets).reduce((collector, [area, permissionSet2]) => {
4320
- if (import_constants4.scopedPermissionAreas[area]) {
4321
- return collector;
4322
- }
4323
- if (permissionSet2 === permissionSetObject.name) {
4324
- collector[area] = [...collector[area], item.value].filter(import_helpers10.duplicateFilter);
4325
- }
4326
- return collector;
4327
- }, accu2),
4328
- { ...import_constants4.emptyUiPermissions, ...permissionSetObject.result ?? {} }
4329
- );
4330
- const scopes = Object.values(import_constants4.scopedPermissionAreas).reduce((accu2, { key, scopeType }) => {
4331
- if (permissionSetObject.supported_scope_types?.includes(key) || permissionSetObject.supported_scope_types?.includes(scopeType)) {
4332
- accu2.push(key);
4333
- }
4334
- return accu2;
4335
- }, []);
4336
- permissionSetObject = scopes.reduce((accu2, scope) => {
4337
- accu2.result = {
4338
- ...accu2.result,
4339
- [scope]: mapPermissionSet(permissionSetObject.name, [import_constants4.scopedPermissionAreas[scope].excessiveAccessSelector], scope)
4340
- };
4341
- return accu2;
4342
- }, permissionSetObject);
4343
- accu[permissionSet.name] = permissionSetObject;
4344
- return accu;
4345
- },
4346
- { ...getState().users.permissionSetsById }
4347
- );
4348
- return Promise.all([dispatch(actions8.receivedPermissionSets(permissionSets)), permissionSets]);
4349
- }).catch(() => console.log("Permission set retrieval failed - likely accessing a non-RBAC backend"))
4350
- );
4351
- var getRoles = createAppAsyncThunk(
4352
- `${sliceName8}/getRoles`,
4353
- (_, { dispatch, getState }) => Promise.all([general_api_default.get(`${import_constants4.useradmApiUrlv2}/roles?per_page=500`), dispatch(getPermissionSets())]).then((results) => {
4354
- if (!results) {
4355
- return Promise.resolve();
4356
- }
4357
- const [{ data: roles }, { payload: permissionSetTasks }] = results;
4358
- const rolesById2 = normalizeRbacRoles(roles, getRolesById(getState()), permissionSetTasks[permissionSetTasks.length - 1]);
4359
- return Promise.resolve(dispatch(actions8.receivedRoles(rolesById2)));
4360
- }).catch(() => console.log("Role retrieval failed - likely accessing a non-RBAC backend")).finally(() => Promise.resolve(dispatch(actions8.finishedRoleInitialization(true))))
4361
- );
4362
- var deriveImpliedAreaPermissions = (area, areaPermissions, skipPermissions = []) => {
4363
- const highestAreaPermissionLevelSelected = areaPermissions.reduce(
4364
- (highest, current) => import_constants4.uiPermissionsById[current].permissionLevel > highest ? import_constants4.uiPermissionsById[current].permissionLevel : highest,
4365
- 1
4366
- );
4367
- return import_constants4.uiPermissionsByArea[area].uiPermissions.reduce((permissions, current) => {
4368
- if ((current.permissionLevel < highestAreaPermissionLevelSelected || areaPermissions.includes(current.value)) && !skipPermissions.includes(current.value)) {
4369
- permissions.push(current.value);
4370
- }
4371
- return permissions;
4372
- }, []);
4373
- };
4374
- var transformAreaRoleDataToScopedPermissionsSets = (area, areaPermissions, excessiveAccessSelector) => {
4375
- const permissionSetObject = areaPermissions.reduce((accu, { item, uiPermissions }) => {
4376
- const skipPermissions = import_constants4.scopedPermissionAreas.releases.key === area && item !== import_constants4.ALL_RELEASES ? [import_constants4.uiPermissionsById.upload.value] : [];
4377
- const impliedPermissions = deriveImpliedAreaPermissions(area, uiPermissions, skipPermissions);
4378
- accu = impliedPermissions.reduce((itemPermissionAccu, impliedPermission) => {
4379
- const permissionSetState = itemPermissionAccu[import_constants4.uiPermissionsById[impliedPermission].permissionSets[area]] ?? {
4380
- type: import_constants4.uiPermissionsByArea[area].scope,
4381
- value: []
4382
- };
4383
- itemPermissionAccu[import_constants4.uiPermissionsById[impliedPermission].permissionSets[area]] = {
4384
- ...permissionSetState,
4385
- value: [...permissionSetState.value, item]
4386
- };
4387
- return itemPermissionAccu;
4388
- }, accu);
4389
- return accu;
4390
- }, {});
4391
- return Object.entries(permissionSetObject).map(([name, { value, ...scope }]) => {
4392
- if (value.includes(excessiveAccessSelector)) {
4393
- return { name };
4394
- }
4395
- return { name, scope: { ...scope, value: value.filter(import_helpers10.duplicateFilter) } };
4396
- });
4397
- };
4398
- var transformRoleDataToRole = (roleData, roleState = {}) => {
4399
- const role = { ...roleState, ...roleData };
4400
- const { description = "", name, uiPermissions = import_constants4.emptyUiPermissions } = role;
4401
- const { maybeUiPermissions, remainderKeys } = Object.entries(import_constants4.emptyUiPermissions).reduce(
4402
- (accu, [key, emptyPermissions]) => {
4403
- if (!import_constants4.scopedPermissionAreas[key]) {
4404
- accu.remainderKeys.push(key);
4405
- } else if (uiPermissions[key]) {
4406
- accu.maybeUiPermissions[key] = uiPermissions[key].reduce(itemUiPermissionsReducer, emptyPermissions);
4407
- }
4408
- return accu;
4409
- },
4410
- { maybeUiPermissions: {}, remainderKeys: [] }
4411
- );
4412
- const { permissionSetsWithScope, roleUiPermissions } = remainderKeys.reduce(
4413
- (accu, area) => {
4414
- const areaPermissions = role.uiPermissions[area];
4415
- if (!Array.isArray(areaPermissions)) {
4416
- return accu;
4417
- }
4418
- const impliedPermissions = deriveImpliedAreaPermissions(area, areaPermissions);
4419
- accu.roleUiPermissions[area] = impliedPermissions;
4420
- const mappedPermissions = impliedPermissions.map((uiPermission) => ({ name: import_constants4.uiPermissionsById[uiPermission].permissionSets[area] }));
4421
- accu.permissionSetsWithScope.push(...mappedPermissions);
4422
- return accu;
4423
- },
4424
- { permissionSetsWithScope: [{ name: import_constants4.defaultPermissionSets.Basic.name }], roleUiPermissions: {} }
4425
- );
4426
- const scopedPermissionSets = Object.values(import_constants4.scopedPermissionAreas).reduce((accu, { key, excessiveAccessSelector }) => {
4427
- if (!uiPermissions[key]) {
4428
- return accu;
4429
- }
4430
- accu.push(
4431
- ...transformAreaRoleDataToScopedPermissionsSets(
4432
- key,
4433
- uiPermissions[key],
4434
- excessiveAccessSelector
4435
- )
4436
- );
4437
- return accu;
4438
- }, []);
4439
- return {
4440
- permissionSetsWithScope: [...permissionSetsWithScope, ...scopedPermissionSets],
4441
- role: {
4442
- ...import_constants4.emptyRole,
4443
- name,
4444
- description: description ? description : roleState.description || "",
4445
- uiPermissions: {
4446
- ...import_constants4.emptyUiPermissions,
4447
- ...roleUiPermissions,
4448
- ...maybeUiPermissions
4449
- }
4450
- }
4451
- };
4452
- };
4453
- var roleActions = {
4454
- create: {
4455
- successMessage: "The role was created successfully.",
4456
- errorMessage: "creating"
4457
- },
4458
- edit: {
4459
- successMessage: "The role has been updated.",
4460
- errorMessage: "editing"
4461
- },
4462
- remove: {
4463
- successMessage: "The role was deleted successfully.",
4464
- errorMessage: "removing"
4465
- }
4466
- };
4467
- var roleActionErrorHandler = (err, type, dispatch, meta) => {
4468
- let errorContext = `There was an error ${roleActions[type].errorMessage} the role.`;
4469
- if (meta) {
4470
- const { permissionSetsCreated, name } = meta;
4471
- errorContext += ` Tried to ${type} role ${name} with ${permissionSetsCreated} permission sets.`;
4472
- }
4473
- return commonErrorHandler(err, errorContext, dispatch);
4474
- };
4475
- var createRole = createAppAsyncThunk(`${sliceName8}/createRole`, (roleData, { dispatch }) => {
4476
- const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData);
4477
- return general_api_default.post(`${import_constants4.useradmApiUrlv2}/roles`, {
4478
- name: role.name,
4479
- description: role.description,
4480
- permission_sets_with_scope: permissionSetsWithScope
4481
- }).then(() => Promise.all([dispatch(actions8.createdRole(role)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.create.successMessage))])).catch((err) => roleActionErrorHandler(err, "create", dispatch, { permissionSetsCreated: permissionSetsWithScope.length, name: role.name }));
4482
- });
4483
- var editRole = createAppAsyncThunk(`${sliceName8}/editRole`, (roleData, { dispatch, getState }) => {
4484
- const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData, getRolesById(getState())[roleData.name]);
4485
- return general_api_default.put(`${import_constants4.useradmApiUrlv2}/roles/${role.name}`, {
4486
- description: role.description,
4487
- name: role.name,
4488
- permission_sets_with_scope: permissionSetsWithScope
4489
- }).then(() => Promise.all([dispatch(actions8.createdRole(role)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.edit.successMessage))])).catch((err) => roleActionErrorHandler(err, "edit", dispatch, { permissionSetsCreated: permissionSetsWithScope.length, name: role.name }));
4490
- });
4491
- var removeRole = createAppAsyncThunk(
4492
- `${sliceName8}/removeRole`,
4493
- (roleId, { dispatch }) => general_api_default.delete(`${import_constants4.useradmApiUrlv2}/roles/${roleId}`).then(() => Promise.all([dispatch(actions8.removedRole(roleId)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.remove.successMessage))])).catch((err) => roleActionErrorHandler(err, "remove", dispatch))
4494
- );
4495
- var getGlobalSettings2 = createAppAsyncThunk(
4496
- `${sliceName8}/getGlobalSettings`,
4497
- (_, { dispatch }) => general_api_default.get(`${import_constants4.useradmApiUrl}/settings`).then(({ data: settings, headers: { etag } }) => {
4498
- window.sessionStorage.setItem(settingsKeys.initialized, "true");
4499
- return Promise.all([dispatch(actions8.setGlobalSettings(settings)), dispatch(setOfflineThreshold()), etag]);
4500
- })
4501
- );
4502
- var saveGlobalSettings = createAppAsyncThunk(
4503
- `${sliceName8}/saveGlobalSettings`,
4504
- ({ beOptimistic = false, notify = false, ...settings }, { dispatch, getState }) => {
4505
- if (!window.sessionStorage.getItem(settingsKeys.initialized) && !beOptimistic) {
4506
- return;
4507
- }
4508
- return dispatch(getGlobalSettings2()).unwrap().then((result) => {
4509
- const updatedSettings = { ...getState().users.globalSettings, ...settings };
4510
- if (getCurrentUser(getState()).verified) {
4511
- updatedSettings["2fa"] = import_constants4.twoFAStates.enabled;
4512
- } else {
4513
- delete updatedSettings["2fa"];
4514
- }
4515
- const tasks = [dispatch(actions8.setGlobalSettings(updatedSettings))];
4516
- const headers = result[result.length - 1] ? { "If-Match": result[result.length - 1] } : {};
4517
- return general_api_default.post(`${import_constants4.useradmApiUrl}/settings`, updatedSettings, { headers }).then(() => {
4518
- if (notify) {
4519
- tasks.push(dispatch(setSnackbar4("Settings saved successfully")));
4520
- }
4521
- return Promise.all(tasks);
4522
- }).catch((err) => {
4523
- if (beOptimistic) {
4524
- return Promise.all([tasks]);
4525
- }
4526
- console.log(err);
4527
- return commonErrorHandler(err, `The settings couldn't be saved.`, dispatch);
4528
- });
4529
- });
4530
- }
4531
- );
4532
- var getUserSettings2 = createAppAsyncThunk(
4533
- `${sliceName8}/getUserSettings`,
4534
- (_, { dispatch }) => general_api_default.get(`${import_constants4.useradmApiUrl}/settings/me`).then(({ data: settings, headers: { etag } }) => {
4535
- window.sessionStorage.setItem(settingsKeys.initialized, "true");
4536
- return Promise.all([dispatch(actions8.setUserSettings(settings)), etag]);
4537
- })
4538
- );
4539
- var saveUserSettings = createAppAsyncThunk(
4540
- `${sliceName8}/saveUserSettings`,
4541
- (settings = { onboarding: {} }, { dispatch, getState }) => {
4542
- if (!getCurrentUser(getState()).id) {
4543
- return Promise.resolve();
4544
- }
4545
- return dispatch(getUserSettings2()).unwrap().then((result) => {
4546
- const userSettings = getUserSettings(getState());
4547
- const onboardingState = getOnboardingState(getState());
4548
- const tooltipState = getTooltipsState(getState());
4549
- const updatedSettings = {
4550
- ...userSettings,
4551
- ...settings,
4552
- firstLoginTimestamp: userSettings.firstLoginTimestamp ?? (0, import_dayjs2.default)().format(),
4553
- onboarding: {
4554
- ...onboardingState,
4555
- ...settings.onboarding
4556
- },
4557
- tooltips: tooltipState
4558
- };
4559
- const headers = result[result.length - 1] ? { "If-Match": result[result.length - 1] } : {};
4560
- return Promise.all([
4561
- Promise.resolve(dispatch(actions8.setUserSettings(updatedSettings))),
4562
- general_api_default.post(`${import_constants4.useradmApiUrl}/settings/me`, updatedSettings, { headers })
4563
- ]).catch(() => dispatch(actions8.setUserSettings(userSettings)));
4564
- });
4565
- }
4566
- );
4567
- var get2FAQRCode = createAppAsyncThunk(
4568
- `${sliceName8}/get2FAQRCode`,
4569
- (_, { dispatch }) => general_api_default.get(`${import_constants4.useradmApiUrl}/2faqr`).then((res) => dispatch(actions8.receivedQrCode(res.data.qr)))
4570
- );
4571
- var setHideAnnouncement = createAppAsyncThunk(
4572
- `${sliceName8}/setHideAnnouncement`,
4573
- ({ shouldHide, userId }, { dispatch, getState }) => {
4574
- const currentUserId = userId || getCurrentUser(getState()).id;
4575
- const announcement = getHostedAnnouncement(getState());
4576
- const hash = announcement ? (0, import_md5.default)(announcement) : "";
4577
- const announceCookie = cookies4.get(`${currentUserId}${hash}`);
4578
- if (shouldHide || hash.length && typeof announceCookie !== "undefined") {
4579
- cookies4.set(`${currentUserId}${hash}`, true, { maxAge: 604800 });
4580
- dispatch(setAnnouncement(""));
4581
- }
4582
- }
4583
- );
4584
- var getTokens = createAppAsyncThunk(
4585
- `${sliceName8}/getTokens`,
4586
- (_, { dispatch, getState }) => general_api_default.get(`${import_constants4.useradmApiUrl}/settings/tokens`).then(({ data: tokens }) => {
4587
- const user = getCurrentUser(getState());
4588
- const updatedUser = {
4589
- ...user,
4590
- tokens
4591
- };
4592
- return Promise.resolve(dispatch(actions8.updatedUser(updatedUser)));
4593
- })
4594
- );
4595
- var ONE_YEAR = 31536e3;
4596
- var generateToken = createAppAsyncThunk(
4597
- `${sliceName8}/generateToken`,
4598
- ({ expiresIn = ONE_YEAR, name }, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrl}/settings/tokens`, { name, expires_in: expiresIn }).then(({ data: token }) => Promise.all([dispatch(getTokens()), token])).catch((err) => commonErrorHandler(err, "There was an error creating the token:", dispatch))
4599
- );
4600
- var revokeToken = createAppAsyncThunk(
4601
- `${sliceName8}/revokeToken`,
4602
- (token, { dispatch }) => general_api_default.delete(`${import_constants4.useradmApiUrl}/settings/tokens/${token.id}`).then(() => Promise.resolve(dispatch(getTokens())))
4603
- );
4604
- var setTooltipReadState = createAppAsyncThunk(
4605
- `${sliceName8}/setTooltipReadState`,
4606
- async ({ persist, ...remainder }, { dispatch }) => {
4607
- dispatch(actions8.setTooltipState(remainder));
4608
- if (persist) {
4609
- await dispatch(saveUserSettings());
4610
- }
4611
- }
4612
- );
4613
- var setAllTooltipsReadState = createAppAsyncThunk(
4614
- `${sliceName8}/toggleHelptips`,
4615
- ({ readState = READ_STATES.read, tooltipIds }, { dispatch }) => {
4616
- const updatedTips = tooltipIds.reduce((accu, id) => ({ ...accu, [id]: { readState } }), {});
4617
- return Promise.resolve(dispatch(actions8.setTooltipsState(updatedTips))).then(() => dispatch(saveUserSettings()));
4618
- }
4619
- );
4620
- var submitUserFeedback = createAppAsyncThunk(
4621
- `${sliceName8}/submitFeedback`,
4622
- ({ formId, feedback }, { dispatch }) => general_api_default.post(`${import_constants4.useradmApiUrlv2}/support/feedback/${formId}`, feedback).then(() => {
4623
- if (formId === "product") {
4624
- const today = /* @__PURE__ */ new Date();
4625
- dispatch(saveUserSettings({ feedbackCollectedAt: today.toISOString().split("T")[0] }));
4626
- setTimeout(() => dispatch(actions8.setShowFeedbackDialog(false)), TIMEOUTS.threeSeconds);
4627
- }
4628
- })
4629
- );
4630
-
4631
- // src/useDeploymentDevice.ts
4632
- var { isUUID: isUUID2 } = import_validator2.default;
4633
- var useDeploymentDevice = (deploymentName) => {
4634
- const isLoading = (0, import_react2.useRef)(false);
4635
- const dispatch = useAppDispatch();
4636
- const devicesById = (0, import_react_redux2.useSelector)(getDevicesById);
4637
- const hasDeviceInfo = !!devicesById[deploymentName];
4638
- (0, import_react2.useEffect)(() => {
4639
- if (isLoading.current) {
4640
- return;
4641
- }
4642
- isLoading.current = true;
4643
- if (isUUID2(deploymentName) && !hasDeviceInfo) {
4644
- dispatch(getDeviceById2(deploymentName)).then(() => isLoading.current = false);
4645
- }
4646
- }, [deploymentName, dispatch, hasDeviceInfo]);
4647
- };
4648
- // Annotate the CommonJS export names for ESM import in node:
4649
- 0 && (module.exports = {
4650
- useDeploymentDevice
4651
- });
4652
28
  //# sourceMappingURL=useDeploymentDevice.cjs.map