strapi-plugin-magic-sessionmanager 4.20.0 → 4.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +104 -50
  3. package/dist/admin/{Analytics-B5GnwMtH.js → Analytics-DeDLGiCe.js} +1 -1
  4. package/dist/admin/{Analytics-B-MVQ6dQ.mjs → Analytics-WbCUmkQQ.mjs} +1 -1
  5. package/dist/admin/{App-xBOmg4g9.js → App-Bkv-W0Sv.js} +1640 -2561
  6. package/dist/admin/{App-DzbP5VPQ.mjs → App-C4bihk2K.mjs} +1610 -2531
  7. package/dist/admin/{OnlineUsersWidget-FuPPPCCV.js → OnlineUsersWidget-CSvNe2rC.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Bf3BICmx.mjs → OnlineUsersWidget-q0Z6nbbO.mjs} +1 -1
  9. package/dist/admin/{Settings-hpkloyO6.mjs → Settings-avD0DbXP.mjs} +17 -9
  10. package/dist/admin/{Settings-WRIXHLDa.js → Settings-xokFI5LO.js} +59 -51
  11. package/dist/admin/dashboardModel-BBNRgcEr.mjs +170 -0
  12. package/dist/admin/dashboardModel-D4389iIV.js +169 -0
  13. package/dist/admin/{de-Bzd14FzX.mjs → de-BQlEdBMr.mjs} +104 -4
  14. package/dist/admin/{de-Uqb30N5n.js → de-HcJ19LKI.js} +104 -4
  15. package/dist/admin/{en-CDBcocLk.js → en-DI-98CPM.js} +105 -5
  16. package/dist/admin/{en-DovyVwa5.mjs → en-DzuXWL1W.mjs} +105 -5
  17. package/dist/admin/{es-BygJxl1J.mjs → es-BfyED9YI.mjs} +104 -4
  18. package/dist/admin/{es-DA1X0RPv.js → es-Cm0Eklav.js} +104 -4
  19. package/dist/admin/{fr-CPPA27jW.js → fr-C3nzszsI.js} +104 -4
  20. package/dist/admin/{fr-DONxL73-.mjs → fr-CzFNGWq0.mjs} +104 -4
  21. package/dist/admin/index-6zc5D8eb.mjs +4729 -0
  22. package/dist/admin/index-Dk5Jqe5U.js +4730 -0
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-BMuwyaan.js → pt-BPZ6chPT.js} +104 -4
  26. package/dist/admin/{pt-D2yGNz2N.mjs → pt-DmyQnGI_.mjs} +104 -4
  27. package/dist/server/index.js +1048 -67
  28. package/dist/server/index.mjs +1048 -67
  29. package/package.json +1 -1
  30. package/dist/admin/index-DsaGGK7x.mjs +0 -2297
  31. package/dist/admin/index-Q_D-5LlE.js +0 -2298
  32. package/dist/admin/settingsTabs--7IsqMdn.mjs +0 -437
  33. package/dist/admin/settingsTabs-Dxlevody.js +0 -436
@@ -0,0 +1,4730 @@
1
+ "use strict";
2
+ const react = require("react");
3
+ const jsxRuntime = require("react/jsx-runtime");
4
+ const icons = require("@strapi/icons");
5
+ const reactIntl = require("react-intl");
6
+ const reactRouterDom = require("react-router-dom");
7
+ const designSystem = require("@strapi/design-system");
8
+ const StrapiAdmin = require("@strapi/strapi/admin");
9
+ const styled = require("styled-components");
10
+ const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
11
+ const styled__default = /* @__PURE__ */ _interopDefault(styled);
12
+ const strapi = { "name": "magic-sessionmanager", "displayName": "Magic Sessionmanager" };
13
+ const pluginPkg = {
14
+ strapi
15
+ };
16
+ const pluginId$1 = "magic-sessionmanager";
17
+ const PLUGIN_ID = pluginId$1;
18
+ const Initializer = ({ setPlugin }) => {
19
+ const ref = react.useRef(setPlugin);
20
+ react.useEffect(() => {
21
+ if (ref.current) {
22
+ ref.current(pluginId$1);
23
+ }
24
+ }, []);
25
+ return null;
26
+ };
27
+ const PluginIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(icons.Monitor, { "aria-hidden": true, focusable: false, ...props });
28
+ const TONES = {
29
+ danger: { background: "danger100", border: "danger200", icon: "danger700" },
30
+ success: { background: "success100", border: "success200", icon: "success700" },
31
+ warning: { background: "warning100", border: "warning200", icon: "warning700" },
32
+ default: { background: "primary100", border: "primary200", icon: "primary700" },
33
+ neutral: { background: "neutral0", border: "neutral200", icon: "neutral600" }
34
+ };
35
+ const AlertBody = styled__default.default(designSystem.Typography)`
36
+ min-width: 0;
37
+
38
+ & > * {
39
+ display: inline;
40
+ max-width: none;
41
+ margin: 0;
42
+ font-size: inherit;
43
+ font-weight: inherit;
44
+ line-height: inherit;
45
+ color: inherit;
46
+ }
47
+ `;
48
+ const PersistentAlert = react.forwardRef(function PersistentAlert2({
49
+ variant = "default",
50
+ title,
51
+ titleAs = "p",
52
+ stacked = false,
53
+ action,
54
+ closeLabel: _closeLabel,
55
+ onClose: _onClose,
56
+ children,
57
+ ...rest
58
+ }, ref) {
59
+ const tone = TONES[variant] || TONES.default;
60
+ const Icon = variant === "success" ? icons.CheckCircle : variant === "danger" || variant === "warning" ? icons.WarningCircle : icons.Information;
61
+ return /* @__PURE__ */ jsxRuntime.jsxs(
62
+ designSystem.Flex,
63
+ {
64
+ ref,
65
+ alignItems: "flex-start",
66
+ background: tone.background,
67
+ borderColor: tone.border,
68
+ shadow: "filterShadow",
69
+ gap: 3,
70
+ hasRadius: true,
71
+ padding: 5,
72
+ paddingRight: 6,
73
+ "data-persistent-alert": "",
74
+ ...rest,
75
+ children: [
76
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { shrink: 0, width: "2rem", height: "2rem", children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true, focusable: "false", width: "2rem", height: "2rem", fill: tone.icon }) }),
77
+ /* @__PURE__ */ jsxRuntime.jsxs(
78
+ designSystem.Flex,
79
+ {
80
+ direction: stacked ? "column" : "row",
81
+ alignItems: stacked ? "stretch" : "start",
82
+ gap: action || stacked ? 2 : 1,
83
+ wrap: stacked ? "nowrap" : "wrap",
84
+ role: variant === "danger" ? "alert" : "status",
85
+ width: "100%",
86
+ minWidth: 0,
87
+ children: [
88
+ title ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", textColor: "neutral800", tag: titleAs, children: title }) : null,
89
+ /* @__PURE__ */ jsxRuntime.jsx(AlertBody, { tag: "div", variant: "omega", textColor: "neutral800", children }),
90
+ action ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { children: action }) : null
91
+ ]
92
+ }
93
+ )
94
+ ]
95
+ }
96
+ );
97
+ });
98
+ const paragraphRhythm = styled.css`
99
+ p {
100
+ max-width: 72ch;
101
+ margin-block: 0;
102
+ line-height: 1.6;
103
+ text-wrap: pretty;
104
+ }
105
+
106
+ p + p {
107
+ margin-block-start: ${({ theme }) => theme.spaces[3]};
108
+ }
109
+
110
+ li {
111
+ max-width: 72ch;
112
+ line-height: 1.6;
113
+ text-wrap: pretty;
114
+ }
115
+
116
+ li + li {
117
+ margin-block-start: ${({ theme }) => theme.spaces[2]};
118
+ }
119
+ `;
120
+ const ReadableText = styled__default.default(designSystem.Typography)`
121
+ display: block;
122
+ width: 100%;
123
+ min-width: 0;
124
+ max-width: 72ch;
125
+ margin: 0;
126
+ line-height: 1.6;
127
+ text-wrap: pretty;
128
+
129
+ & + & {
130
+ margin-block-start: ${({ theme }) => theme.spaces[3]};
131
+ }
132
+ `;
133
+ const ParagraphGroup = styled__default.default.div`
134
+ display: block;
135
+ width: 100%;
136
+ min-width: 0;
137
+ `;
138
+ const InlineParagraphGroup = styled__default.default.span`
139
+ display: block;
140
+ width: 100%;
141
+ min-width: 0;
142
+ `;
143
+ const ReadableParagraphs = ({ id, text, ...typographyProps }) => {
144
+ const ParagraphContainer = typographyProps.tag === "span" ? InlineParagraphGroup : ParagraphGroup;
145
+ const paragraphs = String(text ?? "").split(/\n\s*\n/).map((paragraph) => paragraph.trim()).filter(Boolean);
146
+ return /* @__PURE__ */ jsxRuntime.jsx(ParagraphContainer, { id, "data-readable-paragraphs": "", children: paragraphs.map((paragraph, index2) => /* @__PURE__ */ jsxRuntime.jsx(
147
+ ReadableText,
148
+ {
149
+ ...typographyProps,
150
+ tag: typographyProps.tag || "p",
151
+ children: paragraph
152
+ },
153
+ `${id || "readable-paragraph"}-${index2}`
154
+ )) });
155
+ };
156
+ const PageContent = styled__default.default(designSystem.Flex)`
157
+ width: 100%;
158
+ min-width: 0;
159
+
160
+ ${paragraphRhythm}
161
+ `;
162
+ const PageShell = ({
163
+ headingId,
164
+ title,
165
+ documentTitle,
166
+ subtitle,
167
+ primaryAction,
168
+ secondaryAction,
169
+ navigationAction,
170
+ startActions,
171
+ endActions,
172
+ children
173
+ }) => {
174
+ const generatedId = react.useId();
175
+ const titleId = headingId || `page-title-${generatedId.replace(/:/g, "")}`;
176
+ const hasActionBar = Boolean(startActions || endActions);
177
+ const tabTitle = documentTitle || (typeof title === "string" ? title : "");
178
+ return /* @__PURE__ */ jsxRuntime.jsxs(StrapiAdmin.Page.Main, { "aria-labelledby": titleId, children: [
179
+ tabTitle ? /* @__PURE__ */ jsxRuntime.jsx(StrapiAdmin.Page.Title, { children: tabTitle }) : null,
180
+ /* @__PURE__ */ jsxRuntime.jsx(
181
+ StrapiAdmin.Layouts.Header,
182
+ {
183
+ id: titleId,
184
+ title,
185
+ subtitle,
186
+ primaryAction,
187
+ secondaryAction,
188
+ navigationAction
189
+ }
190
+ ),
191
+ hasActionBar ? /* @__PURE__ */ jsxRuntime.jsx(StrapiAdmin.Layouts.Action, { startActions, endActions }) : null,
192
+ /* @__PURE__ */ jsxRuntime.jsx(StrapiAdmin.Layouts.Content, { children: /* @__PURE__ */ jsxRuntime.jsx(
193
+ PageContent,
194
+ {
195
+ direction: "column",
196
+ alignItems: "stretch",
197
+ gap: 6,
198
+ paddingBottom: 8,
199
+ "data-text-rhythm": "page",
200
+ "data-page-shell": "",
201
+ children
202
+ }
203
+ ) })
204
+ ] });
205
+ };
206
+ const ALLOWED_COLUMNS = /* @__PURE__ */ new Set([1, 2, 3, 4, 6]);
207
+ function getGridItemSpans(columns, stackBelow = "medium") {
208
+ const count = ALLOWED_COLUMNS.has(columns) ? columns : 2;
209
+ const col = 12 / count;
210
+ const twoUp = count >= 2 ? 6 : 12;
211
+ if (stackBelow === "small") {
212
+ return { xs: 12, s: twoUp, m: twoUp, col };
213
+ }
214
+ return { xs: 12, s: 12, m: twoUp, col };
215
+ }
216
+ const EqualGrid = ({ columns = 2, stackBelow = "medium", gap = 6, label, children }) => {
217
+ const spans = getGridItemSpans(columns, stackBelow);
218
+ const items = react.Children.toArray(children).filter(Boolean);
219
+ return /* @__PURE__ */ jsxRuntime.jsx(
220
+ designSystem.Grid.Root,
221
+ {
222
+ gap,
223
+ role: label ? "group" : void 0,
224
+ "aria-label": label,
225
+ "data-equal-grid": columns,
226
+ children: items.map((child, index2) => /* @__PURE__ */ jsxRuntime.jsx(
227
+ designSystem.Grid.Item,
228
+ {
229
+ col: spans.col,
230
+ m: spans.m,
231
+ s: spans.s,
232
+ xs: spans.xs,
233
+ direction: "column",
234
+ alignItems: "stretch",
235
+ minWidth: 0,
236
+ children: child
237
+ },
238
+ child.key ?? index2
239
+ ))
240
+ }
241
+ );
242
+ };
243
+ const STAT_GRID_FOLD_REM = (4 * 200 + 3 * 16) / 10;
244
+ const DS_SMALL_REM = 52;
245
+ const StatGridFrame = styled__default.default.div`
246
+ container-type: inline-size;
247
+ min-width: 0;
248
+
249
+ @container (min-width: ${DS_SMALL_REM}rem) and (max-width: ${STAT_GRID_FOLD_REM - 0.01}rem) {
250
+ [data-equal-grid='4'] > * {
251
+ grid-column: span 6;
252
+ }
253
+ }
254
+
255
+ /* Rows without secondary lines: pin every value to the card bottom, so a
256
+ label that wraps onto two lines does not push its value off the row's line. */
257
+ &[data-align-values] [data-stat-body] {
258
+ flex: 1 1 auto;
259
+ }
260
+
261
+ &[data-align-values] [data-stat-text] {
262
+ justify-content: space-between;
263
+ }
264
+ `;
265
+ const StatGrid = ({ columns = 4, label, alignValues = false, children }) => /* @__PURE__ */ jsxRuntime.jsx(StatGridFrame, { "data-stat-grid": "", "data-align-values": alignValues ? "" : void 0, children: /* @__PURE__ */ jsxRuntime.jsx(EqualGrid, { columns, stackBelow: "small", gap: 4, label, children }) });
266
+ const IconTile = styled__default.default(designSystem.Flex)`
267
+ align-self: flex-start;
268
+
269
+ svg {
270
+ width: ${({ theme }) => theme.spaces[5]};
271
+ height: ${({ theme }) => theme.spaces[5]};
272
+ }
273
+
274
+ svg path {
275
+ fill: ${({ theme, $tone }) => theme.colors[`${$tone}600`]};
276
+ }
277
+ `;
278
+ const STAT_TONES = /* @__PURE__ */ new Set([
279
+ "primary",
280
+ "success",
281
+ "warning",
282
+ "danger",
283
+ "neutral",
284
+ "secondary",
285
+ "alternative"
286
+ ]);
287
+ const CardButton = styled__default.default(designSystem.Box)`
288
+ appearance: none;
289
+ font: inherit;
290
+ color: inherit;
291
+ text-align: start;
292
+ cursor: pointer;
293
+ width: 100%;
294
+
295
+ &:hover {
296
+ background: ${({ theme }) => theme.colors.primary100};
297
+ }
298
+ `;
299
+ const StatCard = ({
300
+ label,
301
+ value,
302
+ icon: Icon,
303
+ tone = "neutral",
304
+ description,
305
+ onClick,
306
+ pressed,
307
+ actionLabel
308
+ }) => {
309
+ const safeTone = STAT_TONES.has(tone) ? tone : "neutral";
310
+ const clickable = typeof onClick === "function";
311
+ const buttonProps = clickable ? {
312
+ tag: "button",
313
+ type: "button",
314
+ onClick,
315
+ "aria-pressed": Boolean(pressed),
316
+ "aria-label": actionLabel
317
+ } : {};
318
+ const Card = clickable ? CardButton : designSystem.Box;
319
+ return /* @__PURE__ */ jsxRuntime.jsx(
320
+ Card,
321
+ {
322
+ ...buttonProps,
323
+ background: "neutral0",
324
+ hasRadius: true,
325
+ shadow: "tableShadow",
326
+ borderColor: clickable ? pressed ? "primary600" : "neutral150" : void 0,
327
+ padding: 4,
328
+ flex: "1 1 auto",
329
+ minWidth: 0,
330
+ "data-stat-card": safeTone,
331
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, height: "100%", children: [
332
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 3, alignItems: "stretch", minWidth: 0, "data-stat-body": "", children: [
333
+ Icon ? /* @__PURE__ */ jsxRuntime.jsx(
334
+ IconTile,
335
+ {
336
+ $tone: safeTone,
337
+ background: `${safeTone}100`,
338
+ hasRadius: true,
339
+ padding: 2,
340
+ shrink: 0,
341
+ justifyContent: "center",
342
+ alignItems: "center",
343
+ "aria-hidden": true,
344
+ children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true, focusable: false })
345
+ }
346
+ ) : null,
347
+ /* @__PURE__ */ jsxRuntime.jsxs(
348
+ designSystem.Flex,
349
+ {
350
+ direction: "column",
351
+ alignItems: "flex-start",
352
+ gap: 1,
353
+ minWidth: 0,
354
+ flex: "1 1 auto",
355
+ "data-stat-text": "",
356
+ children: [
357
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "span", children: label }),
358
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "beta", textColor: "neutral800", tag: "span", children: value })
359
+ ]
360
+ }
361
+ )
362
+ ] }),
363
+ description ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", tag: "span", children: description }) : null
364
+ ] })
365
+ }
366
+ );
367
+ };
368
+ const MISSING_VALUE_GLYPH = "—";
369
+ const MISSING_VALUE_MESSAGE = Object.freeze({
370
+ messageId: "common.value.missing",
371
+ defaultMessage: "Not available"
372
+ });
373
+ function isMissingValue(value) {
374
+ if (value === null || value === void 0) return true;
375
+ if (typeof value === "number") return !Number.isFinite(value);
376
+ if (value instanceof Date) return !Number.isFinite(value.getTime());
377
+ if (typeof value === "string") {
378
+ const trimmed = value.trim();
379
+ return trimmed === "" || trimmed.toLowerCase() === "unknown";
380
+ }
381
+ return false;
382
+ }
383
+ function presentText(value) {
384
+ if (isMissingValue(value)) return "";
385
+ return String(value).trim();
386
+ }
387
+ const getTranslation = (id) => `${PLUGIN_ID}.${id}`;
388
+ const MissingValue = ({ textColor = "neutral600", variant }) => {
389
+ const { formatMessage } = reactIntl.useIntl();
390
+ const label = formatMessage({
391
+ id: getTranslation(MISSING_VALUE_MESSAGE.messageId),
392
+ defaultMessage: MISSING_VALUE_MESSAGE.defaultMessage
393
+ });
394
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { textColor, variant, "data-missing-value": "", children: [
395
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "aria-hidden": "true", children: MISSING_VALUE_GLYPH }),
396
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { children: label })
397
+ ] });
398
+ };
399
+ const ValueOrMissing = ({ value, children, textColor, variant }) => {
400
+ if (isMissingValue(value)) return /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { textColor, variant });
401
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children ?? String(value) });
402
+ };
403
+ const List = styled__default.default.dl`
404
+ display: grid;
405
+ grid-template-columns: minmax(0, 1fr);
406
+ gap: ${({ theme }) => theme.spaces[4]};
407
+ column-gap: ${({ theme, $columnGap }) => theme.spaces[$columnGap ?? 4]};
408
+ margin: 0;
409
+ min-width: 0;
410
+
411
+ ${({ theme }) => theme.breakpoints.small} {
412
+ grid-template-columns: repeat(${({ $columns }) => $columns}, minmax(0, 1fr));
413
+ }
414
+
415
+ & > div {
416
+ display: flex;
417
+ flex-direction: column;
418
+ gap: ${({ theme }) => theme.spaces[1]};
419
+ min-width: 0;
420
+ }
421
+
422
+ & > div[data-span='full'] {
423
+ grid-column: 1 / -1;
424
+ }
425
+
426
+ dt,
427
+ dd {
428
+ margin: 0;
429
+ min-width: 0;
430
+ }
431
+
432
+ dd {
433
+ overflow-wrap: break-word;
434
+ }
435
+
436
+ dd[data-wrap='anywhere'] {
437
+ overflow-wrap: anywhere;
438
+ }
439
+ `;
440
+ const PropertyList = ({ items = [], columns = 2, label, columnGap }) => /* @__PURE__ */ jsxRuntime.jsx(
441
+ List,
442
+ {
443
+ $columns: columns === 1 ? 1 : 2,
444
+ $columnGap: columnGap,
445
+ "aria-label": label,
446
+ "data-property-list": "",
447
+ children: items.filter(Boolean).map((item) => {
448
+ const wrapsAnywhere = item.kind === "id" || item.kind === "email";
449
+ const missing = item.render === void 0 && isMissingValue(item.value);
450
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { "data-span": item.fullWidth ? "full" : void 0, children: [
451
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: item.label }) }),
452
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { "data-wrap": wrapsAnywhere ? "anywhere" : void 0, children: missing ? /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "omega" }) : item.render ?? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral800", children: String(item.value) }) })
453
+ ] }, item.id);
454
+ })
455
+ }
456
+ );
457
+ const DEFAULT_DATE_OPTIONS = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
458
+ const RELATIVE_UNITS = [
459
+ ["year", 365 * 24 * 60 * 60],
460
+ ["month", 30 * 24 * 60 * 60],
461
+ ["week", 7 * 24 * 60 * 60],
462
+ ["day", 24 * 60 * 60],
463
+ ["hour", 60 * 60],
464
+ ["minute", 60],
465
+ ["second", 1]
466
+ ];
467
+ function toValidDate(value) {
468
+ if (value === null || value === void 0 || value === "") return null;
469
+ const date = value instanceof Date ? value : new Date(value);
470
+ return Number.isFinite(date.getTime()) ? date : null;
471
+ }
472
+ function formatSessionDate(value, locale, fallback = "", options = DEFAULT_DATE_OPTIONS) {
473
+ const date = toValidDate(value);
474
+ if (!date) return fallback;
475
+ try {
476
+ return new Intl.DateTimeFormat(locale || "en", options).format(date);
477
+ } catch {
478
+ return new Intl.DateTimeFormat("en", options).format(date);
479
+ }
480
+ }
481
+ function getRelativeTimeParts(value, now = Date.now()) {
482
+ const date = toValidDate(value);
483
+ const reference = toValidDate(now);
484
+ if (!date || !reference) return null;
485
+ const diffSeconds = Math.round((date.getTime() - reference.getTime()) / 1e3);
486
+ const absolute = Math.abs(diffSeconds);
487
+ if (absolute < 45) return { value: 0, unit: "second" };
488
+ for (const [unit, seconds] of RELATIVE_UNITS) {
489
+ if (absolute >= seconds) {
490
+ const amount = Math.round(diffSeconds / seconds);
491
+ return { value: amount === 0 ? Math.sign(diffSeconds) : amount, unit };
492
+ }
493
+ }
494
+ return { value: 0, unit: "second" };
495
+ }
496
+ function formatRelative(value, locale, { now = Date.now(), fallback = "" } = {}) {
497
+ const parts = getRelativeTimeParts(value, now);
498
+ if (!parts) return fallback;
499
+ const options = { numeric: "auto" };
500
+ try {
501
+ return new Intl.RelativeTimeFormat(locale || "en", options).format(parts.value, parts.unit);
502
+ } catch {
503
+ return new Intl.RelativeTimeFormat("en", options).format(parts.value, parts.unit);
504
+ }
505
+ }
506
+ const API_CLIENTS = [
507
+ ["curl/", "cURL"],
508
+ ["postman", "Postman"],
509
+ ["insomnia", "Insomnia"],
510
+ ["okhttp", "OkHttp"],
511
+ ["python-requests", "Python Requests"],
512
+ ["axios/", "Axios"],
513
+ ["node-fetch", "node-fetch"],
514
+ ["undici", "undici"],
515
+ ["go-http-client", "Go HTTP client"],
516
+ ["cfnetwork/", "CFNetwork"],
517
+ ["dart/", "Dart"],
518
+ ["java/", "Java"],
519
+ ["wget/", "Wget"],
520
+ ["httpie/", "HTTPie"]
521
+ ];
522
+ const RUNTIME_AGENTS = Object.freeze({ node: "Node.js", deno: "Deno", bun: "Bun" });
523
+ const BOT_PATTERN = /bot\b|crawler|spider|slurp|headlesschrome/i;
524
+ const TABLET_PATTERN = /(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i;
525
+ const MOBILE_PATTERN = /Mobile|Android|iP(?:hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(?:hpw|web)OS|Opera M(?:obi|ini)/;
526
+ const LEGACY_DEVICE_LABELS = Object.freeze({
527
+ desktop: "Desktop",
528
+ mobile: "Mobile",
529
+ tablet: "Tablet",
530
+ api: "API Client",
531
+ bot: "Bot",
532
+ "": ""
533
+ });
534
+ const detectBrowser = (ua) => {
535
+ if (ua.includes("edg/") || ua.includes("edga/") || ua.includes("edgios/")) return "Edge";
536
+ if (ua.includes("opr/") || ua.includes("opera")) return "Opera";
537
+ if (ua.includes("firefox/") || ua.includes("fxios/")) return "Firefox";
538
+ if (ua.includes("chrome/") || ua.includes("crios/")) return "Chrome";
539
+ if (ua.includes("safari/")) return "Safari";
540
+ return "";
541
+ };
542
+ const detectOs = (ua) => {
543
+ if (ua.includes("android")) return "Android";
544
+ if (ua.includes("iphone") || ua.includes("ipad") || ua.includes("ipod")) return "iOS";
545
+ if (ua.includes("windows")) return "Windows";
546
+ if (ua.includes("cros")) return "ChromeOS";
547
+ if (ua.includes("mac os x") || ua.includes("macintosh")) return "macOS";
548
+ if (ua.includes("linux") || ua.includes("x11")) return "Linux";
549
+ return "";
550
+ };
551
+ const DESKTOP_OPERATING_SYSTEMS = /* @__PURE__ */ new Set(["Windows", "macOS", "Linux", "ChromeOS"]);
552
+ function parseUserAgent(userAgent) {
553
+ const raw = typeof userAgent === "string" ? userAgent.trim() : "";
554
+ if (!raw || raw.toLowerCase() === "unknown") {
555
+ return { deviceType: "", device: "", deviceIcon: "unknown", browser: "", os: "" };
556
+ }
557
+ const ua = raw.toLowerCase();
558
+ const runtime = RUNTIME_AGENTS[ua.split("/")[0]];
559
+ if (runtime && !ua.includes(" ")) {
560
+ return {
561
+ deviceType: "api",
562
+ device: LEGACY_DEVICE_LABELS.api,
563
+ deviceIcon: "api",
564
+ browser: runtime,
565
+ os: ""
566
+ };
567
+ }
568
+ const apiClient = API_CLIENTS.find(([needle]) => ua.includes(needle));
569
+ if (apiClient) {
570
+ return {
571
+ deviceType: "api",
572
+ device: LEGACY_DEVICE_LABELS.api,
573
+ deviceIcon: "api",
574
+ browser: apiClient[1],
575
+ os: detectOs(ua)
576
+ };
577
+ }
578
+ const browser = detectBrowser(ua);
579
+ const os = detectOs(ua);
580
+ let deviceType = "";
581
+ if (BOT_PATTERN.test(raw)) deviceType = "bot";
582
+ else if (TABLET_PATTERN.test(raw)) deviceType = "tablet";
583
+ else if (MOBILE_PATTERN.test(raw)) deviceType = "mobile";
584
+ else if (DESKTOP_OPERATING_SYSTEMS.has(os)) deviceType = "desktop";
585
+ return {
586
+ deviceType,
587
+ device: LEGACY_DEVICE_LABELS[deviceType],
588
+ deviceIcon: deviceType || "unknown",
589
+ browser,
590
+ os
591
+ };
592
+ }
593
+ const BROWSER_VERSION_PATTERNS = [
594
+ /\bEdg(?:A|iOS)?\/([\d.]+)/i,
595
+ /\bOPR\/([\d.]+)/i,
596
+ /\b(?:Chrome|CriOS)\/([\d.]+)/i,
597
+ /\bFirefox\/([\d.]+)/i,
598
+ /\bVersion\/([\d.]+).*Safari/i
599
+ ];
600
+ function getBrowserVersionFromUserAgent(userAgent) {
601
+ if (typeof userAgent !== "string" || !userAgent.trim() || userAgent.trim().toLowerCase() === "unknown") {
602
+ return "";
603
+ }
604
+ for (const pattern of BROWSER_VERSION_PATTERNS) {
605
+ const match = userAgent.match(pattern);
606
+ if (match?.[1]) return match[1];
607
+ }
608
+ return "";
609
+ }
610
+ const DEVICE_TYPE_MESSAGES = Object.freeze({
611
+ desktop: Object.freeze({ messageId: "common.device.type.desktop", defaultMessage: "Desktop" }),
612
+ mobile: Object.freeze({ messageId: "common.device.type.mobile", defaultMessage: "Mobile" }),
613
+ tablet: Object.freeze({ messageId: "common.device.type.tablet", defaultMessage: "Tablet" }),
614
+ api: Object.freeze({ messageId: "common.device.type.api", defaultMessage: "API client" }),
615
+ bot: Object.freeze({ messageId: "common.device.type.bot", defaultMessage: "Bot" }),
616
+ unknown: Object.freeze({
617
+ messageId: "common.device.type.unknown",
618
+ defaultMessage: "Unknown device"
619
+ })
620
+ });
621
+ const DEVICE_SUMMARY_MESSAGE = Object.freeze({
622
+ messageId: "common.device.summary",
623
+ defaultMessage: "{browser} · {os}"
624
+ });
625
+ const DEVICE_TYPE_ALIASES = Object.freeze({
626
+ desktop: "desktop",
627
+ laptop: "desktop",
628
+ pc: "desktop",
629
+ computer: "desktop",
630
+ mobile: "mobile",
631
+ phone: "mobile",
632
+ smartphone: "mobile",
633
+ tablet: "tablet",
634
+ "api client": "api",
635
+ api: "api",
636
+ apiclient: "api",
637
+ bot: "bot",
638
+ crawler: "bot"
639
+ });
640
+ function normalizeDeviceType(value) {
641
+ if (typeof value !== "string") return "";
642
+ const key = value.trim().toLowerCase().replace(/[\s_-]+/g, " ");
643
+ return DEVICE_TYPE_ALIASES[key] || DEVICE_TYPE_ALIASES[key.replace(/ /g, "")] || "";
644
+ }
645
+ function getDeviceTypeMessage(deviceType) {
646
+ return DEVICE_TYPE_MESSAGES[deviceType] || DEVICE_TYPE_MESSAGES.unknown;
647
+ }
648
+ const TRAILING_VERSION = /\s+v?\d[\w./-]*$/i;
649
+ function splitNameAndVersion(value) {
650
+ let name2 = presentText(value);
651
+ const versions = [];
652
+ while (TRAILING_VERSION.test(name2)) {
653
+ const match = name2.match(TRAILING_VERSION);
654
+ versions.unshift(match[0].trim());
655
+ name2 = name2.slice(0, match.index).trim();
656
+ }
657
+ return { name: presentText(name2), version: versions.join(" ") };
658
+ }
659
+ function getDevicePresentation(session = {}) {
660
+ const row = session || {};
661
+ const userAgent = presentText(row.userAgent);
662
+ const parsed = userAgent ? parseUserAgent(userAgent) : null;
663
+ const storedBrowser = splitNameAndVersion(row.browserName);
664
+ const storedOs = splitNameAndVersion(row.osName);
665
+ const deviceType = parsed ? parsed.deviceType : normalizeDeviceType(row.deviceType);
666
+ const browser = parsed?.browser || storedBrowser.name;
667
+ const os = parsed?.os || storedOs.name;
668
+ const browserVersion = userAgent && getBrowserVersionFromUserAgent(userAgent) || presentText(row.browserVersion) || storedBrowser.version;
669
+ let summary = { text: "" };
670
+ if (browser && os) {
671
+ summary = { ...DEVICE_SUMMARY_MESSAGE, values: { browser, os } };
672
+ } else if (browser || os) {
673
+ summary = { text: browser || os };
674
+ }
675
+ return {
676
+ deviceType,
677
+ hasDeviceType: Boolean(deviceType),
678
+ icon: deviceType || "unknown",
679
+ deviceTypeMessage: getDeviceTypeMessage(deviceType),
680
+ browser,
681
+ browserVersion,
682
+ browserLabel: browser,
683
+ os,
684
+ hasSummary: Boolean(browser || os),
685
+ summary
686
+ };
687
+ }
688
+ const SESSION_STATES = Object.freeze(["active", "idle", "ended"]);
689
+ const SESSION_END_REASONS = Object.freeze([
690
+ "logout",
691
+ "idle",
692
+ "expired",
693
+ "manual",
694
+ "blocked",
695
+ "unrecorded"
696
+ ]);
697
+ const RECORDED_END_REASONS = /* @__PURE__ */ new Set(["logout", "idle", "expired", "manual", "blocked"]);
698
+ const ACTIVE_DEFINITION = Object.freeze({
699
+ messageId: "common.status.active.definition",
700
+ defaultMessage: "Open and used within the inactivity timeout."
701
+ });
702
+ const SESSION_STATUS_PRESENTATION = Object.freeze({
703
+ active: Object.freeze({
704
+ tone: "success",
705
+ messageId: "common.status.active",
706
+ defaultMessage: "Active",
707
+ // B.3 tooltip and A.3 definition are the same sentence: one message.
708
+ help: ACTIVE_DEFINITION,
709
+ definition: ACTIVE_DEFINITION
710
+ }),
711
+ idle: Object.freeze({
712
+ tone: "warning",
713
+ messageId: "common.status.idle",
714
+ defaultMessage: "Idle",
715
+ help: Object.freeze({
716
+ messageId: "common.status.idle.help",
717
+ defaultMessage: "Still open. It ends on its next request or at the next idle check. A token refresh makes it active again."
718
+ }),
719
+ definition: Object.freeze({
720
+ messageId: "common.status.idle.definition",
721
+ defaultMessage: "Open, but not used for longer than the inactivity timeout. It ends on its next request or at the next idle check. A token refresh makes it active again."
722
+ })
723
+ }),
724
+ ended: Object.freeze({
725
+ tone: "neutral",
726
+ messageId: "common.status.ended",
727
+ defaultMessage: "Ended",
728
+ help: null,
729
+ definition: Object.freeze({
730
+ messageId: "common.status.ended.definition",
731
+ defaultMessage: "The session can no longer be used. The user has to sign in again on this device."
732
+ })
733
+ })
734
+ });
735
+ const SESSION_END_REASON_PRESENTATION = Object.freeze({
736
+ logout: Object.freeze({
737
+ messageId: "common.endReason.logout",
738
+ defaultMessage: "Logged out",
739
+ description: Object.freeze({
740
+ messageId: "common.endReason.logout.description",
741
+ defaultMessage: "The user signed out."
742
+ })
743
+ }),
744
+ idle: Object.freeze({
745
+ messageId: "common.endReason.idle",
746
+ defaultMessage: "Timed out",
747
+ description: Object.freeze({
748
+ messageId: "common.endReason.idle.description",
749
+ defaultMessage: "Not used for longer than the inactivity timeout."
750
+ })
751
+ }),
752
+ expired: Object.freeze({
753
+ messageId: "common.endReason.expired",
754
+ defaultMessage: "Expired",
755
+ description: Object.freeze({
756
+ messageId: "common.endReason.expired.description",
757
+ defaultMessage: "Reached the maximum session age."
758
+ })
759
+ }),
760
+ manual: Object.freeze({
761
+ messageId: "common.endReason.manual",
762
+ defaultMessage: "Ended manually",
763
+ description: Object.freeze({
764
+ messageId: "common.endReason.manual.description",
765
+ defaultMessage: "Ended from the Strapi admin, or by the user from another of their devices."
766
+ })
767
+ }),
768
+ blocked: Object.freeze({
769
+ messageId: "common.endReason.blocked",
770
+ defaultMessage: "User blocked",
771
+ description: Object.freeze({
772
+ messageId: "common.endReason.blocked.description",
773
+ defaultMessage: "Ended because the user account was blocked."
774
+ })
775
+ }),
776
+ unrecorded: Object.freeze({
777
+ messageId: "common.endReason.unrecorded",
778
+ defaultMessage: "Reason not recorded",
779
+ description: Object.freeze({
780
+ messageId: "common.endReason.unrecorded.description",
781
+ defaultMessage: "No end reason was stored, for example because the session ended in Strapi’s own session store or was recorded by an older plugin version."
782
+ })
783
+ })
784
+ });
785
+ function getSessionState(session = {}) {
786
+ const row = session || {};
787
+ if (row.isActive === true) return row.isTrulyActive ? "active" : "idle";
788
+ return "ended";
789
+ }
790
+ function getSessionStatus(session = {}) {
791
+ return getSessionState(session);
792
+ }
793
+ function getSessionEndReason(session = {}) {
794
+ const row = session || {};
795
+ if (row.isActive === true) return null;
796
+ const reason = typeof row.terminationReason === "string" ? row.terminationReason.trim().toLowerCase() : "";
797
+ return RECORDED_END_REASONS.has(reason) ? (
798
+ /** @type {any} */
799
+ reason
800
+ ) : "unrecorded";
801
+ }
802
+ function isNativeOnlySession(session) {
803
+ const id = session?.id;
804
+ return typeof id === "string" && id.startsWith("native_");
805
+ }
806
+ function isSessionStatus(status) {
807
+ return SESSION_STATES.includes(
808
+ /** @type {any} */
809
+ status
810
+ );
811
+ }
812
+ function isSessionEndReason(reason) {
813
+ return SESSION_END_REASONS.includes(
814
+ /** @type {any} */
815
+ reason
816
+ );
817
+ }
818
+ function getSessionStatusPresentation(statusOrSession) {
819
+ const status = typeof statusOrSession === "string" ? statusOrSession : getSessionState(statusOrSession);
820
+ const key = isSessionStatus(status) ? status : "ended";
821
+ return { status: key, ...SESSION_STATUS_PRESENTATION[key] };
822
+ }
823
+ function getEndReasonPresentation(reason) {
824
+ const key = isSessionEndReason(reason) ? reason : "unrecorded";
825
+ return { reason: key, ...SESSION_END_REASON_PRESENTATION[key] };
826
+ }
827
+ function getSessionEndReasonPresentation(session) {
828
+ const reason = getSessionEndReason(session);
829
+ return reason ? getEndReasonPresentation(reason) : null;
830
+ }
831
+ function useSessionFormatters() {
832
+ const { formatMessage, locale } = reactIntl.useIntl();
833
+ const translate = react.useCallback(
834
+ (descriptor, values) => formatMessage(
835
+ { id: getTranslation(descriptor.messageId), defaultMessage: descriptor.defaultMessage },
836
+ values
837
+ ),
838
+ [formatMessage]
839
+ );
840
+ return react.useMemo(() => {
841
+ const formatDate = (value, options) => formatSessionDate(value, locale, MISSING_VALUE_GLYPH, options);
842
+ const formatRelativeTime = (value, now) => formatRelative(value, locale, { now: now ?? Date.now(), fallback: MISSING_VALUE_GLYPH });
843
+ const statusLabel = (statusOrSession) => translate(getSessionStatusPresentation(statusOrSession));
844
+ const endReasonLabel = (sessionOrReason) => {
845
+ const reason = typeof sessionOrReason === "string" ? getEndReasonPresentation(sessionOrReason) : getSessionEndReasonPresentation(sessionOrReason);
846
+ return reason ? translate(reason) : "";
847
+ };
848
+ const deviceTypeLabel = (session) => translate(getDevicePresentation(session).deviceTypeMessage);
849
+ const deviceSummary = (session) => {
850
+ const { summary } = getDevicePresentation(session);
851
+ return summary.text ?? translate(summary, summary.values);
852
+ };
853
+ return {
854
+ locale,
855
+ formatDate,
856
+ formatRelativeTime,
857
+ translate,
858
+ statusLabel,
859
+ endReasonLabel,
860
+ deviceTypeLabel,
861
+ deviceSummary
862
+ };
863
+ }, [locale, translate]);
864
+ }
865
+ const NoWrap$1 = styled__default.default.span`
866
+ white-space: nowrap;
867
+ `;
868
+ const StatusDetail = ({ session, status }) => {
869
+ const { formatMessage } = reactIntl.useIntl();
870
+ const { formatDate, formatRelativeTime, endReasonLabel } = useSessionFormatters();
871
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
872
+ let text;
873
+ if (status === "ended") {
874
+ const endedAt = toValidDate(session.logoutTime);
875
+ text = t("common.status.ended.detail", "{reason} · {endedAt}", {
876
+ reason: /* @__PURE__ */ jsxRuntime.jsx(NoWrap$1, { children: endReasonLabel(session) }, "reason"),
877
+ endedAt: endedAt ? /* @__PURE__ */ jsxRuntime.jsx(NoWrap$1, { children: formatDate(endedAt) }, "ended-at") : /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "pi" }, "ended-at")
878
+ });
879
+ } else {
880
+ const minutes = Number(session.minutesSinceActive);
881
+ const hasMinutes = session.minutesSinceActive !== null && session.minutesSinceActive !== void 0 && Number.isFinite(minutes);
882
+ text = status === "idle" && hasMinutes ? t("common.status.idle.detail", "Not used for {minutes} min", { minutes }) : t("common.status.active.detail", "Last active {time}", {
883
+ time: formatRelativeTime(session.lastActive || session.loginTime)
884
+ });
885
+ }
886
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", "data-status-detail": "", children: text });
887
+ };
888
+ const getBadgeColors = (tone) => tone === "warning" ? { backgroundColor: "warning200", textColor: "neutral800" } : { variant: tone };
889
+ const StatusBadge = ({ status, session, detail = false, showEndReason = false, size = "M" }) => {
890
+ const { formatMessage } = reactIntl.useIntl();
891
+ const presentation = getSessionStatusPresentation(status || session || {});
892
+ const translate = (descriptor) => formatMessage({
893
+ id: getTranslation(descriptor.messageId),
894
+ defaultMessage: descriptor.defaultMessage
895
+ });
896
+ const label = translate(presentation);
897
+ const badge = /* @__PURE__ */ jsxRuntime.jsx(
898
+ designSystem.Badge,
899
+ {
900
+ ...getBadgeColors(presentation.tone),
901
+ size,
902
+ "data-session-status": presentation.status,
903
+ children: label
904
+ }
905
+ );
906
+ if (!(detail || showEndReason) || !session) return badge;
907
+ const reason = presentation.status === "ended" ? getSessionEndReasonPresentation(session) : null;
908
+ const help = reason ? reason.description : presentation.help;
909
+ const native = isNativeOnlySession(session);
910
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
911
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", wrap: "wrap", children: [
912
+ help ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tooltip, { label: translate(help), children: /* @__PURE__ */ jsxRuntime.jsx("span", { children: badge }) }) : badge,
913
+ native ? /* @__PURE__ */ jsxRuntime.jsx(
914
+ designSystem.Tooltip,
915
+ {
916
+ label: formatMessage({
917
+ id: getTranslation("common.status.nativeSession.help"),
918
+ defaultMessage: "Created by Strapi’s own session store. No device or location details were recorded."
919
+ }),
920
+ children: /* @__PURE__ */ jsxRuntime.jsx("span", { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { variant: "neutral", size, "data-native-session": "", children: formatMessage({
921
+ id: getTranslation("common.status.nativeSession"),
922
+ defaultMessage: "Strapi session"
923
+ }) }) })
924
+ }
925
+ ) : null
926
+ ] }),
927
+ /* @__PURE__ */ jsxRuntime.jsx(StatusDetail, { session, status: presentation.status })
928
+ ] });
929
+ };
930
+ const canTakeFocus = (element) => Boolean(
931
+ element?.isConnected && typeof element.focus === "function" && !element.disabled && element.getAttribute?.("aria-disabled") !== "true"
932
+ );
933
+ function pickFocusTarget(opener, fallback) {
934
+ if (canTakeFocus(opener)) return opener;
935
+ return canTakeFocus(fallback) ? fallback : null;
936
+ }
937
+ function restoreDialogFocus(event, opener, fallback) {
938
+ const target = pickFocusTarget(opener, fallback);
939
+ if (!target) return;
940
+ event.preventDefault();
941
+ target.focus();
942
+ }
943
+ function refocusIfLost(opener, fallback, doc = typeof document === "undefined" ? void 0 : document) {
944
+ if (!doc) return;
945
+ const active = doc.activeElement;
946
+ if (active && active !== doc.body) return;
947
+ pickFocusTarget(opener, fallback)?.focus();
948
+ }
949
+ const ConfirmAction = ({
950
+ trigger,
951
+ title,
952
+ body,
953
+ confirmLabel,
954
+ onConfirm,
955
+ variant = "danger",
956
+ disabled = false,
957
+ fallbackFocusRef,
958
+ isOpen,
959
+ onOpenChange,
960
+ returnFocusRef
961
+ }) => {
962
+ const [internalOpen, setInternalOpen] = react.useState(false);
963
+ const [busy, setBusy] = react.useState(false);
964
+ const triggerRef = react.useRef(null);
965
+ const controlled = !trigger;
966
+ const open = controlled ? Boolean(isOpen) : internalOpen;
967
+ const restoreFocus = () => {
968
+ if (typeof window === "undefined") return;
969
+ window.requestAnimationFrame(() => {
970
+ const active = document.activeElement;
971
+ if (active && active !== document.body) return;
972
+ const ownTrigger = controlled ? returnFocusRef?.current : triggerRef.current;
973
+ const target = pickFocusTarget(ownTrigger, fallbackFocusRef?.current);
974
+ if (target) target.focus();
975
+ });
976
+ };
977
+ const setOpen = (next) => {
978
+ if (controlled) onOpenChange?.(next);
979
+ else setInternalOpen(next);
980
+ };
981
+ const handleOpenChange = (next) => {
982
+ if (busy) return;
983
+ setOpen(next);
984
+ if (!next) restoreFocus();
985
+ };
986
+ const handleConfirm = async (event) => {
987
+ event?.preventDefault?.();
988
+ setBusy(true);
989
+ try {
990
+ await onConfirm();
991
+ setOpen(false);
992
+ restoreFocus();
993
+ } catch {
994
+ } finally {
995
+ setBusy(false);
996
+ }
997
+ };
998
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Dialog.Root, { open, onOpenChange: handleOpenChange, children: [
999
+ trigger ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Trigger, { ref: triggerRef, disabled, children: trigger }) : null,
1000
+ /* @__PURE__ */ jsxRuntime.jsx(
1001
+ StrapiAdmin.ConfirmDialog,
1002
+ {
1003
+ title,
1004
+ variant,
1005
+ endAction: /* @__PURE__ */ jsxRuntime.jsx(
1006
+ designSystem.Button,
1007
+ {
1008
+ fullWidth: true,
1009
+ variant,
1010
+ onClick: handleConfirm,
1011
+ loading: busy,
1012
+ disabled: busy,
1013
+ children: confirmLabel
1014
+ }
1015
+ ),
1016
+ children: body
1017
+ }
1018
+ )
1019
+ ] });
1020
+ };
1021
+ const DEVICE_ICONS = {
1022
+ desktop: icons.Monitor,
1023
+ mobile: icons.Phone,
1024
+ tablet: icons.Phone,
1025
+ api: icons.Code,
1026
+ bot: icons.Server,
1027
+ unknown: icons.Information
1028
+ };
1029
+ const DeviceIcon = ({ icon }) => {
1030
+ const Icon = DEVICE_ICONS[icon] || icons.Information;
1031
+ return /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true, focusable: false });
1032
+ };
1033
+ const TargetLink = styled__default.default(designSystem.Link)`
1034
+ min-height: 3.2rem;
1035
+ display: inline-flex;
1036
+ align-items: center;
1037
+ align-self: flex-start;
1038
+ `;
1039
+ const ActionStack = styled__default.default.div`
1040
+ display: grid;
1041
+ grid-template-columns: minmax(0, 1fr);
1042
+ grid-auto-rows: 1fr;
1043
+ gap: ${({ theme }) => theme.spaces[2]};
1044
+ min-width: 0;
1045
+
1046
+ /* The buttons are the plugin's own children; wrapped labels centre
1047
+ through inheritance, not through a selector into the DS button. */
1048
+ & > button {
1049
+ height: auto;
1050
+ min-height: 3.2rem;
1051
+ padding-block: ${({ theme }) => theme.spaces[1]};
1052
+ text-align: center;
1053
+ }
1054
+ `;
1055
+ const pluginPermissions = {
1056
+ access: [{ action: `plugin::${pluginId$1}.access`, subject: null }],
1057
+ /** Strapi admin panel sessions (view). The server also requires `access`. */
1058
+ adminSessionsRead: [{ action: `plugin::${pluginId$1}.admin-sessions.read`, subject: null }],
1059
+ /** Signing admins out. The server also requires `access` and `admin-sessions.read`. */
1060
+ adminSessionsRevoke: [{ action: `plugin::${pluginId$1}.admin-sessions.revoke`, subject: null }],
1061
+ /** Admin sign-in history and Content Manager activity. The server also requires `access` and `admin-sessions.read`. */
1062
+ adminActivityRead: [{ action: `plugin::${pluginId$1}.admin-activity.read`, subject: null }],
1063
+ /**
1064
+ * Protected settings (4.17): location lookup, webhooks and the security log.
1065
+ * The server also requires `access` (and `admin-activity.read` for the log).
1066
+ */
1067
+ settingsUpdate: [{ action: `plugin::${pluginId$1}.settings.update`, subject: null }],
1068
+ /**
1069
+ * App-user security activity (4.22): failed sign-ins, lockouts, new devices,
1070
+ * impersonations ... of Users & Permissions accounts, and its export. The
1071
+ * server also requires `access`.
1072
+ */
1073
+ userActivityRead: [{ action: `plugin::${pluginId$1}.user-activity.read`, subject: null }],
1074
+ /** Lifting a sign-in lock. The server also requires `access`. */
1075
+ lockoutsUnlock: [{ action: `plugin::${pluginId$1}.lockouts.unlock`, subject: null }],
1076
+ /**
1077
+ * Impersonating app users (4.20): start, list and end. The server also
1078
+ * requires `access` and the Impersonation switch.
1079
+ */
1080
+ impersonateUsers: [{ action: `plugin::${pluginId$1}.impersonate.users`, subject: null }],
1081
+ /**
1082
+ * "View as admin" (4.20): the read-only permission preview of another
1083
+ * admin. The server also requires `access`, the switch and the
1084
+ * anti-escalation rules.
1085
+ */
1086
+ impersonateAdmins: [{ action: `plugin::${pluginId$1}.impersonate.admins`, subject: null }]
1087
+ };
1088
+ const SAFE_SCOPE = /^[A-Za-z0-9_.:-]{1,48}$/;
1089
+ const CANCEL_NAMES = /* @__PURE__ */ new Set(["AbortError", "TimeoutError", "CanceledError"]);
1090
+ function safeGet(value, key) {
1091
+ try {
1092
+ return value && typeof value === "object" ? value[key] : void 0;
1093
+ } catch {
1094
+ return void 0;
1095
+ }
1096
+ }
1097
+ function isCancelledRequest(error) {
1098
+ const name2 = safeGet(error, "name");
1099
+ return typeof name2 === "string" && CANCEL_NAMES.has(name2);
1100
+ }
1101
+ function logSafeAdminError(scope, error) {
1102
+ if (isCancelledRequest(error)) return;
1103
+ const safeScope = typeof scope === "string" && SAFE_SCOPE.test(scope) ? scope : "admin";
1104
+ const directStatus = safeGet(error, "status");
1105
+ const status = Number.isInteger(directStatus) ? directStatus : safeGet(safeGet(error, "response"), "status");
1106
+ const statusSuffix = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
1107
+ console.warn(`[${safeScope}] Request failed${statusSuffix}`);
1108
+ }
1109
+ function useSettingsTranslate() {
1110
+ const { formatMessage, locale } = reactIntl.useIntl();
1111
+ const t = react.useCallback(
1112
+ (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values),
1113
+ [formatMessage]
1114
+ );
1115
+ const tError = react.useCallback(
1116
+ (descriptor) => descriptor ? t(descriptor.messageId, descriptor.defaultMessage, descriptor.values) : void 0,
1117
+ [t]
1118
+ );
1119
+ return { t, tError, locale };
1120
+ }
1121
+ async function copyText(value, clipboard = globalThis.navigator?.clipboard) {
1122
+ if (typeof value !== "string") {
1123
+ throw new TypeError("clipboard_value_must_be_text");
1124
+ }
1125
+ if (!clipboard || typeof clipboard.writeText !== "function") {
1126
+ throw new Error("clipboard_unavailable");
1127
+ }
1128
+ await clipboard.writeText(value);
1129
+ }
1130
+ const USER_IMPERSONATION_DURATIONS = Object.freeze([15, 30, 60]);
1131
+ const DEFAULT_IMPERSONATION_MINUTES = 15;
1132
+ const REASON_MIN = 3;
1133
+ const REASON_MAX = 255;
1134
+ function validateReason(value) {
1135
+ const clean = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
1136
+ if (clean.length < REASON_MIN) {
1137
+ return {
1138
+ messageId: "impersonation.reason.tooShort",
1139
+ defaultMessage: "Enter a reason of at least {min} characters.",
1140
+ values: { min: REASON_MIN }
1141
+ };
1142
+ }
1143
+ if (clean.length > REASON_MAX) {
1144
+ return {
1145
+ messageId: "impersonation.reason.tooLong",
1146
+ defaultMessage: "Use at most {max} characters.",
1147
+ values: { max: REASON_MAX }
1148
+ };
1149
+ }
1150
+ return null;
1151
+ }
1152
+ function secondsUntil(iso, now = Date.now()) {
1153
+ const end = Date.parse(String(iso ?? ""));
1154
+ if (!Number.isFinite(end)) return 0;
1155
+ return Math.max(0, Math.floor((end - now) / 1e3));
1156
+ }
1157
+ function formatClock(seconds) {
1158
+ const total = Math.max(0, Math.floor(Number(seconds) || 0));
1159
+ const hours = Math.floor(total / 3600);
1160
+ const minutes = Math.floor(total % 3600 / 60);
1161
+ const rest = String(total % 60).padStart(2, "0");
1162
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}` : `${minutes}:${rest}`;
1163
+ }
1164
+ function submitFrontendHandoff(doc, handoff) {
1165
+ if (!doc || !handoff || typeof handoff.url !== "string" || typeof handoff.code !== "string") {
1166
+ return false;
1167
+ }
1168
+ let url;
1169
+ try {
1170
+ url = new URL(handoff.url);
1171
+ } catch {
1172
+ return false;
1173
+ }
1174
+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;
1175
+ const form = doc.createElement("form");
1176
+ form.method = "POST";
1177
+ form.action = url.toString();
1178
+ form.target = "_blank";
1179
+ form.rel = "noopener noreferrer";
1180
+ form.style.display = "none";
1181
+ const input = doc.createElement("input");
1182
+ input.type = "hidden";
1183
+ input.name = typeof handoff.field === "string" && handoff.field ? handoff.field : "code";
1184
+ input.value = handoff.code;
1185
+ form.appendChild(input);
1186
+ doc.body.appendChild(form);
1187
+ try {
1188
+ form.submit();
1189
+ } finally {
1190
+ form.remove();
1191
+ }
1192
+ return true;
1193
+ }
1194
+ const dialogs = /* @__PURE__ */ new Map();
1195
+ const mounted = /* @__PURE__ */ new Map();
1196
+ const listeners = /* @__PURE__ */ new Set();
1197
+ const notify = () => {
1198
+ for (const listener of listeners) listener();
1199
+ };
1200
+ function subscribeImpersonationDialogs(listener) {
1201
+ listeners.add(listener);
1202
+ return () => listeners.delete(listener);
1203
+ }
1204
+ function getImpersonationDialog(key) {
1205
+ return dialogs.get(key) || null;
1206
+ }
1207
+ function registerImpersonationPanel(key, instance) {
1208
+ const list = [...mounted.get(key) || [], instance];
1209
+ mounted.set(key, list);
1210
+ const dialog = dialogs.get(key);
1211
+ if (dialog && (!dialog.owner || !list.includes(dialog.owner))) {
1212
+ dialogs.set(key, { ...dialog, owner: instance });
1213
+ notify();
1214
+ }
1215
+ return () => {
1216
+ const rest = (mounted.get(key) || []).filter((id) => id !== instance);
1217
+ if (rest.length) mounted.set(key, rest);
1218
+ else mounted.delete(key);
1219
+ const current = dialogs.get(key);
1220
+ if (current && current.owner === instance) {
1221
+ dialogs.set(key, { ...current, owner: rest[rest.length - 1] || null });
1222
+ notify();
1223
+ }
1224
+ };
1225
+ }
1226
+ function openImpersonationDialog(key, instance) {
1227
+ dialogs.set(key, { open: true, owner: instance, draft: {} });
1228
+ notify();
1229
+ }
1230
+ function saveImpersonationDraft(key, draft) {
1231
+ const current = dialogs.get(key);
1232
+ if (current) dialogs.set(key, { ...current, draft });
1233
+ }
1234
+ function closeImpersonationDialog(key) {
1235
+ if (dialogs.delete(key)) notify();
1236
+ }
1237
+ const REFUSALS = Object.freeze({
1238
+ disabled: ["impersonation.error.disabled", "Impersonation is turned off in the settings."],
1239
+ "already-active": [
1240
+ "impersonation.error.alreadyActive",
1241
+ "An impersonation of this user is already running. End it first."
1242
+ ],
1243
+ blocked: ["impersonation.error.blocked", "Blocked accounts cannot be impersonated."],
1244
+ "api-token": ["impersonation.error.apiToken", "API tokens cannot impersonate."]
1245
+ });
1246
+ function useSecondsLeft(expiresAt) {
1247
+ const [now, setNow] = react.useState(() => Date.now());
1248
+ react.useEffect(() => {
1249
+ if (!expiresAt) return void 0;
1250
+ const timer = window.setInterval(() => setNow(Date.now()), 1e3);
1251
+ return () => window.clearInterval(timer);
1252
+ }, [expiresAt]);
1253
+ return secondsUntil(expiresAt, now);
1254
+ }
1255
+ const SecretField = ({ label, value, name: name2 }) => {
1256
+ const { t } = useSettingsTranslate();
1257
+ const { toggleNotification } = StrapiAdmin.useNotification();
1258
+ const copy = async () => {
1259
+ try {
1260
+ await copyText(value);
1261
+ toggleNotification({
1262
+ type: "success",
1263
+ message: t("impersonation.result.copied", "Copied to the clipboard.")
1264
+ });
1265
+ } catch {
1266
+ toggleNotification({
1267
+ type: "warning",
1268
+ message: t(
1269
+ "impersonation.result.copyFailed",
1270
+ "Copying failed. Select the text and copy it yourself."
1271
+ )
1272
+ });
1273
+ }
1274
+ };
1275
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: name2, children: [
1276
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: label }),
1277
+ /* @__PURE__ */ jsxRuntime.jsx(
1278
+ designSystem.TextInput,
1279
+ {
1280
+ value,
1281
+ readOnly: true,
1282
+ onFocus: (event) => event.target.select(),
1283
+ endAction: /* @__PURE__ */ jsxRuntime.jsx(
1284
+ designSystem.Field.Action,
1285
+ {
1286
+ label: t("impersonation.result.copy", "Copy {name}", { name: label }),
1287
+ onClick: copy,
1288
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Duplicate, {})
1289
+ }
1290
+ )
1291
+ }
1292
+ )
1293
+ ] });
1294
+ };
1295
+ const ImpersonateUserModal = ({
1296
+ open,
1297
+ onOpenChange,
1298
+ onCloseAutoFocus,
1299
+ user,
1300
+ status,
1301
+ onChanged
1302
+ }) => {
1303
+ const { t, tError } = useSettingsTranslate();
1304
+ const { post } = StrapiAdmin.useFetchClient();
1305
+ const { toggleNotification } = StrapiAdmin.useNotification();
1306
+ const notifyHintId = react.useId();
1307
+ const [saved] = react.useState(() => getImpersonationDialog(user.documentId)?.draft || {});
1308
+ const [reason, setReason] = react.useState(saved.reason ?? "");
1309
+ const [minutes, setMinutes] = react.useState(saved.minutes ?? DEFAULT_IMPERSONATION_MINUTES);
1310
+ const [notifyUser, setNotifyUser] = react.useState(saved.notifyUser === true);
1311
+ const [touched, setTouched] = react.useState(false);
1312
+ const [pending, setPending] = react.useState(null);
1313
+ const [failure, setFailure] = react.useState(null);
1314
+ const [result, setResult] = react.useState(saved.result ?? null);
1315
+ react.useEffect(() => {
1316
+ if (!open) return;
1317
+ saveImpersonationDraft(user.documentId, { reason, minutes, notifyUser, result });
1318
+ }, [open, user.documentId, reason, minutes, notifyUser, result]);
1319
+ const secondsLeft = useSecondsLeft(result?.impersonation?.expiresAt || null);
1320
+ const durations = Array.isArray(status?.durations) ? status.durations : USER_IMPERSONATION_DURATIONS;
1321
+ const reasonError = validateReason(reason);
1322
+ const showReasonError = touched && reasonError;
1323
+ const start = async () => {
1324
+ setTouched(true);
1325
+ if (reasonError) return;
1326
+ setPending("start");
1327
+ setFailure(null);
1328
+ try {
1329
+ const { data } = await post(
1330
+ `/${pluginId$1}/impersonation/users/${encodeURIComponent(user.documentId)}`,
1331
+ { reason: reason.trim(), durationMinutes: minutes, notifyUser }
1332
+ );
1333
+ setResult(data?.data || null);
1334
+ onChanged?.();
1335
+ } catch (err) {
1336
+ if (isCancelledRequest(err)) return;
1337
+ const response = err?.response;
1338
+ const reasonCode = response?.data?.error?.details?.reason;
1339
+ if (response?.status === 429) {
1340
+ setFailure(
1341
+ t(
1342
+ "impersonation.error.rateLimited",
1343
+ "Too many impersonations were started. Try again in a few minutes."
1344
+ )
1345
+ );
1346
+ } else if (REFUSALS[reasonCode]) {
1347
+ setFailure(t(...REFUSALS[reasonCode]));
1348
+ } else {
1349
+ logSafeAdminError("impersonation.start", err);
1350
+ setFailure(t("impersonation.error.start", "The impersonation could not be started."));
1351
+ }
1352
+ } finally {
1353
+ setPending(null);
1354
+ }
1355
+ };
1356
+ const end = async () => {
1357
+ if (!result?.impersonation?.id) return;
1358
+ setPending("end");
1359
+ try {
1360
+ await post(`/${pluginId$1}/impersonation/${result.impersonation.id}/end`, {});
1361
+ toggleNotification({
1362
+ type: "success",
1363
+ message: t("impersonation.ended", "Impersonation ended.")
1364
+ });
1365
+ onChanged?.();
1366
+ onOpenChange(false);
1367
+ } catch (err) {
1368
+ logSafeAdminError("impersonation.end", err);
1369
+ toggleNotification({
1370
+ type: "danger",
1371
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
1372
+ });
1373
+ } finally {
1374
+ setPending(null);
1375
+ }
1376
+ };
1377
+ const openFrontend = () => {
1378
+ setFailure(null);
1379
+ const onViolation = (event) => {
1380
+ if (String(event?.violatedDirective || "").startsWith("form-action")) {
1381
+ setFailure(
1382
+ t(
1383
+ "impersonation.error.csp",
1384
+ "Your Strapi security settings block sending the sign-in to {origin}. Add this origin to form-action of the Content-Security-Policy (see the README), then start again.",
1385
+ { origin: status?.frontendOrigin || "" }
1386
+ )
1387
+ );
1388
+ }
1389
+ };
1390
+ document.addEventListener("securitypolicyviolation", onViolation);
1391
+ window.setTimeout(
1392
+ () => document.removeEventListener("securitypolicyviolation", onViolation),
1393
+ 3e3
1394
+ );
1395
+ if (!submitFrontendHandoff(document, result?.handoff)) {
1396
+ setFailure(t("impersonation.error.frontend", "The frontend could not be opened."));
1397
+ }
1398
+ };
1399
+ const handoff = result?.handoff;
1400
+ const clock = formatClock(secondsLeft);
1401
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
1402
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: result ? t("impersonation.result.title", "Impersonating {user}", { user: user.label }) : t("impersonation.modal.title", "Impersonate {user}", { user: user.label }) }) }),
1403
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1404
+ failure ? /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: failure }) : null,
1405
+ !result ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1406
+ /* @__PURE__ */ jsxRuntime.jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
1407
+ "impersonation.modal.intro",
1408
+ "You get a short-lived sign-in as this user to reproduce a problem. Password, email address, account and sessions cannot be changed with it. It is recorded in the security log."
1409
+ ) }),
1410
+ /* @__PURE__ */ jsxRuntime.jsxs(
1411
+ designSystem.Field.Root,
1412
+ {
1413
+ name: "reason",
1414
+ required: true,
1415
+ error: showReasonError ? tError(reasonError) : void 0,
1416
+ hint: t(
1417
+ "impersonation.reason.hint",
1418
+ "Stored in the security log and, if you email the user, shown to them."
1419
+ ),
1420
+ children: [
1421
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("impersonation.reason.label", "Reason") }),
1422
+ /* @__PURE__ */ jsxRuntime.jsx(
1423
+ designSystem.Textarea,
1424
+ {
1425
+ value: reason,
1426
+ maxLength: REASON_MAX,
1427
+ placeholder: t("impersonation.reason.placeholder", "For example: ticket 4711"),
1428
+ onChange: (event) => setReason(event.target.value),
1429
+ onBlur: () => setTouched(true)
1430
+ }
1431
+ ),
1432
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {}),
1433
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
1434
+ ]
1435
+ }
1436
+ ),
1437
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "durationMinutes", children: [
1438
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("impersonation.duration.label", "Duration") }),
1439
+ /* @__PURE__ */ jsxRuntime.jsx(
1440
+ designSystem.SingleSelect,
1441
+ {
1442
+ value: String(minutes),
1443
+ onChange: (value) => setMinutes(Number(value)),
1444
+ children: durations.map((value) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: String(value), children: t(
1445
+ "impersonation.duration.minutes",
1446
+ "{count, plural, one {# minute} other {# minutes}}",
1447
+ {
1448
+ count: value
1449
+ }
1450
+ ) }, value))
1451
+ }
1452
+ )
1453
+ ] }),
1454
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [
1455
+ /* @__PURE__ */ jsxRuntime.jsx(
1456
+ designSystem.Checkbox,
1457
+ {
1458
+ checked: notifyUser,
1459
+ "aria-describedby": notifyHintId,
1460
+ onCheckedChange: (checked) => setNotifyUser(checked === true),
1461
+ children: t(
1462
+ "impersonation.notify.label",
1463
+ "Email the user that their account was opened"
1464
+ )
1465
+ }
1466
+ ),
1467
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { id: notifyHintId, variant: "pi", textColor: "neutral600", children: t(
1468
+ "impersonation.notify.hint",
1469
+ "Sent through Strapi’s email plugin, with the reason and the duration."
1470
+ ) })
1471
+ ] })
1472
+ ] }) : null,
1473
+ handoff?.type === "frontend" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1474
+ /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "default", closeLabel: t("common.close", "Close"), children: t(
1475
+ "impersonation.result.frontendBody",
1476
+ "Open {origin} within one minute. The sign-in link works once and is sent without appearing in the address bar.",
1477
+ { origin: status?.frontendOrigin || "" }
1478
+ ) }),
1479
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.ExternalLink, {}), onClick: openFrontend, children: t("impersonation.result.openFrontend", "Open frontend") }) })
1480
+ ] }) : null,
1481
+ handoff?.type === "token" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1482
+ /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "warning", closeLabel: t("common.close", "Close"), children: t(
1483
+ "impersonation.result.tokenBody",
1484
+ "Shown only once. Anyone who has this token acts as {user} until it ends. Do not store or share it.",
1485
+ { user: user.label }
1486
+ ) }),
1487
+ /* @__PURE__ */ jsxRuntime.jsx(
1488
+ SecretField,
1489
+ {
1490
+ name: "jwt",
1491
+ label: t("impersonation.result.accessToken", "Access token"),
1492
+ value: handoff.jwt
1493
+ }
1494
+ ),
1495
+ handoff.refreshToken ? /* @__PURE__ */ jsxRuntime.jsx(
1496
+ SecretField,
1497
+ {
1498
+ name: "refreshToken",
1499
+ label: t("impersonation.result.refreshToken", "Refresh token"),
1500
+ value: handoff.refreshToken
1501
+ }
1502
+ ) : null
1503
+ ] }) : null,
1504
+ result ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral800", tag: "p", "aria-live": "polite", children: t("impersonation.result.endsIn", "Ends in {time}.", { time: clock }) }) : null
1505
+ ] }) }),
1506
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Footer, { children: result ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1507
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "danger-light", onClick: end, loading: pending === "end", children: t("impersonation.end", "End impersonation") }),
1508
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: t("impersonation.result.done", "Done") }) })
1509
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1510
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: t("common.cancel", "Cancel") }) }),
1511
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: start, loading: pending === "start", children: t("impersonation.start", "Start impersonation") })
1512
+ ] }) })
1513
+ ] }) });
1514
+ };
1515
+ const focusVisibleTrigger = (documentId, fallback) => {
1516
+ const candidates = [
1517
+ ...document.querySelectorAll(
1518
+ `[data-impersonation-trigger="${globalThis.CSS?.escape ? globalThis.CSS.escape(documentId) : documentId}"]`
1519
+ )
1520
+ ];
1521
+ const visible = candidates.find((node) => node.getClientRects().length > 0);
1522
+ (visible || fallback)?.focus?.();
1523
+ };
1524
+ const ImpersonationPanelSection = ({ documentId, userLabel }) => {
1525
+ const { t } = useSettingsTranslate();
1526
+ const { get, post } = StrapiAdmin.useFetchClient();
1527
+ const { toggleNotification } = StrapiAdmin.useNotification();
1528
+ const { formatDate } = useSessionFormatters();
1529
+ const {
1530
+ isLoading,
1531
+ allowedActions: { canUsers }
1532
+ } = StrapiAdmin.useRBAC(pluginPermissions.impersonateUsers);
1533
+ const [status, setStatus] = react.useState(null);
1534
+ const [active, setActive] = react.useState(null);
1535
+ const instance = react.useId();
1536
+ const dialog = react.useSyncExternalStore(
1537
+ subscribeImpersonationDialogs,
1538
+ () => getImpersonationDialog(documentId)
1539
+ );
1540
+ const open = dialog?.open === true && dialog.owner === instance;
1541
+ react.useEffect(() => registerImpersonationPanel(documentId, instance), [documentId, instance]);
1542
+ const triggerRef = react.useRef(null);
1543
+ const endTriggerRef = react.useRef(null);
1544
+ const requestRef = react.useRef(0);
1545
+ const apply = react.useCallback(
1546
+ async (request, pending) => {
1547
+ try {
1548
+ const [statusResponse, listResponse] = await pending;
1549
+ if (request !== requestRef.current) return;
1550
+ setStatus(statusResponse?.data?.data || null);
1551
+ const rows = Array.isArray(listResponse?.data?.data) ? listResponse.data.data : [];
1552
+ setActive(
1553
+ rows.find((row) => row.targetType === "user" && row.targetId === documentId) || null
1554
+ );
1555
+ } catch (err) {
1556
+ if (isCancelledRequest(err) || request !== requestRef.current) return;
1557
+ logSafeAdminError("impersonation.panel", err);
1558
+ setStatus(null);
1559
+ }
1560
+ },
1561
+ [documentId]
1562
+ );
1563
+ const fetchState = react.useCallback(
1564
+ () => Promise.all([
1565
+ get(`/${pluginId$1}/impersonation/status`),
1566
+ get(`/${pluginId$1}/impersonation/active`)
1567
+ ]),
1568
+ [get]
1569
+ );
1570
+ const load = react.useCallback(() => apply(++requestRef.current, fetchState()), [apply, fetchState]);
1571
+ react.useEffect(() => {
1572
+ if (isLoading || !canUsers || !documentId) return;
1573
+ apply(++requestRef.current, fetchState());
1574
+ }, [apply, canUsers, documentId, fetchState, isLoading]);
1575
+ if (isLoading || !canUsers || !status?.enabled) return null;
1576
+ const end = async () => {
1577
+ try {
1578
+ await post(`/${pluginId$1}/impersonation/${active.id}/end`, {});
1579
+ toggleNotification({
1580
+ type: "success",
1581
+ message: t("impersonation.ended", "Impersonation ended.")
1582
+ });
1583
+ } catch (err) {
1584
+ logSafeAdminError("impersonation.end", err);
1585
+ toggleNotification({
1586
+ type: "danger",
1587
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
1588
+ });
1589
+ throw err;
1590
+ } finally {
1591
+ await load();
1592
+ }
1593
+ };
1594
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-impersonation": "", children: [
1595
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("impersonation.panel.title", "Impersonation") }),
1596
+ active ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1597
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral800", tag: "p", children: t("impersonation.panel.running", "Running until {time}.", {
1598
+ time: formatDate(active.expiresAt, { hour: "2-digit", minute: "2-digit" })
1599
+ }) }),
1600
+ /* @__PURE__ */ jsxRuntime.jsx(
1601
+ ConfirmAction,
1602
+ {
1603
+ title: t("impersonation.confirm.title", "End the impersonation of {user}?", {
1604
+ user: userLabel
1605
+ }),
1606
+ body: t(
1607
+ "impersonation.confirm.body",
1608
+ "The short-lived sign-in stops working at once. This is recorded in the security log."
1609
+ ),
1610
+ confirmLabel: t("impersonation.end", "End impersonation"),
1611
+ onConfirm: end,
1612
+ fallbackFocusRef: triggerRef,
1613
+ trigger: /* @__PURE__ */ jsxRuntime.jsx(
1614
+ designSystem.Button,
1615
+ {
1616
+ ref: endTriggerRef,
1617
+ "data-impersonation-trigger": documentId,
1618
+ fullWidth: true,
1619
+ size: "S",
1620
+ variant: "danger-light",
1621
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.SignOut, { "aria-hidden": true, focusable: false }),
1622
+ type: "button",
1623
+ children: t("impersonation.end", "End impersonation")
1624
+ }
1625
+ )
1626
+ }
1627
+ )
1628
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(
1629
+ designSystem.Button,
1630
+ {
1631
+ ref: triggerRef,
1632
+ "data-impersonation-trigger": documentId,
1633
+ fullWidth: true,
1634
+ size: "S",
1635
+ variant: "secondary",
1636
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.User, { "aria-hidden": true, focusable: false }),
1637
+ onClick: () => openImpersonationDialog(documentId, instance),
1638
+ type: "button",
1639
+ children: t("impersonation.panel.start", "Impersonate…")
1640
+ }
1641
+ ),
1642
+ open ? /* @__PURE__ */ jsxRuntime.jsx(
1643
+ ImpersonateUserModal,
1644
+ {
1645
+ open: true,
1646
+ onOpenChange: (next) => {
1647
+ if (!next) {
1648
+ closeImpersonationDialog(documentId);
1649
+ load();
1650
+ window.setTimeout(
1651
+ () => focusVisibleTrigger(documentId, triggerRef.current || endTriggerRef.current),
1652
+ 0
1653
+ );
1654
+ }
1655
+ },
1656
+ onCloseAutoFocus: (event) => {
1657
+ event.preventDefault();
1658
+ focusVisibleTrigger(documentId, triggerRef.current || endTriggerRef.current);
1659
+ },
1660
+ user: { documentId, label: userLabel },
1661
+ status,
1662
+ onChanged: load
1663
+ }
1664
+ ) : null
1665
+ ] });
1666
+ };
1667
+ function useElementWidth() {
1668
+ const [width, setWidth] = react.useState(0);
1669
+ const observerRef = react.useRef(null);
1670
+ const ref = react.useCallback((node) => {
1671
+ observerRef.current?.disconnect();
1672
+ observerRef.current = null;
1673
+ if (!node || typeof ResizeObserver === "undefined") return;
1674
+ const observer = new ResizeObserver((entries) => {
1675
+ const next = Math.round(entries[0]?.contentRect?.width || 0);
1676
+ setWidth((previous) => previous === next ? previous : next);
1677
+ });
1678
+ observer.observe(node);
1679
+ observerRef.current = observer;
1680
+ }, []);
1681
+ react.useEffect(() => () => observerRef.current?.disconnect(), []);
1682
+ return [ref, width];
1683
+ }
1684
+ const CSV_HEADERS = Object.freeze([
1685
+ "ID",
1686
+ "Status",
1687
+ "User Email",
1688
+ "Username",
1689
+ "Device",
1690
+ "Browser",
1691
+ "OS",
1692
+ "IP Address",
1693
+ "Login Time",
1694
+ "Last Active",
1695
+ "Logout Time",
1696
+ "Minutes Idle",
1697
+ "End Reason"
1698
+ ]);
1699
+ const FORMULA_START = /^[\s\u00ad\u200b-\u200f\u2060-\u2064\ufeff]*[=+\-@\uff1d\uff0b\uff0d\uff20\t\r\n]/;
1700
+ const escapeCsvValue = (value) => {
1701
+ const text = String(value ?? "");
1702
+ const safe = typeof value === "string" && FORMULA_START.test(text) ? `'${text}` : text;
1703
+ return `"${safe.replace(/"/g, '""')}"`;
1704
+ };
1705
+ function toIsoTimestamp(value) {
1706
+ if (value === null || value === void 0 || value === "") return "";
1707
+ const date = value instanceof Date ? value : new Date(
1708
+ /** @type {any} */
1709
+ value
1710
+ );
1711
+ return Number.isFinite(date.getTime()) ? date.toISOString() : "";
1712
+ }
1713
+ function buildSessionCsv(sessions, {
1714
+ unavailableValue,
1715
+ getDeviceInfo,
1716
+ getSessionStatus: getSessionStatus2,
1717
+ getSessionEndReason: getSessionEndReason$1 = getSessionEndReason
1718
+ }) {
1719
+ const rows = Array.isArray(sessions) ? sessions : [];
1720
+ const csvRows = rows.map((session) => {
1721
+ const deviceInfo = getDeviceInfo(session, unavailableValue);
1722
+ const minutesIdle = Number.isFinite(session.minutesSinceActive) ? session.minutesSinceActive : "";
1723
+ return [
1724
+ session.id,
1725
+ getSessionStatus2(session),
1726
+ session.user?.email || "",
1727
+ session.user?.username || "",
1728
+ deviceInfo.device,
1729
+ deviceInfo.browser,
1730
+ deviceInfo.os,
1731
+ session.ipAddress || unavailableValue,
1732
+ toIsoTimestamp(session.loginTime),
1733
+ toIsoTimestamp(session.lastActive || session.loginTime),
1734
+ toIsoTimestamp(session.logoutTime),
1735
+ minutesIdle,
1736
+ getSessionEndReason$1(session) || ""
1737
+ ];
1738
+ });
1739
+ return [
1740
+ CSV_HEADERS.map(escapeCsvValue).join(","),
1741
+ ...csvRows.map((row) => row.map(escapeCsvValue).join(","))
1742
+ ].join("\n");
1743
+ }
1744
+ function buildSessionJson(sessions, {
1745
+ filterStatus,
1746
+ totalSessions,
1747
+ exportedAt,
1748
+ unavailableValue,
1749
+ getDeviceInfo,
1750
+ getSessionStatus: getSessionStatus2,
1751
+ getSessionEndReason: getSessionEndReason$1 = getSessionEndReason,
1752
+ truncated = false
1753
+ }) {
1754
+ const rows = Array.isArray(sessions) ? sessions : [];
1755
+ const exportData = {
1756
+ exportedAt,
1757
+ filter: filterStatus,
1758
+ totalSessions,
1759
+ exportedSessions: rows.length,
1760
+ ...truncated ? { truncated: true } : {},
1761
+ sessions: rows.map((session) => {
1762
+ const deviceInfo = getDeviceInfo(session, unavailableValue);
1763
+ return {
1764
+ id: session.id,
1765
+ status: getSessionStatus2(session),
1766
+ endReason: getSessionEndReason$1(session) || null,
1767
+ user: {
1768
+ id: session.user?.documentId || session.user?.id,
1769
+ email: session.user?.email,
1770
+ username: session.user?.username
1771
+ },
1772
+ device: {
1773
+ type: deviceInfo.device,
1774
+ browser: deviceInfo.browser,
1775
+ browserVersion: deviceInfo.browserVersion,
1776
+ os: deviceInfo.os
1777
+ },
1778
+ ipAddress: session.ipAddress || unavailableValue,
1779
+ loginTime: session.loginTime,
1780
+ lastActive: session.lastActive,
1781
+ logoutTime: session.logoutTime,
1782
+ minutesSinceActive: session.minutesSinceActive,
1783
+ isActive: session.isActive,
1784
+ isTrulyActive: session.isTrulyActive
1785
+ };
1786
+ })
1787
+ };
1788
+ return JSON.stringify(exportData, null, 2);
1789
+ }
1790
+ const SETTINGS_TAB_IDS = Object.freeze([
1791
+ "sessions",
1792
+ "login-protection",
1793
+ "location-data",
1794
+ "alerts",
1795
+ "data-retention",
1796
+ "impersonation",
1797
+ "admin-activity"
1798
+ ]);
1799
+ const PERMISSION_GATED_TABS = Object.freeze(["admin-activity"]);
1800
+ const DEFAULT_SETTINGS_TAB = "sessions";
1801
+ const SETTINGS_TAB_LABELS = Object.freeze({
1802
+ sessions: ["settings.config.tab.sessions", "Sessions"],
1803
+ "login-protection": ["settings.config.tab.loginProtection", "Login protection"],
1804
+ "location-data": ["settings.config.tab.locationData", "Location data"],
1805
+ alerts: ["settings.config.tab.alerts", "Alerts"],
1806
+ "data-retention": ["settings.config.tab.dataRetention", "Data and retention"],
1807
+ impersonation: ["settings.config.tab.impersonation", "Impersonation"],
1808
+ "admin-activity": ["settings.config.tab.adminActivity", "Admin activity"]
1809
+ });
1810
+ const SETTINGS_TAB_FIELDS = Object.freeze({
1811
+ sessions: [
1812
+ "inactivityTimeout",
1813
+ "maxSessionAgeDays",
1814
+ "lastSeenRateLimit",
1815
+ "cleanupInterval",
1816
+ "cleanupUseDbDirect",
1817
+ "strictSessionEnforcement",
1818
+ "sessionCreationGraceMs",
1819
+ "maxSessionsPerUser",
1820
+ "sessionLimitPolicy",
1821
+ "endOtherSessionsOnPasswordChange",
1822
+ "roleRules"
1823
+ ],
1824
+ "login-protection": [
1825
+ "maxFailedLogins",
1826
+ "maxFailedLoginsPerAccount",
1827
+ "lockoutWindowMinutes",
1828
+ "lockoutDurationMinutes",
1829
+ "lockoutTrustedAddresses",
1830
+ "lockoutNotifyUser",
1831
+ "recordUserSignInEvents",
1832
+ "impossibleTravelEnabled",
1833
+ "impossibleTravelSpeedKmh",
1834
+ "impossibleTravelMinDistanceKm",
1835
+ "impossibleTravelAction",
1836
+ "trustedProxies",
1837
+ "blockSuspiciousSessions",
1838
+ "geoLookupFailureMode",
1839
+ "enableGeofencing",
1840
+ "allowedCountries",
1841
+ "blockedCountries"
1842
+ ],
1843
+ "location-data": [
1844
+ "enableGeolocation",
1845
+ "enableSecurityScoring",
1846
+ "geoIpProvider",
1847
+ "geoIpDatabasePath"
1848
+ ],
1849
+ alerts: [
1850
+ "enableEmailAlerts",
1851
+ "alertOnSuspiciousLogin",
1852
+ "alertOnNewLocation",
1853
+ "alertOnVpnProxy",
1854
+ "emailTemplates",
1855
+ "enableWebhooks",
1856
+ "discordWebhookUrl",
1857
+ "slackWebhookUrl",
1858
+ "alertOnNewDevice",
1859
+ "alertOnImpossibleTravel",
1860
+ "webhookEvents",
1861
+ "genericWebhookEnabled",
1862
+ "genericWebhookUrl",
1863
+ "genericWebhookSecret"
1864
+ ],
1865
+ "data-retention": ["retentionDays", "sessionIpAnonymize"],
1866
+ impersonation: ["impersonationEnabled"],
1867
+ "admin-activity": [
1868
+ "adminSignInHistory",
1869
+ "adminContentActivity",
1870
+ "securityLogStoreIp",
1871
+ "securityLogAnonymizeIp",
1872
+ "securityLogGeoLookup",
1873
+ "securityLogRetentionDays"
1874
+ ]
1875
+ });
1876
+ const PRESERVED_SETTINGS_KEYS = Object.freeze([
1877
+ "rateLimitWriteMax",
1878
+ "rateLimitReadMax",
1879
+ "rateLimitWindowSeconds"
1880
+ ]);
1881
+ const SETTINGS_FIELD_LABELS = Object.freeze({
1882
+ inactivityTimeout: ["settings.config.sessions.inactivity.label", "Inactivity timeout"],
1883
+ maxSessionAgeDays: ["settings.config.sessions.maxAge.label", "Maximum session age"],
1884
+ lastSeenRateLimit: [
1885
+ "settings.config.sessions.lastSeen.label",
1886
+ 'Update "Last active" at most every'
1887
+ ],
1888
+ cleanupInterval: ["settings.config.sessions.idleCheck.label", "Run idle check every"],
1889
+ cleanupUseDbDirect: ["settings.config.sessions.idleMethod.label", "Idle check method"],
1890
+ strictSessionEnforcement: ["settings.config.token.check.label", "Strict token check"],
1891
+ sessionCreationGraceMs: ["settings.config.token.grace.label", "Grace period after sign-in"],
1892
+ maxFailedLogins: ["settings.config.failed.lockout.label", "Lock an IP address after"],
1893
+ maxFailedLoginsPerAccount: ["settings.config.failed.account.label", "Lock an account after"],
1894
+ lockoutWindowMinutes: ["settings.config.failed.window.label", "Count failed sign-ins within"],
1895
+ lockoutDurationMinutes: ["settings.config.failed.duration.label", "Lock for"],
1896
+ lockoutTrustedAddresses: ["settings.config.failed.trusted.label", "Trusted addresses"],
1897
+ lockoutNotifyUser: [
1898
+ "settings.config.failed.notify.label",
1899
+ "Email the user when their account is locked"
1900
+ ],
1901
+ recordUserSignInEvents: [
1902
+ "settings.config.failed.record.label",
1903
+ "Record failed and refused sign-ins"
1904
+ ],
1905
+ maxSessionsPerUser: ["settings.config.sessionLimit.max.label", "Open sessions per user"],
1906
+ sessionLimitPolicy: ["settings.config.sessionLimit.policy.label", "When the limit is reached"],
1907
+ endOtherSessionsOnPasswordChange: [
1908
+ "settings.config.passwordChange.label",
1909
+ "End other sessions after a password change"
1910
+ ],
1911
+ roleRules: ["settings.roleRules.title", "Different rules for some roles"],
1912
+ impossibleTravelEnabled: ["settings.config.travel.enable.label", "Detect impossible travel"],
1913
+ impossibleTravelSpeedKmh: ["settings.config.travel.speed.label", "Faster than"],
1914
+ impossibleTravelMinDistanceKm: ["settings.config.travel.distance.label", "Over at least"],
1915
+ impossibleTravelAction: ["settings.config.travel.action.label", "Then"],
1916
+ alertOnNewDevice: ["settings.config.email.newDevice.label", "Sign-in from a new device"],
1917
+ alertOnImpossibleTravel: ["settings.config.email.travel.label", "Impossible travel"],
1918
+ webhookEvents: ["settings.webhookEvents.title", "Events to send"],
1919
+ genericWebhookEnabled: ["settings.signedWebhook.enable.label", "Send to the signed webhook"],
1920
+ genericWebhookUrl: ["settings.signedWebhook.url.label", "Webhook URL"],
1921
+ genericWebhookSecret: ["settings.signedWebhook.secret.label", "Signing secret"],
1922
+ sessionIpAnonymize: ["settings.config.privacy.shortIp.label", "Shorten IP addresses of sessions"],
1923
+ trustedProxies: ["settings.config.clientIp.trustProxy.label", "Trust proxy headers"],
1924
+ blockSuspiciousSessions: [
1925
+ "settings.config.suspicious.reject.label",
1926
+ "Reject suspicious sign-ins"
1927
+ ],
1928
+ geoLookupFailureMode: [
1929
+ "settings.config.suspicious.failureMode.label",
1930
+ "If the location cannot be determined"
1931
+ ],
1932
+ enableGeofencing: ["settings.config.countries.enable.label", "Use country rules"],
1933
+ allowedCountries: ["settings.config.countries.list.label", "Countries"],
1934
+ blockedCountries: ["settings.config.countries.list.label", "Countries"],
1935
+ enableGeolocation: ["settings.config.lookup.enable.label", "IP location lookup"],
1936
+ enableSecurityScoring: ["settings.config.lookup.scoring.label", "Security scoring"],
1937
+ geoIpProvider: ["settings.config.provider.label", "Provider"],
1938
+ geoIpDatabasePath: ["settings.config.database.fileName.label", "Database file name"],
1939
+ enableEmailAlerts: ["settings.config.email.enable.label", "Send security emails"],
1940
+ alertOnSuspiciousLogin: ["settings.config.email.suspicious.label", "Suspicious sign-in"],
1941
+ alertOnNewLocation: ["settings.config.email.newCountry.label", "Sign-in from a new country"],
1942
+ alertOnVpnProxy: ["settings.config.email.vpnProxy.label", "VPN or proxy"],
1943
+ emailTemplates: ["settings.config.email.templates.field", "Email templates"],
1944
+ enableWebhooks: ["settings.config.webhooks.enable.label", "Send team notifications"],
1945
+ discordWebhookUrl: ["settings.config.webhooks.discord.label", "Discord webhook URL"],
1946
+ slackWebhookUrl: ["settings.config.webhooks.slack.label", "Slack webhook URL"],
1947
+ retentionDays: ["settings.config.retention.keep.label", "Keep ended sessions for"],
1948
+ impersonationEnabled: ["settings.impersonation.enable.label", "Allow impersonation"],
1949
+ adminSignInHistory: ["settings.config.adminActivity.signIns.label", "Record admin sign-ins"],
1950
+ adminContentActivity: [
1951
+ "settings.config.adminActivity.content.label",
1952
+ "Record Content Manager activity"
1953
+ ],
1954
+ securityLogStoreIp: ["settings.config.adminActivity.storeIp.label", "Store IP addresses"],
1955
+ securityLogAnonymizeIp: [
1956
+ "settings.config.adminActivity.anonymize.label",
1957
+ "Anonymise the last part of IP addresses"
1958
+ ],
1959
+ securityLogGeoLookup: [
1960
+ "settings.config.adminActivity.geoLookup.label",
1961
+ "Look up the location of security events"
1962
+ ],
1963
+ securityLogRetentionDays: [
1964
+ "settings.config.adminActivity.retention.label",
1965
+ "Keep security events for"
1966
+ ]
1967
+ });
1968
+ const SELECT_PRESETS = Object.freeze({
1969
+ inactivityTimeout: Object.freeze([5, 10, 15, 30, 60, 120]),
1970
+ maxSessionAgeDays: Object.freeze([1, 7, 14, 30, 60, 90, 180, 365]),
1971
+ lastSeenRateLimit: Object.freeze([10, 30, 60, 120, 300]),
1972
+ cleanupInterval: Object.freeze([15, 30, 60, 120]),
1973
+ sessionCreationGraceMs: Object.freeze([0, 2e3, 5e3, 1e4, 3e4]),
1974
+ retentionDays: Object.freeze([7, 30, 60, 90, 180, 365, -1]),
1975
+ securityLogRetentionDays: Object.freeze([7, 30, 90, 180, 365])
1976
+ });
1977
+ function resolveSettingsTab(value, tabs = SETTINGS_TAB_IDS) {
1978
+ const candidate = Array.isArray(value) ? value[0] : value;
1979
+ return tabs.includes(candidate) ? candidate : DEFAULT_SETTINGS_TAB;
1980
+ }
1981
+ function getVisibleSettingsTabs(canViewAdminActivity) {
1982
+ return SETTINGS_TAB_IDS.filter(
1983
+ (tab) => canViewAdminActivity || !PERMISSION_GATED_TABS.includes(tab)
1984
+ );
1985
+ }
1986
+ function buildTabSearch(search, tab) {
1987
+ const params = new URLSearchParams(typeof search === "string" ? search : "");
1988
+ params.set("tab", resolveSettingsTab(tab));
1989
+ return `?${params.toString()}`;
1990
+ }
1991
+ function fieldHasError(errors, field) {
1992
+ return Object.keys(errors || {}).some((path) => path === field || path.startsWith(`${field}.`));
1993
+ }
1994
+ function tabHasFieldErrors(errors, tab) {
1995
+ return (SETTINGS_TAB_FIELDS[tab] || []).some((field) => fieldHasError(errors, field));
1996
+ }
1997
+ function getErrorTab(errors) {
1998
+ return SETTINGS_TAB_IDS.find((tab) => tabHasFieldErrors(errors, tab));
1999
+ }
2000
+ function buildSelectOptions(presets, current) {
2001
+ const options = presets.map((value) => ({ value, custom: false }));
2002
+ const number = typeof current === "number" ? current : Number.parseInt(String(current ?? ""), 10);
2003
+ if (Number.isInteger(number) && !presets.includes(number)) {
2004
+ options.push({ value: number, custom: true });
2005
+ }
2006
+ return options;
2007
+ }
2008
+ function buildSavePayload(draft, saved) {
2009
+ const payload = { ...draft || {} };
2010
+ for (const key of PRESERVED_SETTINGS_KEYS) {
2011
+ if (saved && Object.prototype.hasOwnProperty.call(saved, key)) payload[key] = saved[key];
2012
+ }
2013
+ return payload;
2014
+ }
2015
+ function usesLocalDatabase(provider) {
2016
+ return provider === void 0 || provider === null || provider === "" || provider === "auto" || provider === "local-mmdb";
2017
+ }
2018
+ function getRevealScrollDelta(listRect, tabRect) {
2019
+ if (!listRect || !tabRect) return 0;
2020
+ if (tabRect.left < listRect.left - 0.5) return Math.round(tabRect.left - listRect.left);
2021
+ if (tabRect.right > listRect.right + 0.5) return Math.round(tabRect.right - listRect.right);
2022
+ return 0;
2023
+ }
2024
+ const SIGN_IN_FILTER_OPTIONS = Object.freeze(["all", "succeeded", "failed", "signed-out"]);
2025
+ const ALL_ADMINS_FILTER_OPTIONS = Object.freeze([...SIGN_IN_FILTER_OPTIONS, "changes"]);
2026
+ const ACTIVITY_ACTION_OPTIONS = Object.freeze([
2027
+ "all",
2028
+ "view",
2029
+ "create",
2030
+ "update",
2031
+ "publish",
2032
+ "unpublish",
2033
+ "discard",
2034
+ "delete",
2035
+ "clone"
2036
+ ]);
2037
+ const PERIOD_OPTIONS = Object.freeze(["1", "7", "30", "90", "all"]);
2038
+ const EVENT_PAGE_SIZE = 20;
2039
+ const MAX_EVENT_EXPORT_ROWS = 1e4;
2040
+ function periodStart(period, now = /* @__PURE__ */ new Date()) {
2041
+ const days = Number.parseInt(period, 10);
2042
+ if (!Number.isInteger(days) || days <= 0) return void 0;
2043
+ return new Date(now.getTime() - days * 24 * 60 * 60 * 1e3).toISOString();
2044
+ }
2045
+ function buildSignInParams(filters, now) {
2046
+ const params = {
2047
+ page: filters.page || 1,
2048
+ pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2049
+ event: ALL_ADMINS_FILTER_OPTIONS.includes(filters.event) ? filters.event : "all"
2050
+ };
2051
+ if (filters.adminId) params.adminId = String(filters.adminId);
2052
+ const from = periodStart(filters.period || "all", now);
2053
+ if (from) params.from = from;
2054
+ return params;
2055
+ }
2056
+ function buildActivityParams(filters, now) {
2057
+ const params = {
2058
+ page: filters.page || 1,
2059
+ pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2060
+ action: ACTIVITY_ACTION_OPTIONS.includes(filters.action) ? filters.action : "all"
2061
+ };
2062
+ if (filters.adminId) params.adminId = String(filters.adminId);
2063
+ if (filters.contentType && filters.contentType !== "all")
2064
+ params.contentType = filters.contentType;
2065
+ const from = periodStart(filters.period || "all", now);
2066
+ if (from) params.from = from;
2067
+ return params;
2068
+ }
2069
+ function toExportParams(params, cursor) {
2070
+ const { page: _page, pageSize: _pageSize, ...rest } = params;
2071
+ return cursor ? { ...rest, cursor } : rest;
2072
+ }
2073
+ const message$1 = (messageId, defaultMessage) => ({ messageId, defaultMessage });
2074
+ const FAILURE_REASONS = Object.freeze({
2075
+ invalid_credentials: message$1(
2076
+ "adminPanel.activity.reason.invalidCredentials",
2077
+ "Wrong email or password"
2078
+ ),
2079
+ account_inactive: message$1("adminPanel.activity.reason.accountInactive", "Account is deactivated"),
2080
+ login_not_allowed: message$1("adminPanel.activity.reason.notAllowed", "Sign-in is not allowed"),
2081
+ rate_limited: message$1("adminPanel.activity.reason.rateLimited", "Too many attempts")
2082
+ });
2083
+ const LOG_READ_DETAILS = Object.freeze({
2084
+ "sign-ins": [
2085
+ message$1("adminPanel.activity.read.signIns", "Sign-in history listed"),
2086
+ message$1("adminPanel.activity.read.signInsExport", "Sign-in history exported")
2087
+ ],
2088
+ content: [
2089
+ message$1("adminPanel.activity.read.content", "Content Manager activity listed"),
2090
+ message$1("adminPanel.activity.read.contentExport", "Content Manager activity exported")
2091
+ ],
2092
+ "user-activity": [
2093
+ message$1("adminPanel.activity.read.userActivity", "App-user security activity listed"),
2094
+ message$1("adminPanel.activity.read.userActivityExport", "App-user security activity exported")
2095
+ ]
2096
+ });
2097
+ const appUserEvent = (key, tone, icon, messageId, defaultMessage) => ({
2098
+ key,
2099
+ tone,
2100
+ icon,
2101
+ label: message$1(messageId, defaultMessage),
2102
+ detail: null
2103
+ });
2104
+ function getEventPresentation(row) {
2105
+ switch (row?.event) {
2106
+ case "admin.sign-in":
2107
+ return {
2108
+ key: "sign-in",
2109
+ tone: "success",
2110
+ icon: "signIn",
2111
+ label: message$1("adminPanel.activity.event.signIn", "Signed in"),
2112
+ detail: row.reason === "registration" ? message$1("adminPanel.activity.reason.registration", "First sign-in after registration") : row.reason === "password_reset" ? message$1(
2113
+ "adminPanel.activity.reason.passwordReset",
2114
+ "Signed in after a password reset"
2115
+ ) : null
2116
+ };
2117
+ case "admin.sign-in.failed":
2118
+ return {
2119
+ key: "failed",
2120
+ tone: "danger",
2121
+ icon: "failed",
2122
+ label: message$1("adminPanel.activity.event.failed", "Sign-in failed"),
2123
+ detail: FAILURE_REASONS[row.reason] || null
2124
+ };
2125
+ case "admin.lockout":
2126
+ return {
2127
+ key: "lockout",
2128
+ tone: "danger",
2129
+ icon: "lockout",
2130
+ label: message$1("adminPanel.activity.event.lockout", "Locked out"),
2131
+ detail: FAILURE_REASONS.rate_limited
2132
+ };
2133
+ case "admin.sign-out":
2134
+ return {
2135
+ key: "sign-out",
2136
+ tone: "neutral",
2137
+ icon: "signOut",
2138
+ label: message$1("adminPanel.activity.event.signOut", "Signed out"),
2139
+ detail: null
2140
+ };
2141
+ case "admin.session.revoked":
2142
+ return {
2143
+ key: "revoked",
2144
+ tone: "warning",
2145
+ icon: "revoked",
2146
+ label: message$1("adminPanel.activity.event.revoked", "Signed out by an admin"),
2147
+ detail: row.scope === "one_browser" ? message$1("adminPanel.activity.scope.oneBrowser", "One browser") : message$1("adminPanel.activity.scope.everywhere", "Every browser")
2148
+ };
2149
+ case "settings.updated":
2150
+ return {
2151
+ key: "settings",
2152
+ tone: "secondary",
2153
+ icon: "settings",
2154
+ label: message$1("adminPanel.activity.event.settings", "Settings changed"),
2155
+ detail: row.change?.viaToken ? message$1("adminPanel.activity.via.token", "With an admin API token") : null
2156
+ };
2157
+ case "security-log.read":
2158
+ return {
2159
+ key: "log-read",
2160
+ tone: "secondary",
2161
+ icon: row.read?.via === "admin-panel" ? "export" : "logRead",
2162
+ // 4.22: exports of the app-user activity from the admin panel are recorded too.
2163
+ label: row.read?.via === "admin-panel" ? message$1("adminPanel.activity.event.logExported", "Security log exported") : message$1("adminPanel.activity.event.logRead", "Log read with an API token"),
2164
+ detail: LOG_READ_DETAILS[row.read?.list || "sign-ins"]?.[row.read?.exported ? 1 : 0] || null
2165
+ };
2166
+ case "security-log.retention.purged":
2167
+ return {
2168
+ key: "purged",
2169
+ tone: "neutral",
2170
+ icon: "purged",
2171
+ label: message$1("adminPanel.activity.event.purged", "Old events deleted"),
2172
+ detail: null
2173
+ };
2174
+ // App-user events (4.17 / 4.18), listed by the app-user Security activity (4.22) only.
2175
+ // The admin lists never return them; the labels are plain because that view is about app
2176
+ // users already.
2177
+ case "user.sign-in.failed":
2178
+ return appUserEvent(
2179
+ "user-failed",
2180
+ "danger",
2181
+ "failed",
2182
+ "adminPanel.activity.event.userFailed",
2183
+ "Sign-in failed"
2184
+ );
2185
+ case "user.sign-in.refused":
2186
+ return appUserEvent(
2187
+ "user-refused",
2188
+ "danger",
2189
+ "refused",
2190
+ "adminPanel.activity.event.userRefused",
2191
+ "Sign-in refused"
2192
+ );
2193
+ case "user.lockout":
2194
+ return appUserEvent(
2195
+ "user-lockout",
2196
+ "danger",
2197
+ "lockout",
2198
+ "adminPanel.activity.event.userLockout",
2199
+ "Locked out"
2200
+ );
2201
+ case "user.lockout.lifted":
2202
+ return appUserEvent(
2203
+ "user-unlock",
2204
+ "secondary",
2205
+ "unlock",
2206
+ "adminPanel.activity.event.userUnlock",
2207
+ "Lock lifted"
2208
+ );
2209
+ case "user.session.limit":
2210
+ return appUserEvent(
2211
+ "user-limit",
2212
+ "warning",
2213
+ "limit",
2214
+ "adminPanel.activity.event.userLimit",
2215
+ "Session limit reached"
2216
+ );
2217
+ case "user.password-change.ended-others":
2218
+ return appUserEvent(
2219
+ "user-password",
2220
+ "warning",
2221
+ "password",
2222
+ "adminPanel.activity.event.userPassword",
2223
+ "Signed out after a password change"
2224
+ );
2225
+ case "user.sign-in.new-device":
2226
+ return appUserEvent(
2227
+ "user-device",
2228
+ "secondary",
2229
+ "device",
2230
+ "adminPanel.activity.event.userNewDevice",
2231
+ "Sign-in from a new device"
2232
+ );
2233
+ case "user.sign-in.impossible-travel":
2234
+ return appUserEvent(
2235
+ "user-travel",
2236
+ "danger",
2237
+ "travel",
2238
+ "adminPanel.activity.event.userTravel",
2239
+ "Impossible travel"
2240
+ );
2241
+ case "user.not-me":
2242
+ return appUserEvent(
2243
+ "user-not-me",
2244
+ "danger",
2245
+ "notMe",
2246
+ "adminPanel.activity.event.userNotMe",
2247
+ 'Reported as "This wasn’t me"'
2248
+ );
2249
+ case "user.data.exported":
2250
+ return appUserEvent(
2251
+ "user-export",
2252
+ "secondary",
2253
+ "export",
2254
+ "adminPanel.activity.event.userExport",
2255
+ "Personal data exported"
2256
+ );
2257
+ case "impersonation.started":
2258
+ return appUserEvent(
2259
+ "impersonation-started",
2260
+ "warning",
2261
+ "impersonation",
2262
+ "adminPanel.activity.event.impersonationStarted",
2263
+ "Impersonation started"
2264
+ );
2265
+ case "impersonation.ended":
2266
+ return appUserEvent(
2267
+ "impersonation-ended",
2268
+ "neutral",
2269
+ "impersonationEnd",
2270
+ "adminPanel.activity.event.impersonationEnded",
2271
+ "Impersonation ended"
2272
+ );
2273
+ case "impersonation.expired":
2274
+ return appUserEvent(
2275
+ "impersonation-expired",
2276
+ "neutral",
2277
+ "expired",
2278
+ "adminPanel.activity.event.impersonationExpired",
2279
+ "Impersonation timed out"
2280
+ );
2281
+ case "impersonation.refused":
2282
+ return appUserEvent(
2283
+ "impersonation-refused",
2284
+ "danger",
2285
+ "refused",
2286
+ "adminPanel.activity.event.impersonationRefused",
2287
+ "Impersonation request refused"
2288
+ );
2289
+ default:
2290
+ if (typeof row?.event === "string" && row.event.startsWith("impersonation.")) {
2291
+ return appUserEvent(
2292
+ "impersonation",
2293
+ "warning",
2294
+ "impersonation",
2295
+ "adminPanel.activity.event.impersonation",
2296
+ "Impersonation"
2297
+ );
2298
+ }
2299
+ if (typeof row?.event === "string" && row.event.startsWith("webhook.")) {
2300
+ return appUserEvent(
2301
+ "webhook",
2302
+ "neutral",
2303
+ "webhook",
2304
+ "adminPanel.activity.event.webhook",
2305
+ "Webhook delivery"
2306
+ );
2307
+ }
2308
+ return {
2309
+ key: "other",
2310
+ tone: "neutral",
2311
+ icon: "other",
2312
+ label: message$1("adminPanel.activity.event.other", "Security event"),
2313
+ detail: null
2314
+ };
2315
+ }
2316
+ }
2317
+ function getSessionStatePresentation(session) {
2318
+ switch (session?.state) {
2319
+ case "active":
2320
+ return {
2321
+ tone: "success",
2322
+ label: message$1("adminPanel.activity.session.active", "Still signed in")
2323
+ };
2324
+ case "signed-out":
2325
+ return {
2326
+ tone: "neutral",
2327
+ label: message$1("adminPanel.activity.session.signedOut", "Signed out")
2328
+ };
2329
+ case "ended":
2330
+ return {
2331
+ tone: "neutral",
2332
+ label: message$1("adminPanel.activity.session.ended", "Session ended")
2333
+ };
2334
+ default:
2335
+ return null;
2336
+ }
2337
+ }
2338
+ const RECENT_EVENT_LIMIT = 8;
2339
+ const ACTIVITY_PAGE_SIZE_OPTIONS = Object.freeze(["10", "20", "50", "100"]);
2340
+ const EVENT_TABLE_MIN_WIDTH = Object.freeze({ withAdmin: 800, withoutAdmin: 740 });
2341
+ const EVENT_TABLE_FULL_WIDTH = 1e3;
2342
+ function getEventListLayout(width, { showAdmin = false, wide = false, minWidth } = {}) {
2343
+ if (!width) return "full";
2344
+ const min = Number.isFinite(minWidth) && minWidth > 0 ? minWidth : showAdmin || wide ? EVENT_TABLE_MIN_WIDTH.withAdmin : EVENT_TABLE_MIN_WIDTH.withoutAdmin;
2345
+ if (width < min) return "stacked";
2346
+ return width >= EVENT_TABLE_FULL_WIDTH ? "full" : "table";
2347
+ }
2348
+ function getEventPlace(row) {
2349
+ return [row?.location?.city, row?.location?.country].filter(Boolean).join(", ");
2350
+ }
2351
+ function parseActivityPageQuery(query) {
2352
+ const source = query || {};
2353
+ const event = ALL_ADMINS_FILTER_OPTIONS.includes(String(source.event)) ? String(source.event) : "all";
2354
+ const period = PERIOD_OPTIONS.includes(String(source.period)) ? String(source.period) : "30";
2355
+ const adminId = /^[1-9][0-9]{0,11}$/.test(String(source.adminId ?? "")) ? Number(source.adminId) : null;
2356
+ const page = Number.parseInt(String(source.page ?? ""), 10);
2357
+ const pageSize = String(source.pageSize ?? "");
2358
+ return {
2359
+ event,
2360
+ period,
2361
+ adminId,
2362
+ page: Number.isInteger(page) && page > 0 ? page : 1,
2363
+ pageSize: ACTIVITY_PAGE_SIZE_OPTIONS.includes(pageSize) ? Number(pageSize) : EVENT_PAGE_SIZE
2364
+ };
2365
+ }
2366
+ function hasActivityPageFilters(view) {
2367
+ return view.event !== "all" || view.period !== "30" || view.adminId !== null;
2368
+ }
2369
+ function groupChangedSettings(keys) {
2370
+ const list = Array.isArray(keys) ? keys.filter((key) => typeof key === "string" && key) : [];
2371
+ const byTab = /* @__PURE__ */ new Map();
2372
+ const unknown = [];
2373
+ const seen = /* @__PURE__ */ new Set();
2374
+ for (const key of list) {
2375
+ const tab = SETTINGS_TAB_IDS.find((id) => SETTINGS_TAB_FIELDS[id]?.includes(key));
2376
+ const entry = SETTINGS_FIELD_LABELS[key];
2377
+ if (!tab || !entry) {
2378
+ if (!seen.has(`raw:${key}`)) unknown.push({ key, label: null });
2379
+ seen.add(`raw:${key}`);
2380
+ continue;
2381
+ }
2382
+ if (seen.has(`label:${entry[0]}`)) continue;
2383
+ seen.add(`label:${entry[0]}`);
2384
+ if (!byTab.has(tab)) byTab.set(tab, []);
2385
+ byTab.get(tab).push({ key, label: message$1(entry[0], entry[1]) });
2386
+ }
2387
+ const groups = SETTINGS_TAB_IDS.filter((tab) => byTab.has(tab)).map((tab) => ({
2388
+ tab,
2389
+ label: message$1(SETTINGS_TAB_LABELS[tab][0], SETTINGS_TAB_LABELS[tab][1]),
2390
+ fields: byTab.get(tab)
2391
+ }));
2392
+ if (unknown.length) groups.push({ tab: null, label: null, fields: unknown });
2393
+ return groups;
2394
+ }
2395
+ const ACTIVITY_ACTION_LABELS = Object.freeze({
2396
+ all: message$1("adminPanel.activity.action.all", "All actions"),
2397
+ view: message$1("adminPanel.activity.action.view", "Opened"),
2398
+ create: message$1("adminPanel.activity.action.create", "Created"),
2399
+ update: message$1("adminPanel.activity.action.update", "Edited"),
2400
+ publish: message$1("adminPanel.activity.action.publish", "Published"),
2401
+ unpublish: message$1("adminPanel.activity.action.unpublish", "Unpublished"),
2402
+ discard: message$1("adminPanel.activity.action.discard", "Discarded draft"),
2403
+ delete: message$1("adminPanel.activity.action.delete", "Deleted"),
2404
+ clone: message$1("adminPanel.activity.action.clone", "Duplicated")
2405
+ });
2406
+ function getActivityTone(action) {
2407
+ if (action === "publish") return "success";
2408
+ if (action === "delete") return "warning";
2409
+ return "neutral";
2410
+ }
2411
+ function getEntryPath(row) {
2412
+ const type = row?.contentType;
2413
+ if (!type?.exists || row.action === "delete") return null;
2414
+ const uid = encodeURIComponent(type.uid);
2415
+ const locale = row.entry?.locale ? `?plugins[i18n][locale]=${encodeURIComponent(row.entry.locale)}` : "";
2416
+ if (type.kind === "single") return `/content-manager/single-types/${uid}${locale}`;
2417
+ if (!row.entry?.documentId) return null;
2418
+ return `/content-manager/collection-types/${uid}/${encodeURIComponent(row.entry.documentId)}${locale}`;
2419
+ }
2420
+ const SIGN_IN_CSV_HEADERS = Object.freeze([
2421
+ "Time",
2422
+ "Event",
2423
+ "Reason",
2424
+ "Admin",
2425
+ "Admin ID",
2426
+ "IP Address",
2427
+ "IP Anonymized",
2428
+ "Country",
2429
+ "City",
2430
+ "Browser",
2431
+ "OS",
2432
+ "Device",
2433
+ "Session",
2434
+ "Signed Out By"
2435
+ ]);
2436
+ const ACTIVITY_CSV_HEADERS = Object.freeze([
2437
+ "Time",
2438
+ "Action",
2439
+ "Admin",
2440
+ "Admin ID",
2441
+ "Content Type",
2442
+ "Content Type UID",
2443
+ "Document ID",
2444
+ "Locale",
2445
+ "Title",
2446
+ "Entries"
2447
+ ]);
2448
+ const toCsv = (headers, rows) => [headers, ...rows].map((cells) => cells.map(escapeCsvValue).join(",")).join("\n");
2449
+ function buildSignInCsv(rows) {
2450
+ return toCsv(
2451
+ SIGN_IN_CSV_HEADERS,
2452
+ rows.map((row) => [
2453
+ row.at || "",
2454
+ row.event || "",
2455
+ row.reason || row.scope || "",
2456
+ row.admin?.name || "",
2457
+ row.admin?.id ?? "",
2458
+ row.ipAddress || "",
2459
+ row.ipAnonymized ? "yes" : "no",
2460
+ row.location?.country || "",
2461
+ row.location?.city || "",
2462
+ row.browser || "",
2463
+ row.os || "",
2464
+ row.deviceType || "",
2465
+ row.session?.state || "",
2466
+ row.actor?.name || ""
2467
+ ])
2468
+ );
2469
+ }
2470
+ function buildActivityCsv(rows) {
2471
+ return toCsv(
2472
+ ACTIVITY_CSV_HEADERS,
2473
+ rows.map((row) => [
2474
+ row.at || "",
2475
+ row.action || "",
2476
+ row.admin?.name || "",
2477
+ row.admin?.id ?? "",
2478
+ row.contentType?.name || "",
2479
+ row.contentType?.uid || "",
2480
+ row.entry?.documentId || "",
2481
+ row.entry?.locale || "",
2482
+ row.entry?.title || "",
2483
+ row.entry?.count ?? ""
2484
+ ])
2485
+ );
2486
+ }
2487
+ const pluginId = "magic-sessionmanager";
2488
+ const USER_ACTIVITY_FILTER_OPTIONS = Object.freeze([
2489
+ "all",
2490
+ "failed",
2491
+ "lockouts",
2492
+ "suspicious",
2493
+ "sessions",
2494
+ "privacy",
2495
+ "impersonation"
2496
+ ]);
2497
+ const USER_ACTIVITY_FILTER_LABELS = Object.freeze({
2498
+ all: ["userActivity.filter.all", "All events"],
2499
+ failed: ["userActivity.filter.failed", "Failed and refused sign-ins"],
2500
+ lockouts: ["userActivity.filter.lockouts", "Lockouts and unlocks"],
2501
+ suspicious: [
2502
+ "userActivity.filter.suspicious",
2503
+ "New devices, impossible travel, “This wasn’t me”"
2504
+ ],
2505
+ sessions: ["userActivity.filter.sessions", "Session limit and password change"],
2506
+ privacy: ["userActivity.filter.privacy", "Personal data exports"],
2507
+ impersonation: ["userActivity.filter.impersonation", "Impersonation"]
2508
+ });
2509
+ const USER_ACTIVITY_API_PATH = `/${pluginId}/user-activity`;
2510
+ const USER_ACTIVITY_PAGE_PATH = `/plugins/${pluginId}/app-users/activity`;
2511
+ const USER_ACTIVITY_SETTINGS_PATH = `/settings/${pluginId}/general?tab=login-protection`;
2512
+ const RECENT_USER_EVENT_LIMIT = 8;
2513
+ const PANEL_USER_EVENT_LIMIT = 3;
2514
+ const USER_UID = "plugin::users-permissions.user";
2515
+ const DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
2516
+ function userActivityPagePath(userId) {
2517
+ return typeof userId === "string" && DOCUMENT_ID.test(userId) ? `${USER_ACTIVITY_PAGE_PATH}?userId=${encodeURIComponent(userId)}` : USER_ACTIVITY_PAGE_PATH;
2518
+ }
2519
+ function getUserEntryPath(user) {
2520
+ if (!user || typeof user.documentId !== "string" || !DOCUMENT_ID.test(user.documentId)) {
2521
+ return null;
2522
+ }
2523
+ return `/content-manager/collection-types/${USER_UID}/${encodeURIComponent(user.documentId)}`;
2524
+ }
2525
+ function buildUserActivityParams(filters, now) {
2526
+ const params = {
2527
+ page: filters.page || 1,
2528
+ pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2529
+ event: USER_ACTIVITY_FILTER_OPTIONS.includes(filters.event) ? filters.event : "all"
2530
+ };
2531
+ if (typeof filters.userId === "string" && DOCUMENT_ID.test(filters.userId)) {
2532
+ params.userId = filters.userId;
2533
+ }
2534
+ const from = periodStart(filters.period || "all", now);
2535
+ if (from) params.from = from;
2536
+ return params;
2537
+ }
2538
+ function parseUserActivityQuery(query) {
2539
+ const source = query || {};
2540
+ const event = USER_ACTIVITY_FILTER_OPTIONS.includes(String(source.event)) ? String(source.event) : "all";
2541
+ const period = PERIOD_OPTIONS.includes(String(source.period)) ? String(source.period) : "30";
2542
+ const userId = DOCUMENT_ID.test(String(source.userId ?? "")) ? String(source.userId) : null;
2543
+ const page = Number.parseInt(String(source.page ?? ""), 10);
2544
+ const pageSize = String(source.pageSize ?? "");
2545
+ return {
2546
+ event,
2547
+ period,
2548
+ userId,
2549
+ page: Number.isInteger(page) && page > 0 ? page : 1,
2550
+ pageSize: ACTIVITY_PAGE_SIZE_OPTIONS.includes(pageSize) ? Number(pageSize) : EVENT_PAGE_SIZE
2551
+ };
2552
+ }
2553
+ function hasUserActivityFilters(view) {
2554
+ return view.event !== "all" || view.period !== "30" || view.userId !== null;
2555
+ }
2556
+ const message = (messageId, defaultMessage, values) => ({
2557
+ messageId,
2558
+ defaultMessage,
2559
+ ...values ? { values } : {}
2560
+ });
2561
+ const REFUSAL_REASONS = Object.freeze({
2562
+ lockout: message("userActivity.detail.refused.lockout", "The account or IP address was locked"),
2563
+ "too-many-attempts": message(
2564
+ "userActivity.detail.refused.tooMany",
2565
+ "Too many sign-ins at the same time"
2566
+ ),
2567
+ country: message("userActivity.detail.refused.country", "Sign-ins from this country are blocked"),
2568
+ risk: message("userActivity.detail.refused.risk", "Risky address (VPN, proxy or Tor)"),
2569
+ "location-unavailable": message(
2570
+ "userActivity.detail.refused.location",
2571
+ "The location could not be checked"
2572
+ )
2573
+ });
2574
+ const IMPERSONATION_REFUSALS = Object.freeze({
2575
+ disabled: message("userActivity.detail.impersonation.disabled", "Impersonation is turned off"),
2576
+ blocked: message("userActivity.detail.impersonation.blocked", "The account is blocked"),
2577
+ "already-active": message(
2578
+ "userActivity.detail.impersonation.alreadyActive",
2579
+ "Someone is already impersonating this user"
2580
+ ),
2581
+ "api-token": message(
2582
+ "userActivity.detail.impersonation.apiToken",
2583
+ "Admin API tokens cannot impersonate"
2584
+ ),
2585
+ "call-credentials": message(
2586
+ "userActivity.detail.impersonation.callCredentials",
2587
+ "A sign-in, password or email request was blocked"
2588
+ ),
2589
+ "call-account": message(
2590
+ "userActivity.detail.impersonation.callAccount",
2591
+ "A data export or “This wasn’t me” request was blocked"
2592
+ ),
2593
+ "call-sessions": message(
2594
+ "userActivity.detail.impersonation.callSessions",
2595
+ "A request to end sessions was blocked"
2596
+ )
2597
+ });
2598
+ const UNKNOWN_ACCOUNT = message(
2599
+ "userActivity.detail.unknownAccount",
2600
+ "No account with this email or username"
2601
+ );
2602
+ function getUserEventDetail(row) {
2603
+ const d = row?.details || {};
2604
+ const parts = [];
2605
+ switch (row?.event) {
2606
+ case "user.sign-in.failed":
2607
+ if (d.unknownAccount) parts.push(UNKNOWN_ACCOUNT);
2608
+ break;
2609
+ case "user.sign-in.refused":
2610
+ if (d.reason === "session-limit") {
2611
+ parts.push(
2612
+ Number.isInteger(d.limit) ? message(
2613
+ "userActivity.detail.refused.limit",
2614
+ "Session limit of {limit, number} reached",
2615
+ { limit: d.limit }
2616
+ ) : message("userActivity.detail.refused.limitReached", "Session limit reached")
2617
+ );
2618
+ } else if (REFUSAL_REASONS[d.reason]) parts.push(REFUSAL_REASONS[d.reason]);
2619
+ if (d.unknownAccount) parts.push(UNKNOWN_ACCOUNT);
2620
+ break;
2621
+ case "user.lockout":
2622
+ if (Number.isInteger(d.minutes) && Number.isInteger(d.failures)) {
2623
+ parts.push(
2624
+ d.kind === "ip" ? message(
2625
+ "userActivity.detail.lockout.ip",
2626
+ "IP address locked for {minutes, plural, one {# minute} other {# minutes}} after {failures, plural, one {# failed sign-in} other {# failed sign-ins}}",
2627
+ { minutes: d.minutes, failures: d.failures }
2628
+ ) : message(
2629
+ "userActivity.detail.lockout.account",
2630
+ "Account locked for {minutes, plural, one {# minute} other {# minutes}} after {failures, plural, one {# failed sign-in} other {# failed sign-ins}}",
2631
+ { minutes: d.minutes, failures: d.failures }
2632
+ )
2633
+ );
2634
+ }
2635
+ break;
2636
+ case "user.lockout.lifted":
2637
+ parts.push(
2638
+ d.kind === "ip" ? message("userActivity.detail.unlock.ip", "An admin unlocked an IP address") : message("userActivity.detail.unlock.account", "An admin unlocked the account")
2639
+ );
2640
+ break;
2641
+ case "user.session.limit":
2642
+ if (Number.isInteger(d.ended)) {
2643
+ parts.push(
2644
+ Number.isInteger(d.limit) ? message(
2645
+ "userActivity.detail.limit.ended",
2646
+ "{ended, plural, one {# older session} other {# older sessions}} ended to stay within {limit, number}",
2647
+ { ended: d.ended, limit: d.limit }
2648
+ ) : message(
2649
+ "userActivity.detail.limit.endedOnly",
2650
+ "{ended, plural, one {# older session} other {# older sessions}} ended",
2651
+ { ended: d.ended }
2652
+ )
2653
+ );
2654
+ }
2655
+ break;
2656
+ case "user.password-change.ended-others":
2657
+ if (Number.isInteger(d.ended)) {
2658
+ parts.push(
2659
+ message(
2660
+ "userActivity.detail.password.ended",
2661
+ "{ended, plural, =0 {No other session was open} one {# other session ended} other {# other sessions ended}}",
2662
+ { ended: d.ended }
2663
+ )
2664
+ );
2665
+ }
2666
+ break;
2667
+ case "user.sign-in.impossible-travel":
2668
+ if (Number.isInteger(d.distanceKm) && Number.isInteger(d.speedKmh)) {
2669
+ parts.push(
2670
+ message(
2671
+ "userActivity.detail.travel.distance",
2672
+ "{distance, number} km from the last sign-in, {speed, number} km/h",
2673
+ { distance: d.distanceKm, speed: d.speedKmh }
2674
+ )
2675
+ );
2676
+ }
2677
+ if (d.from && d.to) {
2678
+ parts.push(
2679
+ message("userActivity.detail.travel.countries", "{from} to {to}", {
2680
+ from: d.from,
2681
+ to: d.to
2682
+ })
2683
+ );
2684
+ }
2685
+ if (d.action === "reauthenticate") {
2686
+ parts.push(
2687
+ message(
2688
+ "userActivity.detail.travel.reauthenticate",
2689
+ "All sessions ended, a new sign-in was required"
2690
+ )
2691
+ );
2692
+ }
2693
+ break;
2694
+ case "user.not-me":
2695
+ parts.push(
2696
+ d.scope === "all" ? message("userActivity.detail.notMe.all", "The user ended all their sessions") : message("userActivity.detail.notMe.session", "The user ended that session")
2697
+ );
2698
+ break;
2699
+ case "user.data.exported":
2700
+ if (Number.isInteger(d.sessions) && Number.isInteger(d.events)) {
2701
+ parts.push(
2702
+ message(
2703
+ "userActivity.detail.export.counts",
2704
+ "The user downloaded {count, plural, one {# session} other {# sessions}} and {events, plural, one {# security event} other {# security events}}",
2705
+ { count: d.sessions, events: d.events }
2706
+ )
2707
+ );
2708
+ }
2709
+ break;
2710
+ case "impersonation.started":
2711
+ if (Number.isInteger(d.durationMinutes)) {
2712
+ parts.push(
2713
+ message(
2714
+ "userActivity.detail.impersonation.duration",
2715
+ "For {minutes, plural, one {# minute} other {# minutes}}",
2716
+ { minutes: d.durationMinutes }
2717
+ )
2718
+ );
2719
+ }
2720
+ break;
2721
+ case "impersonation.ended":
2722
+ if (d.endReason === "disabled") {
2723
+ parts.push(
2724
+ message(
2725
+ "userActivity.detail.impersonation.endedDisabled",
2726
+ "Ended because impersonation was turned off"
2727
+ )
2728
+ );
2729
+ } else if (d.endReason === "failed") {
2730
+ parts.push(
2731
+ message("userActivity.detail.impersonation.endedFailed", "Could not be completed")
2732
+ );
2733
+ } else {
2734
+ parts.push(message("userActivity.detail.impersonation.endedByAdmin", "Ended by an admin"));
2735
+ }
2736
+ break;
2737
+ case "impersonation.expired":
2738
+ parts.push(message("userActivity.detail.impersonation.expired", "The time ran out"));
2739
+ break;
2740
+ case "impersonation.refused":
2741
+ if (IMPERSONATION_REFUSALS[d.refusal]) parts.push(IMPERSONATION_REFUSALS[d.refusal]);
2742
+ break;
2743
+ }
2744
+ return parts;
2745
+ }
2746
+ const USER_ACTIVITY_CSV_HEADERS = Object.freeze([
2747
+ "Time",
2748
+ "Event",
2749
+ "Reason",
2750
+ "User",
2751
+ "User ID",
2752
+ "User Document ID",
2753
+ "IP Address",
2754
+ "IP Anonymized",
2755
+ "Country",
2756
+ "City",
2757
+ "Browser",
2758
+ "OS",
2759
+ "Device",
2760
+ "Done By",
2761
+ "Done By Admin ID"
2762
+ ]);
2763
+ function buildUserActivityCsv(rows) {
2764
+ const lines = rows.map((row) => {
2765
+ const d = row.details || {};
2766
+ return [
2767
+ row.at || "",
2768
+ row.event || "",
2769
+ d.reason || d.refusal || d.endReason || d.kind || d.scope || "",
2770
+ row.user?.email || row.user?.username || "",
2771
+ row.user?.id ?? "",
2772
+ row.user?.documentId || "",
2773
+ row.ipAddress || "",
2774
+ row.ipAnonymized ? "yes" : "no",
2775
+ row.location?.country || "",
2776
+ row.location?.city || "",
2777
+ row.browser || "",
2778
+ row.os || "",
2779
+ row.deviceType || "",
2780
+ row.actor?.type === "system" ? "system" : row.actor?.name || "",
2781
+ row.actor?.type === "admin" ? row.actor.id ?? "" : ""
2782
+ ];
2783
+ });
2784
+ return [USER_ACTIVITY_CSV_HEADERS, ...lines].map((cells) => cells.map(escapeCsvValue).join(",")).join("\n");
2785
+ }
2786
+ const settingsGroupText = (t, group) => {
2787
+ const fields = group.fields.map(
2788
+ (field) => field.label ? t(field.label.messageId, field.label.defaultMessage) : field.key
2789
+ ).join(", ");
2790
+ return group.label ? t("adminPanel.activity.settingsGroup", "{tab}: {fields}", {
2791
+ tab: t(group.label.messageId, group.label.defaultMessage),
2792
+ fields
2793
+ }) : fields;
2794
+ };
2795
+ const changedSettingsText = (t, keys, { limit } = {}) => {
2796
+ const groups = groupChangedSettings(keys);
2797
+ const total = groups.reduce((sum, group) => sum + group.fields.length, 0);
2798
+ if (!total) return "";
2799
+ let budget = limit && limit > 0 ? limit : total;
2800
+ const shown = [];
2801
+ for (const group of groups) {
2802
+ if (budget <= 0) break;
2803
+ shown.push({ ...group, fields: group.fields.slice(0, budget) });
2804
+ budget -= Math.min(budget, group.fields.length);
2805
+ }
2806
+ const named = shown.reduce((sum, group) => sum + group.fields.length, 0);
2807
+ const text = shown.map((group) => settingsGroupText(t, group)).join(" · ");
2808
+ return named < total ? t("adminPanel.activity.settingsMore", "{names} and {count, number} more", {
2809
+ names: text,
2810
+ count: total - named
2811
+ }) : text;
2812
+ };
2813
+ const changedSettingsLines = (t, keys) => groupChangedSettings(keys).map((group) => settingsGroupText(t, group));
2814
+ const noAdminText = (t, row) => row?.event === "security-log.retention.purged" ? t("adminPanel.activity.system", "System") : t("adminPanel.activity.unknownAccount", "Unknown account");
2815
+ const deviceText = (t, row) => {
2816
+ if (row.browser && row.os) {
2817
+ return t("adminPanel.activity.browserOnOs", "{browser} on {os}", {
2818
+ browser: row.browser,
2819
+ os: row.os
2820
+ });
2821
+ }
2822
+ return row.browser || row.os || "";
2823
+ };
2824
+ const ipText = (t, row) => {
2825
+ if (!row.ipAddress) return "";
2826
+ return row.ipAnonymized ? t("adminPanel.activity.ipAnonymized", "{ip} (anonymised)", { ip: row.ipAddress }) : row.ipAddress;
2827
+ };
2828
+ const eventDetailText = (t, row, presentation, withActor) => {
2829
+ const parts = [];
2830
+ if (presentation.detail) {
2831
+ parts.push(t(presentation.detail.messageId, presentation.detail.defaultMessage));
2832
+ }
2833
+ if (Number.isInteger(row.attempts) && row.attempts > 1) {
2834
+ parts.push(
2835
+ t(
2836
+ "adminPanel.activity.attempts",
2837
+ "{count, plural, one {# attempt} other {# attempts}} within 5 minutes",
2838
+ { count: row.attempts }
2839
+ )
2840
+ );
2841
+ }
2842
+ const changed = changedSettingsText(t, row.change?.keys, { limit: 3 });
2843
+ if (changed) parts.push(changed);
2844
+ if (Number.isInteger(row.purge?.count)) {
2845
+ parts.push(
2846
+ Number.isInteger(row.purge?.retentionDays) ? t(
2847
+ "adminPanel.activity.purgedDetail",
2848
+ "{count, plural, one {# event} other {# events}}, older than {days, plural, one {# day} other {# days}}",
2849
+ { count: row.purge.count, days: row.purge.retentionDays }
2850
+ ) : t("adminPanel.activity.purgedCount", "{count, plural, one {# event} other {# events}}", {
2851
+ count: row.purge.count
2852
+ })
2853
+ );
2854
+ }
2855
+ if (withActor && row.actor?.name) {
2856
+ parts.push(t("adminPanel.activity.byAdmin", "by {name}", { name: row.actor.name }));
2857
+ }
2858
+ return parts.join(" · ");
2859
+ };
2860
+ const contentTypeText = (row) => [row.contentType?.name, row.entry?.locale].filter(Boolean).join(" · ");
2861
+ const userEventDetailText = (t, row, withActor = false) => {
2862
+ const parts = getUserEventDetail(row).map(
2863
+ (part) => t(part.messageId, part.defaultMessage, part.values)
2864
+ );
2865
+ if (withActor && row?.actor?.type === "admin" && row.actor.name) {
2866
+ parts.push(t("adminPanel.activity.byAdmin", "by {name}", { name: row.actor.name }));
2867
+ }
2868
+ return parts.join(" · ");
2869
+ };
2870
+ const userText = (t, row) => {
2871
+ const user = row?.user;
2872
+ if (user) {
2873
+ return user.email || user.username || t("userActivity.identity.placeholder", "User #{id}", { id: user.id });
2874
+ }
2875
+ if (row?.target === "ip") return t("userActivity.identity.ipLock", "IP address");
2876
+ return t("adminPanel.activity.unknownAccount", "Unknown account");
2877
+ };
2878
+ const doneByText = (t, row) => {
2879
+ if (row?.actor?.type === "system") return t("userActivity.doneBy.system", "Automatic");
2880
+ if (row?.actor?.type === "admin") {
2881
+ return row.actor.name || t("adminPanel.identity.placeholder", "Admin #{id}", { id: row.actor.id ?? "?" });
2882
+ }
2883
+ return "";
2884
+ };
2885
+ const useT = () => {
2886
+ const { formatMessage } = reactIntl.useIntl();
2887
+ return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2888
+ };
2889
+ const SHORT_DATE = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
2890
+ const FULL_DATE = Object.freeze({ dateStyle: "full", timeStyle: "medium" });
2891
+ const EVENT_ICONS = Object.freeze({
2892
+ signIn: icons.CheckCircle,
2893
+ failed: icons.CrossCircle,
2894
+ lockout: icons.Lock,
2895
+ signOut: icons.SignOut,
2896
+ revoked: icons.Shield,
2897
+ settings: icons.Cog,
2898
+ logRead: icons.Key,
2899
+ purged: icons.Trash,
2900
+ refused: icons.CrossCircle,
2901
+ unlock: icons.Lock,
2902
+ limit: icons.Stack,
2903
+ password: icons.Key,
2904
+ device: icons.Monitor,
2905
+ travel: icons.Earth,
2906
+ notMe: icons.WarningCircle,
2907
+ export: icons.Download,
2908
+ impersonation: icons.User,
2909
+ impersonationEnd: icons.Stop,
2910
+ expired: icons.Clock,
2911
+ webhook: icons.Webhooks,
2912
+ other: icons.Information
2913
+ });
2914
+ const ICON_FILL = Object.freeze({
2915
+ success: "success600",
2916
+ danger: "danger600",
2917
+ warning: "warning700",
2918
+ secondary: "secondary600",
2919
+ neutral: "neutral600"
2920
+ });
2921
+ const stopCellKeys = (event) => {
2922
+ if (event.key === "Enter" || event.key === " " || event.key === "Spacebar") {
2923
+ event.stopPropagation();
2924
+ }
2925
+ };
2926
+ const ClickableRow = styled__default.default(designSystem.Tr)`
2927
+ cursor: pointer;
2928
+ `;
2929
+ const WrapCell = styled__default.default(designSystem.Td)`
2930
+ white-space: normal;
2931
+ `;
2932
+ const NoWrap = styled__default.default.span`
2933
+ white-space: nowrap;
2934
+ `;
2935
+ const NameButton = styled__default.default(designSystem.TextButton)`
2936
+ min-height: 3.2rem;
2937
+ text-align: start;
2938
+ `;
2939
+ const StackedList = styled__default.default.ul`
2940
+ margin: 0;
2941
+ padding: 0;
2942
+ list-style: none;
2943
+ border: 1px solid ${({ theme }) => theme.colors.neutral150};
2944
+ border-radius: ${({ theme }) => theme.borderRadius};
2945
+ background: ${({ theme }) => theme.colors.neutral0};
2946
+ min-width: 0;
2947
+
2948
+ & > li + li {
2949
+ border-top: 1px solid ${({ theme }) => theme.colors.neutral150};
2950
+ }
2951
+ `;
2952
+ const StackedItem = styled__default.default.li`
2953
+ cursor: pointer;
2954
+ min-width: 0;
2955
+ `;
2956
+ const BreakAnywhere = styled__default.default(designSystem.Typography)`
2957
+ overflow-wrap: anywhere;
2958
+ `;
2959
+ const getEventBadgeColors = (tone) => tone === "danger" ? { backgroundColor: "danger100", textColor: "danger700" } : getBadgeColors(tone);
2960
+ const EventBadge = ({ presentation, nowrap = false }) => {
2961
+ const t = useT();
2962
+ const Icon = EVENT_ICONS[presentation.icon] || icons.Information;
2963
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", shrink: 0, "data-event-kind": presentation.key, children: [
2964
+ /* @__PURE__ */ jsxRuntime.jsx(
2965
+ Icon,
2966
+ {
2967
+ "aria-hidden": "true",
2968
+ focusable: "false",
2969
+ width: "1.6rem",
2970
+ height: "1.6rem",
2971
+ fill: ICON_FILL[presentation.tone] || ICON_FILL.neutral
2972
+ }
2973
+ ),
2974
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { ...getEventBadgeColors(presentation.tone), "data-event-tone": presentation.tone, children: nowrap ? /* @__PURE__ */ jsxRuntime.jsx(NoWrap, { children: t(presentation.label.messageId, presentation.label.defaultMessage) }) : t(presentation.label.messageId, presentation.label.defaultMessage) })
2975
+ ] });
2976
+ };
2977
+ const EventTime = ({ value, compact = false }) => {
2978
+ const { formatDate, formatRelativeTime } = useSessionFormatters();
2979
+ const date = toValidDate(value);
2980
+ if (!date) return /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "omega" });
2981
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
2982
+ /* @__PURE__ */ jsxRuntime.jsx(
2983
+ designSystem.Typography,
2984
+ {
2985
+ tag: "time",
2986
+ dateTime: date.toISOString(),
2987
+ variant: compact ? "pi" : "omega",
2988
+ textColor: "neutral800",
2989
+ children: /* @__PURE__ */ jsxRuntime.jsx(NoWrap, { children: formatRelativeTime(date) })
2990
+ }
2991
+ ),
2992
+ compact ? null : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: /* @__PURE__ */ jsxRuntime.jsx(NoWrap, { children: formatDate(date, SHORT_DATE) }) })
2993
+ ] });
2994
+ };
2995
+ const AdminName = ({ admin, row, onOpenAdmin }) => {
2996
+ const t = useT();
2997
+ if (!admin) {
2998
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: onOpenAdmin ? "pi" : "omega", textColor: "neutral600", children: noAdminText(t, row) });
2999
+ }
3000
+ if (!onOpenAdmin) {
3001
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: admin.name });
3002
+ }
3003
+ return /* @__PURE__ */ jsxRuntime.jsx(
3004
+ NameButton,
3005
+ {
3006
+ onClick: (event) => {
3007
+ event.stopPropagation();
3008
+ onOpenAdmin(admin, event.currentTarget);
3009
+ },
3010
+ onKeyDown: stopCellKeys,
3011
+ "aria-label": t("adminPanel.activity.openAdmin", "Open the details of {name}", {
3012
+ name: admin.name
3013
+ }),
3014
+ children: admin.name
3015
+ }
3016
+ );
3017
+ };
3018
+ const SignInDetails = ({ row }) => {
3019
+ const t = useT();
3020
+ const ip = ipText(t, row);
3021
+ const second = [getEventPlace(row), deviceText(t, row)].filter(Boolean).join(" · ");
3022
+ if (!ip && !second) return /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "omega" });
3023
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3024
+ ip ? /* @__PURE__ */ jsxRuntime.jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: ip }) : null,
3025
+ second ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3026
+ ] });
3027
+ };
3028
+ const SessionState = ({ row }) => {
3029
+ const t = useT();
3030
+ const { formatRelativeTime } = useSessionFormatters();
3031
+ const state = getSessionStatePresentation(row.session);
3032
+ if (!state) return /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "omega" });
3033
+ const endedAt = toValidDate(row.session?.endedAt);
3034
+ const second = [
3035
+ endedAt ? formatRelativeTime(endedAt) : "",
3036
+ row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3037
+ ].filter(Boolean).join(" · ");
3038
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3039
+ /* @__PURE__ */ jsxRuntime.jsx(
3040
+ designSystem.Typography,
3041
+ {
3042
+ variant: "omega",
3043
+ fontWeight: state.tone === "success" ? "semiBold" : void 0,
3044
+ textColor: state.tone === "success" ? "success600" : "neutral800",
3045
+ "data-session-state": row.session?.state,
3046
+ children: t(state.label.messageId, state.label.defaultMessage)
3047
+ }
3048
+ ),
3049
+ second ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3050
+ ] });
3051
+ };
3052
+ const HeaderCell = ({ children, hidden = false, ...rest }) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { ...rest, children: hidden ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { children }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children }) });
3053
+ const DetailsButton = ({ label, onOpen }) => /* @__PURE__ */ jsxRuntime.jsx(
3054
+ designSystem.IconButton,
3055
+ {
3056
+ variant: "ghost",
3057
+ label,
3058
+ withTooltip: false,
3059
+ onClick: (event) => {
3060
+ event.stopPropagation();
3061
+ onOpen(event.currentTarget);
3062
+ },
3063
+ onKeyDown: stopCellKeys,
3064
+ "data-event-details": "",
3065
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Eye, {})
3066
+ }
3067
+ );
3068
+ const ActivityEntry = ({ row }) => {
3069
+ const t = useT();
3070
+ const path = getEntryPath(row);
3071
+ const name2 = row.entry?.count !== null && row.entry?.count !== void 0 ? t("adminPanel.activity.entries", "{count, plural, one {# entry} other {# entries}}", {
3072
+ count: row.entry.count
3073
+ }) : row.entry?.title || row.entry?.documentId || row.contentType?.name || "";
3074
+ if (!name2) return /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "omega" });
3075
+ if (!path) {
3076
+ return /* @__PURE__ */ jsxRuntime.jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: name2 });
3077
+ }
3078
+ return /* @__PURE__ */ jsxRuntime.jsx(
3079
+ TargetLink,
3080
+ {
3081
+ tag: reactRouterDom.Link,
3082
+ to: path,
3083
+ onClick: (event) => event.stopPropagation(),
3084
+ onKeyDown: stopCellKeys,
3085
+ "aria-label": t("adminPanel.activity.openEntry", "Open {entry} in the Content Manager", {
3086
+ entry: name2
3087
+ }),
3088
+ children: name2
3089
+ }
3090
+ );
3091
+ };
3092
+ const EventDetailsModal = ({ title, items, footerAction, onClose, onCloseAutoFocus }) => {
3093
+ const t = useT();
3094
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open: true, onOpenChange: (open) => open ? null : onClose(), children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
3095
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: title }) }),
3096
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { background: "neutral100", hasRadius: true, padding: { initial: 4, medium: 6 }, children: /* @__PURE__ */ jsxRuntime.jsx(PropertyList, { columns: 2, items }) }) }),
3097
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Footer, { children: [
3098
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: t("common.close", "Close") }) }),
3099
+ footerAction || null
3100
+ ] })
3101
+ ] }) });
3102
+ };
3103
+ const useEventDetails = () => {
3104
+ const [selected, setSelected] = react.useState(null);
3105
+ const [opener, setOpener] = react.useState(null);
3106
+ const [container, setContainer] = react.useState(null);
3107
+ return {
3108
+ selected,
3109
+ setContainer,
3110
+ open: (row, trigger) => {
3111
+ const button = trigger?.matches?.("[data-event-details]") ? trigger : trigger?.querySelector?.("[data-event-details]");
3112
+ setOpener(button || null);
3113
+ setSelected(row);
3114
+ },
3115
+ close: () => setSelected(null),
3116
+ onCloseAutoFocus: (event) => restoreDialogFocus(event, opener, container)
3117
+ };
3118
+ };
3119
+ const signInDetails = (t, formatDate, row) => {
3120
+ const presentation = getEventPresentation(row);
3121
+ const label = t(presentation.label.messageId, presentation.label.defaultMessage);
3122
+ const state = getSessionStatePresentation(row.session);
3123
+ const revoked = presentation.key === "revoked";
3124
+ const adminName = row.admin?.name || noAdminText(t, row);
3125
+ const items = [
3126
+ {
3127
+ id: "event",
3128
+ label: t("adminPanel.activity.column.event", "Event"),
3129
+ render: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
3130
+ /* @__PURE__ */ jsxRuntime.jsx(EventBadge, { presentation }),
3131
+ presentation.detail ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t(presentation.detail.messageId, presentation.detail.defaultMessage) }) : null
3132
+ ] })
3133
+ },
3134
+ {
3135
+ id: "time",
3136
+ label: t("adminPanel.activity.details.exactTime", "Exact time"),
3137
+ value: row.at ? formatDate(row.at, FULL_DATE) : null
3138
+ },
3139
+ { id: "admin", label: t("adminPanel.activity.column.admin", "Admin"), value: adminName }
3140
+ ];
3141
+ if (revoked) {
3142
+ items.push(
3143
+ {
3144
+ id: "actor",
3145
+ label: t("adminPanel.activity.column.doneBy", "Done by"),
3146
+ value: row.actor?.name || null
3147
+ },
3148
+ {
3149
+ id: "scope",
3150
+ label: t("adminPanel.activity.details.signedOutOf", "Signed out of"),
3151
+ value: Number.isInteger(row.sessionsEnded) && row.sessionsEnded >= 0 ? t(
3152
+ "adminPanel.activity.details.scopeCount",
3153
+ "{scope} ({count, plural, =0 {no open session} one {# session ended} other {# sessions ended}})",
3154
+ {
3155
+ scope: t(presentation.detail.messageId, presentation.detail.defaultMessage),
3156
+ count: row.sessionsEnded
3157
+ }
3158
+ ) : t(presentation.detail.messageId, presentation.detail.defaultMessage)
3159
+ }
3160
+ );
3161
+ }
3162
+ if (state) {
3163
+ const endedAt = toValidDate(row.session?.endedAt);
3164
+ items.push({
3165
+ id: "session",
3166
+ label: t("adminPanel.activity.column.session", "Session"),
3167
+ value: [
3168
+ t(state.label.messageId, state.label.defaultMessage),
3169
+ endedAt ? formatDate(endedAt, SHORT_DATE) : "",
3170
+ row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3171
+ ].filter(Boolean).join(" · ")
3172
+ });
3173
+ }
3174
+ if (row.change) {
3175
+ const lines = changedSettingsLines(t, row.change.keys);
3176
+ items.push({
3177
+ id: "settings",
3178
+ label: t("adminPanel.activity.details.changedSettings", "Changed settings"),
3179
+ ...lines.length ? {
3180
+ render: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-changed-settings": "", children: lines.map((line) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral800", children: line }, line)) })
3181
+ } : { value: null },
3182
+ fullWidth: true
3183
+ });
3184
+ }
3185
+ if (row.purge) {
3186
+ items.push(
3187
+ {
3188
+ id: "purged",
3189
+ label: t("adminPanel.activity.details.deleted", "Deleted events"),
3190
+ value: Number.isInteger(row.purge.count) ? row.purge.count : null
3191
+ },
3192
+ {
3193
+ id: "retention",
3194
+ label: t("adminPanel.activity.details.retention", "Kept for"),
3195
+ value: Number.isInteger(row.purge.retentionDays) ? t("adminPanel.duration.days", "{count, plural, one {# day} other {# days}}", {
3196
+ count: row.purge.retentionDays
3197
+ }) : null
3198
+ }
3199
+ );
3200
+ }
3201
+ if (Number.isInteger(row.attempts) && row.attempts > 1) {
3202
+ items.push({
3203
+ id: "attempts",
3204
+ label: t("adminPanel.activity.details.attempts", "Attempts"),
3205
+ value: row.attempts
3206
+ });
3207
+ }
3208
+ items.push(
3209
+ {
3210
+ id: "ip",
3211
+ label: t("adminPanel.activity.details.ip", "IP address"),
3212
+ value: ipText(t, row) || null,
3213
+ kind: "id"
3214
+ },
3215
+ {
3216
+ id: "place",
3217
+ label: t("adminPanel.activity.details.location", "Location"),
3218
+ value: getEventPlace(row) || null
3219
+ },
3220
+ {
3221
+ id: "browser",
3222
+ label: t("adminPanel.activity.details.browser", "Browser"),
3223
+ value: row.browser || null
3224
+ },
3225
+ {
3226
+ id: "os",
3227
+ label: t("adminPanel.activity.details.os", "Operating system"),
3228
+ value: row.os || null
3229
+ },
3230
+ {
3231
+ id: "userAgent",
3232
+ label: t("adminPanel.activity.details.userAgent", "User agent"),
3233
+ value: row.userAgent || null,
3234
+ kind: "id",
3235
+ fullWidth: true
3236
+ },
3237
+ {
3238
+ id: "eventId",
3239
+ label: t("adminPanel.activity.details.eventId", "Event ID"),
3240
+ value: row.id,
3241
+ kind: "id"
3242
+ }
3243
+ );
3244
+ const title = row.admin?.name ? t("adminPanel.activity.details.title", "{event}: {name}", { event: label, name: adminName }) : label;
3245
+ const logEvent = ["settings", "log-read", "purged"].includes(presentation.key);
3246
+ const deviceFields = /* @__PURE__ */ new Set(["ip", "place", "browser", "os", "userAgent"]);
3247
+ return {
3248
+ title,
3249
+ items: logEvent ? items.filter(
3250
+ (item) => !deviceFields.has(item.id) || item.value !== null && item.value !== ""
3251
+ ) : items
3252
+ };
3253
+ };
3254
+ const activityDetails = (t, formatDate, row) => {
3255
+ const label = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3256
+ const action = t(label.messageId, label.defaultMessage);
3257
+ return {
3258
+ title: row.entry?.title ? t("adminPanel.activity.details.title", "{event}: {name}", {
3259
+ event: action,
3260
+ name: row.entry.title
3261
+ }) : action,
3262
+ items: [
3263
+ {
3264
+ id: "action",
3265
+ label: t("adminPanel.activity.column.action", "Action"),
3266
+ render: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { ...getBadgeColors(getActivityTone(row.action)), children: action })
3267
+ },
3268
+ {
3269
+ id: "time",
3270
+ label: t("adminPanel.activity.details.exactTime", "Exact time"),
3271
+ value: row.at ? formatDate(row.at, FULL_DATE) : null
3272
+ },
3273
+ {
3274
+ id: "entry",
3275
+ label: t("adminPanel.activity.column.entry", "Entry"),
3276
+ render: /* @__PURE__ */ jsxRuntime.jsx(ActivityEntry, { row })
3277
+ },
3278
+ {
3279
+ id: "admin",
3280
+ label: t("adminPanel.activity.column.admin", "Admin"),
3281
+ value: row.admin?.name || null
3282
+ },
3283
+ {
3284
+ id: "type",
3285
+ label: t("adminPanel.activity.column.contentType", "Content type"),
3286
+ value: row.contentType?.name || null
3287
+ },
3288
+ {
3289
+ id: "uid",
3290
+ label: t("adminPanel.activity.details.uid", "Content type UID"),
3291
+ value: row.contentType?.uid || null,
3292
+ kind: "id"
3293
+ },
3294
+ {
3295
+ id: "documentId",
3296
+ label: t("adminPanel.activity.details.documentId", "Document ID"),
3297
+ value: row.entry?.documentId || null,
3298
+ kind: "id"
3299
+ },
3300
+ {
3301
+ id: "locale",
3302
+ label: t("adminPanel.activity.details.locale", "Locale"),
3303
+ value: row.entry?.locale || null
3304
+ },
3305
+ {
3306
+ id: "eventId",
3307
+ label: t("adminPanel.activity.details.eventId", "Event ID"),
3308
+ value: row.id,
3309
+ kind: "id"
3310
+ }
3311
+ ]
3312
+ };
3313
+ };
3314
+ const userEventDetails = (t, formatDate, row) => {
3315
+ const presentation = getEventPresentation(row);
3316
+ const label = t(presentation.label.messageId, presentation.label.defaultMessage);
3317
+ const lines = getUserEventDetail(row).map(
3318
+ (part) => t(part.messageId, part.defaultMessage, part.values)
3319
+ );
3320
+ const who = userText(t, row);
3321
+ const doneBy = doneByText(t, row);
3322
+ const items = [
3323
+ {
3324
+ id: "event",
3325
+ label: t("adminPanel.activity.column.event", "Event"),
3326
+ render: /* @__PURE__ */ jsxRuntime.jsx(EventBadge, { presentation })
3327
+ },
3328
+ {
3329
+ id: "time",
3330
+ label: t("adminPanel.activity.details.exactTime", "Exact time"),
3331
+ value: row.at ? formatDate(row.at, FULL_DATE) : null
3332
+ },
3333
+ // Only events with facts get "What happened"; a dash there would say nothing.
3334
+ ...lines.length ? [
3335
+ {
3336
+ id: "what",
3337
+ label: t("userActivity.details.what", "What happened"),
3338
+ render: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-event-facts": "", children: lines.map((line) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral800", children: line }, line)) }),
3339
+ fullWidth: true
3340
+ }
3341
+ ] : [],
3342
+ { id: "user", label: t("userActivity.column.user", "User"), value: who, kind: "id" }
3343
+ ];
3344
+ if (doneBy) {
3345
+ items.push({
3346
+ id: "doneBy",
3347
+ label: t("adminPanel.activity.column.doneBy", "Done by"),
3348
+ value: doneBy
3349
+ });
3350
+ }
3351
+ if (row.details?.reason && presentation.key.startsWith("impersonation")) {
3352
+ items.push({
3353
+ id: "reasonGiven",
3354
+ label: t("userActivity.details.reasonGiven", "Reason given"),
3355
+ value: row.details.reason,
3356
+ fullWidth: true
3357
+ });
3358
+ }
3359
+ items.push(
3360
+ {
3361
+ id: "ip",
3362
+ label: t("adminPanel.activity.details.ip", "IP address"),
3363
+ value: ipText(t, row) || null,
3364
+ kind: "id"
3365
+ },
3366
+ {
3367
+ id: "place",
3368
+ label: t("adminPanel.activity.details.location", "Location"),
3369
+ value: getEventPlace(row) || null
3370
+ },
3371
+ {
3372
+ id: "browser",
3373
+ label: t("adminPanel.activity.details.browser", "Browser"),
3374
+ value: row.browser || null
3375
+ },
3376
+ {
3377
+ id: "os",
3378
+ label: t("adminPanel.activity.details.os", "Operating system"),
3379
+ value: row.os || null
3380
+ },
3381
+ {
3382
+ id: "userAgent",
3383
+ label: t("adminPanel.activity.details.userAgent", "User agent"),
3384
+ value: row.userAgent || null,
3385
+ kind: "id",
3386
+ fullWidth: true
3387
+ },
3388
+ {
3389
+ id: "eventId",
3390
+ label: t("adminPanel.activity.details.eventId", "Event ID"),
3391
+ value: row.id,
3392
+ kind: "id"
3393
+ }
3394
+ );
3395
+ const deviceFields = /* @__PURE__ */ new Set(["ip", "place", "browser", "os", "userAgent"]);
3396
+ const byAdmin = row.actor?.type === "admin" || row.actor?.type === "system";
3397
+ return {
3398
+ title: t("adminPanel.activity.details.title", "{event}: {name}", { event: label, name: who }),
3399
+ items: byAdmin ? items.filter(
3400
+ (item) => !deviceFields.has(item.id) || item.value !== null && item.value !== ""
3401
+ ) : items
3402
+ };
3403
+ };
3404
+ const EventTable = ({
3405
+ rows,
3406
+ label,
3407
+ wide = false,
3408
+ busy = false,
3409
+ nameOf,
3410
+ badge,
3411
+ columns,
3412
+ stackedSubject,
3413
+ stackedDetail,
3414
+ details,
3415
+ detailsAction,
3416
+ rowKind
3417
+ }) => {
3418
+ const t = useT();
3419
+ const { formatRelativeTime } = useSessionFormatters();
3420
+ const [measureRef, width] = useElementWidth();
3421
+ const {
3422
+ selected,
3423
+ open: openDetails,
3424
+ close: closeDetails,
3425
+ onCloseAutoFocus,
3426
+ setContainer
3427
+ } = useEventDetails();
3428
+ const layout = getEventListLayout(width, { wide });
3429
+ const detailsLabel = (row) => t("adminPanel.activity.details.open", "Details of {event}, {time}", {
3430
+ event: nameOf(row),
3431
+ time: formatRelativeTime(row.at)
3432
+ });
3433
+ const kindOf = (row) => rowKind ? rowKind(row) : void 0;
3434
+ let list;
3435
+ if (layout === "stacked") {
3436
+ list = /* @__PURE__ */ jsxRuntime.jsx(StackedList, { "aria-label": label, "data-event-list": "stacked", children: rows.map((row) => {
3437
+ const subject = stackedSubject ? stackedSubject(row) : null;
3438
+ const detail = stackedDetail ? stackedDetail(row) : "";
3439
+ return /* @__PURE__ */ jsxRuntime.jsx(
3440
+ StackedItem,
3441
+ {
3442
+ "data-event-row": kindOf(row),
3443
+ "data-event-id": row.id,
3444
+ onClick: (event) => openDetails(row, event.currentTarget),
3445
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, padding: 3, minWidth: 0, children: [
3446
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", alignItems: "center", minWidth: 0, children: [
3447
+ badge(row),
3448
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", marginLeft: "auto", children: [
3449
+ /* @__PURE__ */ jsxRuntime.jsx(EventTime, { value: row.at, compact: true }),
3450
+ /* @__PURE__ */ jsxRuntime.jsx(
3451
+ DetailsButton,
3452
+ {
3453
+ label: detailsLabel(row),
3454
+ onOpen: (trigger) => openDetails(row, trigger)
3455
+ }
3456
+ )
3457
+ ] })
3458
+ ] }),
3459
+ subject ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { minWidth: 0, children: subject }) : null,
3460
+ detail ? /* @__PURE__ */ jsxRuntime.jsx(BreakAnywhere, { variant: "pi", textColor: "neutral600", children: detail }) : null
3461
+ ] })
3462
+ },
3463
+ row.id
3464
+ );
3465
+ }) });
3466
+ } else {
3467
+ const cols = columns(layout);
3468
+ list = /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-event-list": layout, children: /* @__PURE__ */ jsxRuntime.jsxs(
3469
+ designSystem.Table,
3470
+ {
3471
+ colCount: cols.length + 2,
3472
+ rowCount: rows.length + 1,
3473
+ "aria-label": label,
3474
+ "aria-busy": busy,
3475
+ children: [
3476
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
3477
+ /* @__PURE__ */ jsxRuntime.jsx(HeaderCell, { children: t("adminPanel.activity.column.time", "Time") }),
3478
+ cols.map((column) => /* @__PURE__ */ jsxRuntime.jsx(HeaderCell, { children: column.header }, column.id)),
3479
+ /* @__PURE__ */ jsxRuntime.jsx(HeaderCell, { hidden: true, children: t("adminPanel.table.actions", "Actions") })
3480
+ ] }) }),
3481
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: rows.map((row) => /* @__PURE__ */ jsxRuntime.jsxs(
3482
+ ClickableRow,
3483
+ {
3484
+ "data-event-row": kindOf(row),
3485
+ "data-event-id": row.id,
3486
+ onClick: (event) => openDetails(row, event.currentTarget),
3487
+ children: [
3488
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(EventTime, { value: row.at }) }),
3489
+ cols.map(
3490
+ (column) => column.wrap === false ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: column.render(row, layout) }, column.id) : /* @__PURE__ */ jsxRuntime.jsx(WrapCell, { children: column.render(row, layout) }, column.id)
3491
+ ),
3492
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "flex-end", gap: 1, onKeyDown: stopCellKeys, children: /* @__PURE__ */ jsxRuntime.jsx(
3493
+ DetailsButton,
3494
+ {
3495
+ label: detailsLabel(row),
3496
+ onOpen: (trigger) => openDetails(row, trigger)
3497
+ }
3498
+ ) }) })
3499
+ ]
3500
+ },
3501
+ row.id
3502
+ )) })
3503
+ ]
3504
+ }
3505
+ ) });
3506
+ }
3507
+ const content = selected ? details(selected) : null;
3508
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { ref: measureRef, minWidth: 0, width: "100%", children: [
3509
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { ref: setContainer, tabIndex: -1, minWidth: 0, children: list }),
3510
+ content ? /* @__PURE__ */ jsxRuntime.jsx(
3511
+ EventDetailsModal,
3512
+ {
3513
+ title: content.title,
3514
+ items: content.items,
3515
+ footerAction: detailsAction ? detailsAction(selected, closeDetails) : null,
3516
+ onClose: closeDetails,
3517
+ onCloseAutoFocus
3518
+ }
3519
+ ) : null
3520
+ ] });
3521
+ };
3522
+ const EventCell = ({ presentation, detail }) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3523
+ /* @__PURE__ */ jsxRuntime.jsx(EventBadge, { presentation, nowrap: true }),
3524
+ detail ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: detail }) : null
3525
+ ] });
3526
+ const CellText = ({ text, strong = false }) => text ? /* @__PURE__ */ jsxRuntime.jsx(
3527
+ BreakAnywhere,
3528
+ {
3529
+ variant: "omega",
3530
+ fontWeight: strong ? "semiBold" : void 0,
3531
+ textColor: "neutral800",
3532
+ children: text
3533
+ }
3534
+ ) : /* @__PURE__ */ jsxRuntime.jsx(MissingValue, { variant: "omega" });
3535
+ const SignInEventTable = ({
3536
+ rows,
3537
+ label,
3538
+ showAdmin = false,
3539
+ onOpenAdmin,
3540
+ detailsAction,
3541
+ busy = false
3542
+ }) => {
3543
+ const t = useT();
3544
+ const { formatDate } = useSessionFormatters();
3545
+ const nameOf = (row) => {
3546
+ const presentation = getEventPresentation(row);
3547
+ return t(presentation.label.messageId, presentation.label.defaultMessage);
3548
+ };
3549
+ const adminName = (row) => /* @__PURE__ */ jsxRuntime.jsx(AdminName, { admin: row.admin, row, onOpenAdmin });
3550
+ return /* @__PURE__ */ jsxRuntime.jsx(
3551
+ EventTable,
3552
+ {
3553
+ rows,
3554
+ label,
3555
+ wide: showAdmin,
3556
+ busy,
3557
+ nameOf,
3558
+ rowKind: (row) => getEventPresentation(row).key,
3559
+ badge: (row) => /* @__PURE__ */ jsxRuntime.jsx(EventBadge, { presentation: getEventPresentation(row) }),
3560
+ columns: (layout) => [
3561
+ {
3562
+ id: "event",
3563
+ header: t("adminPanel.activity.column.event", "Event"),
3564
+ render: (row) => {
3565
+ const presentation = getEventPresentation(row);
3566
+ return /* @__PURE__ */ jsxRuntime.jsx(
3567
+ EventCell,
3568
+ {
3569
+ presentation,
3570
+ detail: eventDetailText(t, row, presentation, layout !== "full")
3571
+ }
3572
+ );
3573
+ }
3574
+ },
3575
+ ...showAdmin ? [
3576
+ {
3577
+ id: "admin",
3578
+ header: t("adminPanel.activity.column.admin", "Admin"),
3579
+ render: adminName
3580
+ }
3581
+ ] : [],
3582
+ {
3583
+ id: "details",
3584
+ header: t("adminPanel.activity.column.details", "IP address and device"),
3585
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(SignInDetails, { row })
3586
+ },
3587
+ {
3588
+ id: "session",
3589
+ header: t("adminPanel.activity.column.session", "Session"),
3590
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(SessionState, { row })
3591
+ },
3592
+ ...layout === "full" ? [
3593
+ {
3594
+ id: "doneBy",
3595
+ header: t("adminPanel.activity.column.doneBy", "Done by"),
3596
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(CellText, { text: row.actor?.name || "" })
3597
+ }
3598
+ ] : []
3599
+ ],
3600
+ stackedSubject: showAdmin ? adminName : void 0,
3601
+ stackedDetail: (row) => {
3602
+ const presentation = getEventPresentation(row);
3603
+ const state = getSessionStatePresentation(row.session);
3604
+ return [
3605
+ eventDetailText(t, row, presentation, true),
3606
+ ipText(t, row),
3607
+ getEventPlace(row),
3608
+ deviceText(t, row),
3609
+ state ? t(state.label.messageId, state.label.defaultMessage) : ""
3610
+ ].filter(Boolean).join(" · ");
3611
+ },
3612
+ details: (row) => signInDetails(t, formatDate, row),
3613
+ detailsAction
3614
+ }
3615
+ );
3616
+ };
3617
+ const ActivityEventTable = ({ rows, label, showAdmin = false, busy = false }) => {
3618
+ const t = useT();
3619
+ const { formatDate } = useSessionFormatters();
3620
+ const actionOf = (row) => {
3621
+ const entry = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3622
+ return t(entry.messageId, entry.defaultMessage);
3623
+ };
3624
+ const badge = (row) => /* @__PURE__ */ jsxRuntime.jsx(
3625
+ designSystem.Badge,
3626
+ {
3627
+ ...getBadgeColors(getActivityTone(row.action)),
3628
+ "data-event-tone": getActivityTone(row.action),
3629
+ children: actionOf(row)
3630
+ }
3631
+ );
3632
+ return /* @__PURE__ */ jsxRuntime.jsx(
3633
+ EventTable,
3634
+ {
3635
+ rows,
3636
+ label,
3637
+ wide: showAdmin,
3638
+ busy,
3639
+ nameOf: actionOf,
3640
+ rowKind: (row) => row.action,
3641
+ badge,
3642
+ columns: () => [
3643
+ {
3644
+ id: "action",
3645
+ header: t("adminPanel.activity.column.action", "Action"),
3646
+ render: badge,
3647
+ wrap: false
3648
+ },
3649
+ {
3650
+ id: "entry",
3651
+ header: t("adminPanel.activity.column.entry", "Entry"),
3652
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(ActivityEntry, { row })
3653
+ },
3654
+ {
3655
+ id: "type",
3656
+ header: t("adminPanel.activity.column.contentType", "Content type"),
3657
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(CellText, { text: contentTypeText(row) })
3658
+ },
3659
+ ...showAdmin ? [
3660
+ {
3661
+ id: "admin",
3662
+ header: t("adminPanel.activity.column.admin", "Admin"),
3663
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(AdminName, { admin: row.admin })
3664
+ }
3665
+ ] : []
3666
+ ],
3667
+ stackedSubject: (row) => /* @__PURE__ */ jsxRuntime.jsx(ActivityEntry, { row }),
3668
+ stackedDetail: (row) => [contentTypeText(row), showAdmin ? row.admin?.name : ""].filter(Boolean).join(" · "),
3669
+ details: (row) => activityDetails(t, formatDate, row)
3670
+ }
3671
+ );
3672
+ };
3673
+ const UserEventTable = ({ rows, label, showUser = true, busy = false, detailsAction }) => {
3674
+ const t = useT();
3675
+ const { formatDate } = useSessionFormatters();
3676
+ const nameOf = (row) => {
3677
+ const presentation = getEventPresentation(row);
3678
+ return t(presentation.label.messageId, presentation.label.defaultMessage);
3679
+ };
3680
+ const userCell = (row) => /* @__PURE__ */ jsxRuntime.jsx(CellText, { text: userText(t, row), strong: Boolean(row.user?.email || row.user?.username) });
3681
+ const openUser = (row) => {
3682
+ const path = row.user?.email || row.user?.username ? getUserEntryPath(row.user) : null;
3683
+ return path && showUser ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.LinkButton, { tag: reactRouterDom.Link, to: path, variant: "tertiary", "data-open-user": "", children: t("userActivity.details.openUser", "Open user") }) : null;
3684
+ };
3685
+ return /* @__PURE__ */ jsxRuntime.jsx(
3686
+ EventTable,
3687
+ {
3688
+ rows,
3689
+ label,
3690
+ wide: showUser,
3691
+ busy,
3692
+ nameOf,
3693
+ rowKind: (row) => getEventPresentation(row).key,
3694
+ badge: (row) => /* @__PURE__ */ jsxRuntime.jsx(EventBadge, { presentation: getEventPresentation(row) }),
3695
+ columns: (layout) => [
3696
+ {
3697
+ id: "event",
3698
+ header: t("adminPanel.activity.column.event", "Event"),
3699
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(
3700
+ EventCell,
3701
+ {
3702
+ presentation: getEventPresentation(row),
3703
+ detail: userEventDetailText(t, row, layout !== "full")
3704
+ }
3705
+ )
3706
+ },
3707
+ ...showUser ? [{ id: "user", header: t("userActivity.column.user", "User"), render: userCell }] : [],
3708
+ {
3709
+ id: "details",
3710
+ header: t("adminPanel.activity.column.details", "IP address and device"),
3711
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(SignInDetails, { row })
3712
+ },
3713
+ ...layout === "full" ? [
3714
+ {
3715
+ id: "doneBy",
3716
+ header: t("adminPanel.activity.column.doneBy", "Done by"),
3717
+ render: (row) => /* @__PURE__ */ jsxRuntime.jsx(CellText, { text: doneByText(t, row) })
3718
+ }
3719
+ ] : []
3720
+ ],
3721
+ stackedSubject: showUser ? userCell : void 0,
3722
+ stackedDetail: (row) => [userEventDetailText(t, row, true), ipText(t, row), getEventPlace(row), deviceText(t, row)].filter(Boolean).join(" · "),
3723
+ details: (row) => userEventDetails(t, formatDate, row),
3724
+ detailsAction: (row, close) => {
3725
+ const open = openUser(row);
3726
+ const extra = detailsAction ? detailsAction(row, close) : null;
3727
+ if (!open && !extra) return null;
3728
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", children: [
3729
+ open,
3730
+ extra
3731
+ ] });
3732
+ }
3733
+ }
3734
+ );
3735
+ };
3736
+ const ADMIN_FILTER_OPTIONS = Object.freeze(["all", "signed-in", "not-signed-in"]);
3737
+ const ADMIN_PAGE_SIZE_OPTIONS = Object.freeze(["10", "25", "50", "100"]);
3738
+ const ADMIN_DEFAULT_PAGE_SIZE = "25";
3739
+ const ADMIN_MAX_SEARCH_LENGTH = 100;
3740
+ function parseAdminPanelQuery(query = {}) {
3741
+ const page = Number.parseInt(String(query?.page ?? ""), 10);
3742
+ const pageSize = String(query?.pageSize ?? "");
3743
+ const filter = String(query?.filter ?? "");
3744
+ let search = "";
3745
+ if (typeof query?.search === "string") {
3746
+ try {
3747
+ search = decodeURIComponent(query.search).trim();
3748
+ } catch {
3749
+ search = query.search.trim();
3750
+ }
3751
+ }
3752
+ return {
3753
+ page: Number.isInteger(page) && page >= 1 && page <= 1e6 ? page : 1,
3754
+ pageSize: Number(
3755
+ ADMIN_PAGE_SIZE_OPTIONS.includes(pageSize) ? pageSize : ADMIN_DEFAULT_PAGE_SIZE
3756
+ ),
3757
+ filter: ADMIN_FILTER_OPTIONS.includes(filter) ? filter : "all",
3758
+ search: search.slice(0, ADMIN_MAX_SEARCH_LENGTH)
3759
+ };
3760
+ }
3761
+ function buildAdminListParams(state) {
3762
+ return {
3763
+ page: state.page,
3764
+ pageSize: state.pageSize,
3765
+ filter: state.filter,
3766
+ ...state.search ? { search: state.search } : {}
3767
+ };
3768
+ }
3769
+ function hasAdminFilters(state) {
3770
+ return state.filter !== "all" || Boolean(state.search);
3771
+ }
3772
+ function getAdminStatusPresentation(row) {
3773
+ if (row?.account === "invited") {
3774
+ return {
3775
+ key: "invited",
3776
+ tone: "secondary",
3777
+ label: { messageId: "adminPanel.status.invited", defaultMessage: "Invited" },
3778
+ detail: {
3779
+ messageId: "adminPanel.status.invited.detail",
3780
+ defaultMessage: "Invitation not accepted yet"
3781
+ }
3782
+ };
3783
+ }
3784
+ if (row?.account === "deactivated") {
3785
+ return {
3786
+ key: "deactivated",
3787
+ tone: "neutral",
3788
+ label: { messageId: "adminPanel.status.deactivated", defaultMessage: "Deactivated" },
3789
+ detail: {
3790
+ messageId: "adminPanel.status.deactivated.detail",
3791
+ defaultMessage: "Cannot sign in"
3792
+ }
3793
+ };
3794
+ }
3795
+ const count = Number(row?.sessionCount) || 0;
3796
+ if (count > 0) {
3797
+ return {
3798
+ key: "signed-in",
3799
+ tone: "success",
3800
+ label: { messageId: "adminPanel.status.signedIn", defaultMessage: "Signed in" },
3801
+ detail: {
3802
+ messageId: "adminPanel.status.signedIn.detail",
3803
+ defaultMessage: "{count, plural, one {# session} other {# sessions}}",
3804
+ values: { count }
3805
+ }
3806
+ };
3807
+ }
3808
+ return {
3809
+ key: "not-signed-in",
3810
+ tone: "neutral",
3811
+ label: { messageId: "adminPanel.status.notSignedIn", defaultMessage: "Not signed in" },
3812
+ detail: {
3813
+ messageId: "adminPanel.status.notSignedIn.detail",
3814
+ defaultMessage: "No open session"
3815
+ }
3816
+ };
3817
+ }
3818
+ function splitDuration(seconds) {
3819
+ const value = Number(seconds);
3820
+ if (!Number.isFinite(value) || value <= 0) return null;
3821
+ if (value % 86400 === 0) return { unit: "days", count: value / 86400 };
3822
+ if (value % 3600 === 0) return { unit: "hours", count: value / 3600 };
3823
+ return { unit: "minutes", count: Math.max(1, Math.round(value / 60)) };
3824
+ }
3825
+ function getSignOutErrorMessage(error) {
3826
+ const response = (
3827
+ /** @type {any} */
3828
+ error?.response
3829
+ );
3830
+ const status = Number(response?.status ?? /** @type {any} */
3831
+ error?.status);
3832
+ const reason = response?.data?.error?.details?.reason;
3833
+ if (status === 403 && reason === "super-admin-protected") {
3834
+ return {
3835
+ messageId: "adminPanel.signOut.error.protected",
3836
+ defaultMessage: "Only a Super Admin can sign out a Super Admin."
3837
+ };
3838
+ }
3839
+ if (status === 403) {
3840
+ return {
3841
+ messageId: "adminPanel.signOut.error.forbidden",
3842
+ defaultMessage: "You do not have permission to sign admins out."
3843
+ };
3844
+ }
3845
+ if (status === 404) {
3846
+ return {
3847
+ messageId: "adminPanel.signOut.error.gone",
3848
+ defaultMessage: "This session has already ended. The list is up to date now."
3849
+ };
3850
+ }
3851
+ if (status === 429) {
3852
+ return {
3853
+ messageId: "adminPanel.signOut.error.rateLimited",
3854
+ defaultMessage: "Too many sign-outs in a short time. Wait a minute and try again."
3855
+ };
3856
+ }
3857
+ return {
3858
+ messageId: "adminPanel.signOut.error.generic",
3859
+ defaultMessage: "The admin could not be signed out. Try again."
3860
+ };
3861
+ }
3862
+ function withIdentityPlaceholders(admin, placeholderName, identity) {
3863
+ if (!admin || typeof admin !== "object") return admin;
3864
+ const hidden = !admin.self && !admin.name;
3865
+ return {
3866
+ ...admin,
3867
+ name: admin.name || placeholderName(admin.id),
3868
+ identityHidden: hidden,
3869
+ rolesHidden: hidden && identity?.roles === false
3870
+ };
3871
+ }
3872
+ function withEventAdminNames(row, placeholderName) {
3873
+ if (!row || typeof row !== "object") return row;
3874
+ const fill = (admin) => admin && typeof admin === "object" && !admin.name && admin.type !== "system" && admin.id !== null && admin.id !== void 0 ? { ...admin, name: placeholderName(admin.id), identityHidden: true } : admin;
3875
+ return {
3876
+ ...row,
3877
+ ...row.admin !== void 0 ? { admin: fill(row.admin) } : {},
3878
+ ...row.actor !== void 0 ? { actor: fill(row.actor) } : {}
3879
+ };
3880
+ }
3881
+ function useEventList({ path, params, logKey }) {
3882
+ const { get } = StrapiAdmin.useFetchClient();
3883
+ const { formatMessage } = reactIntl.useIntl();
3884
+ const fillNames = react.useCallback(
3885
+ (list) => list.map(
3886
+ (row) => withEventAdminNames(
3887
+ row,
3888
+ (id) => formatMessage(
3889
+ {
3890
+ id: getTranslation("adminPanel.identity.placeholder"),
3891
+ defaultMessage: "Admin #{id}"
3892
+ },
3893
+ { id }
3894
+ )
3895
+ )
3896
+ ),
3897
+ [formatMessage]
3898
+ );
3899
+ const [rows, setRows] = react.useState([]);
3900
+ const [meta, setMeta] = react.useState(null);
3901
+ const [page, setPage] = react.useState(1);
3902
+ const [loading, setLoading] = react.useState(true);
3903
+ const [loadingMore, setLoadingMore] = react.useState(false);
3904
+ const [error, setError] = react.useState(false);
3905
+ const requestRef = react.useRef(0);
3906
+ const key = JSON.stringify(params);
3907
+ const firstPage = Number(params?.page) > 0 ? Number(params.page) : 1;
3908
+ const load = react.useCallback(
3909
+ async (nextPage) => {
3910
+ const requestId = requestRef.current + 1;
3911
+ requestRef.current = requestId;
3912
+ if (nextPage === firstPage) setLoading(true);
3913
+ else setLoadingMore(true);
3914
+ try {
3915
+ const response = await get(path, { params: { ...JSON.parse(key), page: nextPage } });
3916
+ if (requestId !== requestRef.current) return;
3917
+ const body = response?.data || {};
3918
+ const data = fillNames(Array.isArray(body.data) ? body.data : []);
3919
+ setRows((current) => nextPage === firstPage ? data : [...current, ...data]);
3920
+ setMeta(body.meta || null);
3921
+ setPage(nextPage);
3922
+ setError(false);
3923
+ } catch (err) {
3924
+ if (requestId !== requestRef.current || isCancelledRequest(err)) return;
3925
+ setError(true);
3926
+ logSafeAdminError(logKey, err);
3927
+ } finally {
3928
+ if (requestId === requestRef.current) {
3929
+ setLoading(false);
3930
+ setLoadingMore(false);
3931
+ }
3932
+ }
3933
+ },
3934
+ [get, path, key, logKey, fillNames, firstPage]
3935
+ );
3936
+ react.useEffect(() => {
3937
+ load(firstPage);
3938
+ return () => {
3939
+ requestRef.current += 1;
3940
+ };
3941
+ }, [load, firstPage]);
3942
+ const pagination = meta?.pagination;
3943
+ const hasMore = Boolean(pagination && page < pagination.pageCount);
3944
+ const exportAll = react.useCallback(async () => {
3945
+ const all = [];
3946
+ let cursor = null;
3947
+ do {
3948
+ const response = await get(`${path}/export`, {
3949
+ params: toExportParams(JSON.parse(key), cursor)
3950
+ });
3951
+ const body = response?.data || {};
3952
+ if (!Array.isArray(body.data)) throw new Error("Invalid export response");
3953
+ all.push(...fillNames(body.data));
3954
+ cursor = typeof body.meta?.nextCursor === "string" ? body.meta.nextCursor : null;
3955
+ } while (cursor && all.length < MAX_EVENT_EXPORT_ROWS);
3956
+ return {
3957
+ rows: all.slice(0, MAX_EVENT_EXPORT_ROWS),
3958
+ capped: all.length > MAX_EVENT_EXPORT_ROWS || Boolean(cursor)
3959
+ };
3960
+ }, [get, path, key, fillNames]);
3961
+ return {
3962
+ rows,
3963
+ meta,
3964
+ loading,
3965
+ loadingMore,
3966
+ error,
3967
+ hasMore,
3968
+ loadMore: () => load(page + 1),
3969
+ reload: () => load(firstPage),
3970
+ exportAll
3971
+ };
3972
+ }
3973
+ function downloadCsv(content, name2) {
3974
+ const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
3975
+ const url = URL.createObjectURL(blob);
3976
+ const link = document.createElement("a");
3977
+ link.href = url;
3978
+ link.download = `${name2}-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`;
3979
+ link.click();
3980
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
3981
+ }
3982
+ const UserActivityList = ({ documentId, userLabel }) => {
3983
+ const { formatMessage } = reactIntl.useIntl();
3984
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
3985
+ const params = react.useMemo(
3986
+ () => buildUserActivityParams({ userId: documentId, pageSize: PANEL_USER_EVENT_LIMIT }),
3987
+ [documentId]
3988
+ );
3989
+ const list = useEventList({ path: USER_ACTIVITY_API_PATH, params, logKey: "userActivity.panel" });
3990
+ const title = t("userActivity.panel.title", "Security activity");
3991
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-user-activity": "", children: [
3992
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: title }),
3993
+ list.loading && list.rows.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "center", padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
3994
+ !list.loading && list.error ? /* @__PURE__ */ jsxRuntime.jsx(
3995
+ PersistentAlert,
3996
+ {
3997
+ variant: "danger",
3998
+ action: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
3999
+ children: t("adminPanel.activity.error", "The events could not be loaded.")
4000
+ }
4001
+ ) : null,
4002
+ !list.loading && !list.error && list.rows.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { padding: 3, background: "neutral0", borderColor: "neutral200", hasRadius: true, children: /* @__PURE__ */ jsxRuntime.jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t("userActivity.panel.empty", "No security events recorded for {user}.", {
4003
+ user: userLabel
4004
+ }) }) }) : null,
4005
+ list.rows.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
4006
+ UserEventTable,
4007
+ {
4008
+ rows: list.rows,
4009
+ showUser: false,
4010
+ busy: list.loading,
4011
+ label: t("userActivity.panel.listLabel", "Security activity of {user}", {
4012
+ user: userLabel
4013
+ })
4014
+ }
4015
+ ) : null,
4016
+ /* @__PURE__ */ jsxRuntime.jsx(TargetLink, { tag: reactRouterDom.NavLink, to: userActivityPagePath(documentId), "data-user-activity-link": "", children: t("userActivity.panel.showAll", "Show all security activity") })
4017
+ ] });
4018
+ };
4019
+ const UserActivityPanelSection = ({ documentId, userLabel }) => {
4020
+ const {
4021
+ allowedActions: { canRead },
4022
+ isLoading
4023
+ } = StrapiAdmin.useRBAC(pluginPermissions.userActivityRead);
4024
+ if (isLoading || !canRead || !documentId) return null;
4025
+ return /* @__PURE__ */ jsxRuntime.jsx(UserActivityList, { documentId, userLabel });
4026
+ };
4027
+ function requireSessionList(payload) {
4028
+ if (!Array.isArray(payload?.data)) throw new Error("Invalid session response");
4029
+ return payload.data;
4030
+ }
4031
+ function requireSuccessfulMutation(payload) {
4032
+ if (payload?.success !== true) throw new Error("Invalid mutation response");
4033
+ return payload;
4034
+ }
4035
+ const DEFAULT_SESSION_FILTER = "all";
4036
+ const SESSION_FILTER_OPTIONS = Object.freeze(["all", "open", "active", "idle", "ended"]);
4037
+ const DEFAULT_END_REASON_FILTER = "all";
4038
+ const END_REASON_FILTER_OPTIONS = Object.freeze(["all", ...SESSION_END_REASONS]);
4039
+ const VALID_SESSION_FILTERS = new Set(SESSION_FILTER_OPTIONS);
4040
+ const VALID_END_REASON_FILTERS = new Set(END_REASON_FILTER_OPTIONS);
4041
+ function isSessionFilter(value) {
4042
+ return typeof value === "string" && VALID_SESSION_FILTERS.has(value);
4043
+ }
4044
+ function isEndReasonFilter(value) {
4045
+ return typeof value === "string" && VALID_END_REASON_FILTERS.has(value);
4046
+ }
4047
+ function getManageableSessions(sessions) {
4048
+ if (!Array.isArray(sessions)) return [];
4049
+ return sessions.filter((session) => session?.isActive === true);
4050
+ }
4051
+ const USER_MODEL_UID = "plugin::users-permissions.user";
4052
+ const PANEL_SESSION_LIMIT = 5;
4053
+ const DASHBOARD_PATH = "/plugins/magic-sessionmanager";
4054
+ function isUserModel(model) {
4055
+ return model === USER_MODEL_UID;
4056
+ }
4057
+ const getActivity = (session) => toValidDate(session?.lastActive) || toValidDate(session?.loginTime);
4058
+ function getUserSessionSummary(sessions) {
4059
+ const rows = Array.isArray(sessions) ? sessions.filter((row) => row && typeof row === "object") : [];
4060
+ const open = rows.filter((session) => session.isActive === true);
4061
+ const activeCount = open.filter((session) => session.isTrulyActive === true).length;
4062
+ let lastActive = null;
4063
+ for (const session of rows) {
4064
+ const activity = getActivity(session);
4065
+ if (activity && (!lastActive || activity.getTime() > lastActive.getTime()))
4066
+ lastActive = activity;
4067
+ }
4068
+ return { isOnline: activeCount > 0, openCount: open.length, activeCount, lastActive };
4069
+ }
4070
+ function getVisiblePanelSessions(sessions, limit = PANEL_SESSION_LIMIT) {
4071
+ const rows = Array.isArray(sessions) ? [...sessions] : [];
4072
+ rows.sort(
4073
+ (a, b) => (getActivity(b)?.getTime() ?? -Infinity) - (getActivity(a)?.getTime() ?? -Infinity)
4074
+ );
4075
+ return { visible: rows.slice(0, limit), hiddenCount: Math.max(0, rows.length - limit) };
4076
+ }
4077
+ function endOpenSessions(sessions, reason) {
4078
+ if (!Array.isArray(sessions)) return [];
4079
+ return sessions.map(
4080
+ (session) => session?.isActive === true ? { ...session, isActive: false, isTrulyActive: false, terminationReason: reason } : session
4081
+ );
4082
+ }
4083
+ function getPanelUserLabel(user) {
4084
+ return presentText(user?.username) || presentText(user?.email);
4085
+ }
4086
+ function isNotFoundError(error) {
4087
+ if (!error || typeof error !== "object") return false;
4088
+ return error.status === 404 || error.response?.status === 404;
4089
+ }
4090
+ function buildUserSessionsHref(user) {
4091
+ const query = presentText(user?.email) || presentText(user?.username);
4092
+ if (!query) return DASHBOARD_PATH;
4093
+ return `${DASHBOARD_PATH}?${new URLSearchParams({ search: query }).toString()}`;
4094
+ }
4095
+ function planBlockedFormSync({ initialValues, modified, blocked }) {
4096
+ const hasBlockedField = Boolean(initialValues) && typeof initialValues === "object" && Object.prototype.hasOwnProperty.call(initialValues, "blocked");
4097
+ if (!hasBlockedField || typeof blocked !== "boolean") return { mode: "notice" };
4098
+ if (!modified) return { mode: "reset", initialValues: { ...initialValues, blocked } };
4099
+ return { mode: "change", field: "blocked", value: blocked };
4100
+ }
4101
+ function applyBlockedFormSync(plan, form) {
4102
+ try {
4103
+ if (plan.mode === "reset" && typeof form?.resetForm === "function") {
4104
+ form.resetForm(plan.initialValues);
4105
+ return true;
4106
+ }
4107
+ if (plan.mode === "change" && typeof form?.onChange === "function") {
4108
+ form.onChange(plan.field, plan.value);
4109
+ return true;
4110
+ }
4111
+ } catch {
4112
+ return false;
4113
+ }
4114
+ return false;
4115
+ }
4116
+ const FORM_CONSUMER = "MagicSessionManagerPanel";
4117
+ const PanelSessionCard = ({ session, t }) => {
4118
+ const { formatDate, formatRelativeTime, translate } = useSessionFormatters();
4119
+ const device = getDevicePresentation(session);
4120
+ const hasSummary = Boolean(device.browserLabel || device.os);
4121
+ const summary = hasSummary ? device.summary.text ?? translate(device.summary, device.summary.values) : "";
4122
+ const lastActivity = toValidDate(session.lastActive) || toValidDate(session.loginTime);
4123
+ const ipAddress = presentText(session.ipAddress);
4124
+ return /* @__PURE__ */ jsxRuntime.jsx(
4125
+ designSystem.Box,
4126
+ {
4127
+ tag: "li",
4128
+ padding: 3,
4129
+ background: "neutral0",
4130
+ borderColor: "neutral200",
4131
+ hasRadius: true,
4132
+ minWidth: 0,
4133
+ "data-panel-session": "",
4134
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 3, alignItems: "flex-start", minWidth: 0, children: [
4135
+ /* @__PURE__ */ jsxRuntime.jsx(
4136
+ designSystem.Flex,
4137
+ {
4138
+ background: "neutral100",
4139
+ color: "neutral700",
4140
+ hasRadius: true,
4141
+ padding: 2,
4142
+ shrink: 0,
4143
+ justifyContent: "center",
4144
+ alignItems: "center",
4145
+ "aria-hidden": true,
4146
+ children: /* @__PURE__ */ jsxRuntime.jsx(DeviceIcon, { icon: device.icon })
4147
+ }
4148
+ ),
4149
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, flex: "1 1 auto", children: [
4150
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", gap: 2, wrap: "wrap", children: [
4151
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: translate(device.deviceTypeMessage) }),
4152
+ /* @__PURE__ */ jsxRuntime.jsx(StatusBadge, { session, size: "S" })
4153
+ ] }),
4154
+ summary ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: summary }) : null,
4155
+ ipAddress ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("panel.sessions.ip", "IP {ip}", { ip: ipAddress }) }) : null,
4156
+ lastActivity ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", title: formatDate(lastActivity), children: t("panel.sessions.lastActive", "Last active {time}", {
4157
+ time: formatRelativeTime(lastActivity)
4158
+ }) }) : null
4159
+ ] })
4160
+ ] })
4161
+ }
4162
+ );
4163
+ };
4164
+ const SessionInfoPanel = ({ documentId, model, document: document2 }) => {
4165
+ const { formatMessage } = reactIntl.useIntl();
4166
+ const { formatDate, formatRelativeTime } = useSessionFormatters();
4167
+ const {
4168
+ allowedActions: { canAccess },
4169
+ isLoading: permissionsLoading
4170
+ } = StrapiAdmin.useRBAC(pluginPermissions.access);
4171
+ const [sessions, setSessions] = react.useState([]);
4172
+ const [loading, setLoading] = react.useState(true);
4173
+ const [loadError, setLoadError] = react.useState(false);
4174
+ const [reloadKey, setReloadKey] = react.useState(0);
4175
+ const [isBlocked, setIsBlocked] = react.useState(Boolean(document2?.blocked));
4176
+ const [pendingAction, setPendingAction] = react.useState(null);
4177
+ const [formOutOfSync, setFormOutOfSync] = react.useState(false);
4178
+ const panelRef = react.useRef(null);
4179
+ const blockToggleRef = react.useRef(null);
4180
+ const focusBlockToggle = react.useRef(false);
4181
+ const noOpenSessionsHintId = react.useId();
4182
+ const { get, post: postRequest } = StrapiAdmin.useFetchClient();
4183
+ const { toggleNotification } = StrapiAdmin.useNotification();
4184
+ const formInitialValues = StrapiAdmin.useForm(FORM_CONSUMER, (state) => state.initialValues, false);
4185
+ const formModified = StrapiAdmin.useForm(FORM_CONSUMER, (state) => state.modified, false);
4186
+ const formOnChange = StrapiAdmin.useForm(FORM_CONSUMER, (state) => state.onChange, false);
4187
+ const formResetForm = StrapiAdmin.useForm(FORM_CONSUMER, (state) => state.resetForm, false);
4188
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
4189
+ const userId = document2?.documentId || documentId;
4190
+ const isUserPanel = isUserModel(model);
4191
+ const persistedBlocked = Boolean(document2?.blocked);
4192
+ const userLabel = getPanelUserLabel(document2) || String(userId ?? "");
4193
+ react.useEffect(() => {
4194
+ setIsBlocked(persistedBlocked);
4195
+ setFormOutOfSync(false);
4196
+ }, [persistedBlocked, userId]);
4197
+ react.useEffect(() => {
4198
+ if (!focusBlockToggle.current || pendingAction !== null) return void 0;
4199
+ const expected = isBlocked ? "unblock" : "block";
4200
+ let attempts = 0;
4201
+ let timer;
4202
+ const tryFocus = () => {
4203
+ const button = blockToggleRef.current;
4204
+ if (button?.isConnected && !button.disabled && button.dataset.blockToggle === expected) {
4205
+ focusBlockToggle.current = false;
4206
+ button.focus();
4207
+ return;
4208
+ }
4209
+ attempts += 1;
4210
+ if (attempts < 20) timer = window.setTimeout(tryFocus, 25);
4211
+ else focusBlockToggle.current = false;
4212
+ };
4213
+ timer = window.setTimeout(tryFocus, 0);
4214
+ return () => window.clearTimeout(timer);
4215
+ }, [isBlocked, pendingAction]);
4216
+ react.useEffect(() => {
4217
+ if (model !== "plugin::users-permissions.user" || !userId || permissionsLoading || !canAccess) {
4218
+ setLoading(false);
4219
+ return void 0;
4220
+ }
4221
+ let cancelled = false;
4222
+ const fetchData = async () => {
4223
+ setLoading(true);
4224
+ setLoadError(false);
4225
+ try {
4226
+ const { data } = await get(`/magic-sessionmanager/user/${userId}/sessions`);
4227
+ if (cancelled) return;
4228
+ setSessions(requireSessionList(data));
4229
+ } catch (err) {
4230
+ if (!cancelled) setLoadError(true);
4231
+ logSafeAdminError("userSessions.load", err);
4232
+ } finally {
4233
+ if (!cancelled) setLoading(false);
4234
+ }
4235
+ };
4236
+ fetchData();
4237
+ return () => {
4238
+ cancelled = true;
4239
+ };
4240
+ }, [userId, model, get, reloadKey, canAccess, permissionsLoading]);
4241
+ const handleEndAll = async () => {
4242
+ if (!userId) return;
4243
+ setPendingAction("endAll");
4244
+ try {
4245
+ const response = await postRequest(`/magic-sessionmanager/user/${userId}/terminate-all`);
4246
+ requireSuccessfulMutation(response.data);
4247
+ setSessions((rows) => endOpenSessions(rows, "manual"));
4248
+ toggleNotification({
4249
+ type: "success",
4250
+ message: t("panel.notify.endAllSuccess", "All sessions of {user} ended.", {
4251
+ user: userLabel
4252
+ })
4253
+ });
4254
+ } catch (error) {
4255
+ toggleNotification({
4256
+ type: "danger",
4257
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.endAllError", "The sessions could not be ended. Please try again.")
4258
+ });
4259
+ logSafeAdminError("userSessions.endAll", error);
4260
+ throw error;
4261
+ } finally {
4262
+ setPendingAction(null);
4263
+ }
4264
+ };
4265
+ const changeBlocked = async (blocked) => {
4266
+ const response = await postRequest(`/magic-sessionmanager/user/${userId}/toggle-block`, {
4267
+ blocked
4268
+ });
4269
+ requireSuccessfulMutation(response.data);
4270
+ const newBlockedStatus = response.data.blocked === true;
4271
+ focusBlockToggle.current = newBlockedStatus !== isBlocked;
4272
+ setIsBlocked(newBlockedStatus);
4273
+ if (newBlockedStatus) setSessions((rows) => endOpenSessions(rows, "blocked"));
4274
+ const plan = planBlockedFormSync({
4275
+ initialValues: formInitialValues,
4276
+ modified: formModified,
4277
+ blocked: newBlockedStatus
4278
+ });
4279
+ const synced = applyBlockedFormSync(plan, { resetForm: formResetForm, onChange: formOnChange });
4280
+ setFormOutOfSync(!synced);
4281
+ return newBlockedStatus;
4282
+ };
4283
+ const handleBlock = async () => {
4284
+ if (!userId) return;
4285
+ setPendingAction("block");
4286
+ try {
4287
+ await changeBlocked(true);
4288
+ toggleNotification({
4289
+ type: "success",
4290
+ message: t("panel.notify.blockSuccess", "{user} is blocked.", { user: userLabel })
4291
+ });
4292
+ } catch (error) {
4293
+ toggleNotification({
4294
+ type: "danger",
4295
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.blockError", "The user could not be blocked. Please try again.")
4296
+ });
4297
+ logSafeAdminError("userSessions.block", error);
4298
+ throw error;
4299
+ } finally {
4300
+ setPendingAction(null);
4301
+ }
4302
+ };
4303
+ const handleUnblock = async () => {
4304
+ if (!userId) return;
4305
+ setPendingAction("unblock");
4306
+ try {
4307
+ await changeBlocked(false);
4308
+ toggleNotification({
4309
+ type: "success",
4310
+ message: t("panel.notify.unblockSuccess", "{user} can sign in again.", { user: userLabel })
4311
+ });
4312
+ } catch (error) {
4313
+ toggleNotification({
4314
+ type: "danger",
4315
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.unblockError", "The block could not be removed. Please try again.")
4316
+ });
4317
+ logSafeAdminError("userSessions.unblock", error);
4318
+ } finally {
4319
+ setPendingAction(null);
4320
+ }
4321
+ };
4322
+ if (!isUserPanel) {
4323
+ return null;
4324
+ }
4325
+ if (permissionsLoading || !canAccess) {
4326
+ return null;
4327
+ }
4328
+ const title = t("panel.title", "Sessions");
4329
+ if (!userId) {
4330
+ return {
4331
+ title,
4332
+ content: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { width: "100%", minWidth: 0, children: /* @__PURE__ */ jsxRuntime.jsx(ReadableText, { variant: "omega", textColor: "neutral700", tag: "p", children: t("panel.unsaved.description", "Save this user before you can manage sessions.") }) })
4333
+ };
4334
+ }
4335
+ if (loadError) {
4336
+ return {
4337
+ title,
4338
+ content: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { width: "100%", minWidth: 0, children: /* @__PURE__ */ jsxRuntime.jsx(
4339
+ PersistentAlert,
4340
+ {
4341
+ variant: "danger",
4342
+ closeLabel: t("common.close", "Close"),
4343
+ action: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { size: "S", variant: "secondary", onClick: () => setReloadKey((key) => key + 1), children: t("common.tryAgain", "Try again") }),
4344
+ children: t("panel.error.message", "Sessions could not be loaded.")
4345
+ }
4346
+ ) })
4347
+ };
4348
+ }
4349
+ const openSessions = getManageableSessions(sessions);
4350
+ const summary = getUserSessionSummary(sessions);
4351
+ const { visible, hiddenCount } = getVisiblePanelSessions(openSessions);
4352
+ const actionsDisabled = loading || pendingAction !== null;
4353
+ const hasOpenSessions = summary.openCount > 0;
4354
+ const endAllLabel = t("panel.actions.endAll", "End all sessions");
4355
+ const blockLabel = t("panel.actions.blockUser", "Block user");
4356
+ const unblockLabel = t("panel.actions.unblock", "Unblock user");
4357
+ return {
4358
+ title,
4359
+ content: /* @__PURE__ */ jsxRuntime.jsxs(
4360
+ designSystem.Flex,
4361
+ {
4362
+ ref: panelRef,
4363
+ direction: "column",
4364
+ alignItems: "stretch",
4365
+ gap: 4,
4366
+ width: "100%",
4367
+ minWidth: 0,
4368
+ tabIndex: -1,
4369
+ children: [
4370
+ loading ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "center", padding: 2, "data-panel-summary": "", children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: t("panel.loading", "Loading sessions") }) }) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, "data-panel-summary": "", children: [
4371
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
4372
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { variant: summary.isOnline ? "success" : "neutral", size: "M", children: summary.isOnline ? t("panel.status.online", "Online") : t("panel.status.notOnline", "Not online") }),
4373
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: t(
4374
+ "panel.summary.openCount",
4375
+ "{count, plural, one {# open session} other {# open sessions}}",
4376
+ { count: summary.openCount }
4377
+ ) })
4378
+ ] }),
4379
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("panel.summary.openHint", "Active or idle") }),
4380
+ summary.lastActive ? /* @__PURE__ */ jsxRuntime.jsx(
4381
+ designSystem.Typography,
4382
+ {
4383
+ variant: "pi",
4384
+ textColor: "neutral600",
4385
+ title: formatDate(summary.lastActive),
4386
+ children: t("panel.sessions.lastActive", "Last active {time}", {
4387
+ time: formatRelativeTime(summary.lastActive)
4388
+ })
4389
+ }
4390
+ ) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("panel.summary.noSessions", "No sessions recorded") })
4391
+ ] }),
4392
+ isBlocked ? /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: t("panel.blocked.message", "This account is blocked. The user cannot sign in.") }) : null,
4393
+ formOutOfSync ? /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "warning", closeLabel: t("common.close", "Close"), children: t(
4394
+ "panel.form.reloadNotice",
4395
+ "Reload this page before saving, or the Blocked field will be overwritten."
4396
+ ) }) : null,
4397
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-actions": "", children: [
4398
+ /* @__PURE__ */ jsxRuntime.jsxs(ActionStack, { children: [
4399
+ /* @__PURE__ */ jsxRuntime.jsx(
4400
+ ConfirmAction,
4401
+ {
4402
+ title: t("panel.confirm.endAllTitle", "End all sessions of {user}?", {
4403
+ user: userLabel
4404
+ }),
4405
+ body: t(
4406
+ "panel.confirm.endAllBody",
4407
+ "{count, plural, one {# open session ends} other {# open sessions end}} on all devices. {user} can sign in again unless you also block the account.",
4408
+ { count: summary.openCount, user: userLabel }
4409
+ ),
4410
+ confirmLabel: endAllLabel,
4411
+ onConfirm: handleEndAll,
4412
+ fallbackFocusRef: panelRef,
4413
+ disabled: actionsDisabled || !hasOpenSessions,
4414
+ trigger: /* @__PURE__ */ jsxRuntime.jsx(
4415
+ designSystem.Button,
4416
+ {
4417
+ fullWidth: true,
4418
+ size: "S",
4419
+ variant: "danger-light",
4420
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.SignOut, { "aria-hidden": true, focusable: false }),
4421
+ loading: pendingAction === "endAll",
4422
+ disabled: actionsDisabled || !hasOpenSessions,
4423
+ "aria-describedby": !loading && !hasOpenSessions ? noOpenSessionsHintId : void 0,
4424
+ type: "button",
4425
+ children: endAllLabel
4426
+ }
4427
+ )
4428
+ }
4429
+ ),
4430
+ isBlocked ? /* @__PURE__ */ jsxRuntime.jsx(
4431
+ designSystem.Button,
4432
+ {
4433
+ ref: blockToggleRef,
4434
+ "data-block-toggle": "unblock",
4435
+ fullWidth: true,
4436
+ size: "S",
4437
+ variant: "secondary",
4438
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.CheckCircle, { "aria-hidden": true, focusable: false }),
4439
+ loading: pendingAction === "unblock",
4440
+ disabled: actionsDisabled,
4441
+ onClick: handleUnblock,
4442
+ type: "button",
4443
+ children: unblockLabel
4444
+ }
4445
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
4446
+ ConfirmAction,
4447
+ {
4448
+ title: t("panel.confirm.blockTitle", "Block {user}?", { user: userLabel }),
4449
+ body: t(
4450
+ "panel.confirm.blockBody",
4451
+ "{user} can no longer sign in, and {count, plural, =0 {no open sessions are affected} one {# open session ends now} other {# open sessions end now}}. You can unblock the account later; ended sessions stay ended.",
4452
+ { count: summary.openCount, user: userLabel }
4453
+ ),
4454
+ confirmLabel: blockLabel,
4455
+ onConfirm: handleBlock,
4456
+ fallbackFocusRef: panelRef,
4457
+ disabled: actionsDisabled,
4458
+ trigger: /* @__PURE__ */ jsxRuntime.jsx(
4459
+ designSystem.Button,
4460
+ {
4461
+ ref: blockToggleRef,
4462
+ "data-block-toggle": "block",
4463
+ fullWidth: true,
4464
+ size: "S",
4465
+ variant: "danger-light",
4466
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Lock, { "aria-hidden": true, focusable: false }),
4467
+ loading: pendingAction === "block",
4468
+ disabled: actionsDisabled,
4469
+ type: "button",
4470
+ children: blockLabel
4471
+ }
4472
+ )
4473
+ }
4474
+ )
4475
+ ] }),
4476
+ !loading && !hasOpenSessions ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { id: noOpenSessionsHintId, variant: "pi", textColor: "neutral600", children: t("panel.actions.noOpenSessions", "No open sessions") }) : null,
4477
+ /* @__PURE__ */ jsxRuntime.jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
4478
+ "panel.actions.hint",
4479
+ "End all sessions lets the user sign in again. Block user also prevents new sign-ins."
4480
+ ) })
4481
+ ] }),
4482
+ userId ? /* @__PURE__ */ jsxRuntime.jsx(ImpersonationPanelSection, { documentId: String(userId), userLabel }) : null,
4483
+ loading ? null : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-sessions": "", children: [
4484
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("panel.sessions.openTitle", "Open sessions") }),
4485
+ visible.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
4486
+ designSystem.Flex,
4487
+ {
4488
+ tag: "ul",
4489
+ direction: "column",
4490
+ alignItems: "stretch",
4491
+ gap: 2,
4492
+ margin: 0,
4493
+ padding: 0,
4494
+ style: { listStyle: "none" },
4495
+ children: visible.map((session) => /* @__PURE__ */ jsxRuntime.jsx(PanelSessionCard, { session, t }, session.id))
4496
+ }
4497
+ ) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { padding: 3, background: "neutral0", borderColor: "neutral200", hasRadius: true, children: /* @__PURE__ */ jsxRuntime.jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
4498
+ "panel.empty.noOpenSessions",
4499
+ "No open sessions. {user} is not signed in on any device.",
4500
+ { user: userLabel }
4501
+ ) }) }),
4502
+ hiddenCount > 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("panel.sessions.more", "{count, plural, other {+# more}}", {
4503
+ count: hiddenCount
4504
+ }) }) : null
4505
+ ] }),
4506
+ /* @__PURE__ */ jsxRuntime.jsx(TargetLink, { tag: reactRouterDom.NavLink, to: buildUserSessionsHref(document2), children: t("panel.sessions.showAllLink", "Show all sessions") }),
4507
+ userId ? /* @__PURE__ */ jsxRuntime.jsx(UserActivityPanelSection, { documentId: String(userId), userLabel }) : null
4508
+ ]
4509
+ }
4510
+ )
4511
+ };
4512
+ };
4513
+ const prefixPluginTranslations = (data, pluginId2) => {
4514
+ const prefixed = {};
4515
+ Object.keys(data).forEach((key) => {
4516
+ prefixed[`${pluginId2}.${key}`] = data[key];
4517
+ });
4518
+ return prefixed;
4519
+ };
4520
+ const name = pluginPkg.strapi.name;
4521
+ const index = {
4522
+ register(app) {
4523
+ const pluginPermissions$1 = pluginPermissions.access;
4524
+ app.addMenuLink({
4525
+ to: `plugins/${pluginId$1}`,
4526
+ icon: PluginIcon,
4527
+ intlLabel: {
4528
+ id: `${pluginId$1}.plugin.name`,
4529
+ defaultMessage: pluginPkg.strapi.displayName
4530
+ },
4531
+ Component: () => Promise.resolve().then(() => require("./App-Bkv-W0Sv.js")),
4532
+ permissions: pluginPermissions$1
4533
+ });
4534
+ app.addSettingsLink(
4535
+ {
4536
+ id: pluginId$1,
4537
+ intlLabel: { id: `${pluginId$1}.settings.section`, defaultMessage: "Session Manager" }
4538
+ },
4539
+ [
4540
+ {
4541
+ intlLabel: {
4542
+ id: `${pluginId$1}.settings.link.configuration`,
4543
+ defaultMessage: "Configuration"
4544
+ },
4545
+ id: "general",
4546
+ to: `${pluginId$1}/general`,
4547
+ Component: () => Promise.resolve().then(() => require("./Settings-xokFI5LO.js")),
4548
+ permissions: pluginPermissions$1
4549
+ },
4550
+ {
4551
+ intlLabel: {
4552
+ id: `${pluginId$1}.settings.link.analytics`,
4553
+ defaultMessage: "Analytics"
4554
+ },
4555
+ id: "analytics",
4556
+ to: `${pluginId$1}/analytics`,
4557
+ Component: () => Promise.resolve().then(() => require("./Analytics-DeDLGiCe.js")),
4558
+ permissions: pluginPermissions$1
4559
+ }
4560
+ ]
4561
+ );
4562
+ app.registerPlugin({
4563
+ id: pluginId$1,
4564
+ initializer: Initializer,
4565
+ isReady: true,
4566
+ name
4567
+ });
4568
+ if ("widgets" in app && app.widgets && typeof app.widgets.register === "function") {
4569
+ app.widgets.register({
4570
+ icon: PluginIcon,
4571
+ title: {
4572
+ id: `${pluginId$1}.widget.online-users.title`,
4573
+ defaultMessage: "Online users"
4574
+ },
4575
+ link: {
4576
+ label: {
4577
+ id: `${pluginId$1}.widget.link`,
4578
+ defaultMessage: "Open Session Manager"
4579
+ },
4580
+ href: `/plugins/${pluginId$1}`
4581
+ },
4582
+ component: async () => {
4583
+ const component = await Promise.resolve().then(() => require("./OnlineUsersWidget-CSvNe2rC.js"));
4584
+ return component.default;
4585
+ },
4586
+ id: "online-users-widget",
4587
+ pluginId: pluginId$1,
4588
+ permissions: pluginPermissions$1
4589
+ });
4590
+ }
4591
+ },
4592
+ bootstrap(app) {
4593
+ try {
4594
+ const contentManagerPlugin = app.getPlugin("content-manager");
4595
+ if (contentManagerPlugin?.apis?.addEditViewSidePanel) {
4596
+ contentManagerPlugin.apis.addEditViewSidePanel([SessionInfoPanel]);
4597
+ }
4598
+ } catch (error) {
4599
+ logSafeAdminError("plugin.bootstrap", error);
4600
+ }
4601
+ },
4602
+ async registerTrads({ locales }) {
4603
+ const importedTrads = {
4604
+ en: () => Promise.resolve().then(() => require("./en-DI-98CPM.js")),
4605
+ de: () => Promise.resolve().then(() => require("./de-HcJ19LKI.js")),
4606
+ es: () => Promise.resolve().then(() => require("./es-Cm0Eklav.js")),
4607
+ fr: () => Promise.resolve().then(() => require("./fr-C3nzszsI.js")),
4608
+ pt: () => Promise.resolve().then(() => require("./pt-BPZ6chPT.js"))
4609
+ };
4610
+ const translatedLanguages = Object.keys(importedTrads).filter((lang) => locales.includes(lang));
4611
+ const translations = await Promise.all(
4612
+ translatedLanguages.map(
4613
+ (language) => importedTrads[language]().then(({ default: data }) => ({
4614
+ data: prefixPluginTranslations(data, pluginId$1),
4615
+ locale: language
4616
+ })).catch(() => ({
4617
+ data: {},
4618
+ locale: language
4619
+ }))
4620
+ )
4621
+ );
4622
+ return Promise.resolve(translations);
4623
+ }
4624
+ };
4625
+ exports.ACTIVITY_ACTION_LABELS = ACTIVITY_ACTION_LABELS;
4626
+ exports.ACTIVITY_ACTION_OPTIONS = ACTIVITY_ACTION_OPTIONS;
4627
+ exports.ACTIVITY_PAGE_SIZE_OPTIONS = ACTIVITY_PAGE_SIZE_OPTIONS;
4628
+ exports.ADMIN_DEFAULT_PAGE_SIZE = ADMIN_DEFAULT_PAGE_SIZE;
4629
+ exports.ADMIN_FILTER_OPTIONS = ADMIN_FILTER_OPTIONS;
4630
+ exports.ADMIN_PAGE_SIZE_OPTIONS = ADMIN_PAGE_SIZE_OPTIONS;
4631
+ exports.ALL_ADMINS_FILTER_OPTIONS = ALL_ADMINS_FILTER_OPTIONS;
4632
+ exports.ActivityEventTable = ActivityEventTable;
4633
+ exports.ConfirmAction = ConfirmAction;
4634
+ exports.DEFAULT_END_REASON_FILTER = DEFAULT_END_REASON_FILTER;
4635
+ exports.DEFAULT_SESSION_FILTER = DEFAULT_SESSION_FILTER;
4636
+ exports.DeviceIcon = DeviceIcon;
4637
+ exports.END_REASON_FILTER_OPTIONS = END_REASON_FILTER_OPTIONS;
4638
+ exports.EVENT_PAGE_SIZE = EVENT_PAGE_SIZE;
4639
+ exports.EqualGrid = EqualGrid;
4640
+ exports.MAX_EVENT_EXPORT_ROWS = MAX_EVENT_EXPORT_ROWS;
4641
+ exports.MissingValue = MissingValue;
4642
+ exports.PERIOD_OPTIONS = PERIOD_OPTIONS;
4643
+ exports.PageShell = PageShell;
4644
+ exports.PersistentAlert = PersistentAlert;
4645
+ exports.PropertyList = PropertyList;
4646
+ exports.REASON_MAX = REASON_MAX;
4647
+ exports.RECENT_EVENT_LIMIT = RECENT_EVENT_LIMIT;
4648
+ exports.RECENT_USER_EVENT_LIMIT = RECENT_USER_EVENT_LIMIT;
4649
+ exports.ReadableParagraphs = ReadableParagraphs;
4650
+ exports.ReadableText = ReadableText;
4651
+ exports.SELECT_PRESETS = SELECT_PRESETS;
4652
+ exports.SESSION_FILTER_OPTIONS = SESSION_FILTER_OPTIONS;
4653
+ exports.SESSION_STATES = SESSION_STATES;
4654
+ exports.SESSION_STATUS_PRESENTATION = SESSION_STATUS_PRESENTATION;
4655
+ exports.SETTINGS_FIELD_LABELS = SETTINGS_FIELD_LABELS;
4656
+ exports.SETTINGS_TAB_LABELS = SETTINGS_TAB_LABELS;
4657
+ exports.SIGN_IN_FILTER_OPTIONS = SIGN_IN_FILTER_OPTIONS;
4658
+ exports.SignInEventTable = SignInEventTable;
4659
+ exports.StatCard = StatCard;
4660
+ exports.StatGrid = StatGrid;
4661
+ exports.StatusBadge = StatusBadge;
4662
+ exports.USER_ACTIVITY_API_PATH = USER_ACTIVITY_API_PATH;
4663
+ exports.USER_ACTIVITY_FILTER_LABELS = USER_ACTIVITY_FILTER_LABELS;
4664
+ exports.USER_ACTIVITY_FILTER_OPTIONS = USER_ACTIVITY_FILTER_OPTIONS;
4665
+ exports.USER_ACTIVITY_PAGE_PATH = USER_ACTIVITY_PAGE_PATH;
4666
+ exports.USER_ACTIVITY_SETTINGS_PATH = USER_ACTIVITY_SETTINGS_PATH;
4667
+ exports.UserEventTable = UserEventTable;
4668
+ exports.ValueOrMissing = ValueOrMissing;
4669
+ exports.buildActivityCsv = buildActivityCsv;
4670
+ exports.buildActivityParams = buildActivityParams;
4671
+ exports.buildAdminListParams = buildAdminListParams;
4672
+ exports.buildSavePayload = buildSavePayload;
4673
+ exports.buildSelectOptions = buildSelectOptions;
4674
+ exports.buildSessionCsv = buildSessionCsv;
4675
+ exports.buildSessionJson = buildSessionJson;
4676
+ exports.buildSignInCsv = buildSignInCsv;
4677
+ exports.buildSignInParams = buildSignInParams;
4678
+ exports.buildTabSearch = buildTabSearch;
4679
+ exports.buildUserActivityCsv = buildUserActivityCsv;
4680
+ exports.buildUserActivityParams = buildUserActivityParams;
4681
+ exports.copyText = copyText;
4682
+ exports.downloadCsv = downloadCsv;
4683
+ exports.fieldHasError = fieldHasError;
4684
+ exports.formatClock = formatClock;
4685
+ exports.formatSessionDate = formatSessionDate;
4686
+ exports.getAdminStatusPresentation = getAdminStatusPresentation;
4687
+ exports.getBadgeColors = getBadgeColors;
4688
+ exports.getDevicePresentation = getDevicePresentation;
4689
+ exports.getDeviceTypeMessage = getDeviceTypeMessage;
4690
+ exports.getEndReasonPresentation = getEndReasonPresentation;
4691
+ exports.getErrorTab = getErrorTab;
4692
+ exports.getRevealScrollDelta = getRevealScrollDelta;
4693
+ exports.getSessionEndReason = getSessionEndReason;
4694
+ exports.getSessionEndReasonPresentation = getSessionEndReasonPresentation;
4695
+ exports.getSessionStatus = getSessionStatus;
4696
+ exports.getSignOutErrorMessage = getSignOutErrorMessage;
4697
+ exports.getTranslation = getTranslation;
4698
+ exports.getVisibleSettingsTabs = getVisibleSettingsTabs;
4699
+ exports.hasActivityPageFilters = hasActivityPageFilters;
4700
+ exports.hasAdminFilters = hasAdminFilters;
4701
+ exports.hasUserActivityFilters = hasUserActivityFilters;
4702
+ exports.index = index;
4703
+ exports.isCancelledRequest = isCancelledRequest;
4704
+ exports.isEndReasonFilter = isEndReasonFilter;
4705
+ exports.isNativeOnlySession = isNativeOnlySession;
4706
+ exports.isSessionFilter = isSessionFilter;
4707
+ exports.logSafeAdminError = logSafeAdminError;
4708
+ exports.normalizeDeviceType = normalizeDeviceType;
4709
+ exports.parseActivityPageQuery = parseActivityPageQuery;
4710
+ exports.parseAdminPanelQuery = parseAdminPanelQuery;
4711
+ exports.parseUserActivityQuery = parseUserActivityQuery;
4712
+ exports.pluginId = pluginId$1;
4713
+ exports.pluginPermissions = pluginPermissions;
4714
+ exports.presentText = presentText;
4715
+ exports.refocusIfLost = refocusIfLost;
4716
+ exports.requireSessionList = requireSessionList;
4717
+ exports.requireSuccessfulMutation = requireSuccessfulMutation;
4718
+ exports.resolveSettingsTab = resolveSettingsTab;
4719
+ exports.restoreDialogFocus = restoreDialogFocus;
4720
+ exports.splitDuration = splitDuration;
4721
+ exports.toValidDate = toValidDate;
4722
+ exports.useElementWidth = useElementWidth;
4723
+ exports.useEventList = useEventList;
4724
+ exports.useSecondsLeft = useSecondsLeft;
4725
+ exports.useSessionFormatters = useSessionFormatters;
4726
+ exports.useSettingsTranslate = useSettingsTranslate;
4727
+ exports.userText = userText;
4728
+ exports.usesLocalDatabase = usesLocalDatabase;
4729
+ exports.validateReason = validateReason;
4730
+ exports.withIdentityPlaceholders = withIdentityPlaceholders;