create-expo-updates-server 0.4.0 → 0.6.1

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 (175) hide show
  1. package/README.md +4 -2
  2. package/dist/template/Dockerfile +4 -6
  3. package/dist/template/README.md +4 -9
  4. package/dist/template/app/api/admin/device-favorites/route.test.ts +125 -0
  5. package/dist/template/app/api/admin/device-favorites/route.ts +91 -0
  6. package/dist/template/app/api/admin/distribution-history/restore/route.ts +39 -0
  7. package/dist/template/app/api/admin/distribution-history/route.test.ts +55 -0
  8. package/dist/template/app/api/admin/distribution-history/route.ts +24 -0
  9. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +2 -1
  10. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +2 -1
  11. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +2 -1
  12. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +2 -1
  13. package/dist/template/app/api/admin/updates/route.test.ts +21 -0
  14. package/dist/template/app/api/admin/updates/route.ts +12 -1
  15. package/dist/template/app/globals.css +65 -68
  16. package/dist/template/app/login/page.tsx +66 -42
  17. package/dist/template/app/updates/[encodedKey]/page.tsx +375 -263
  18. package/dist/template/app/updates/devices/page.tsx +188 -152
  19. package/dist/template/app/updates/embedded/page.tsx +63 -29
  20. package/dist/template/app/updates/emergency-redirects/page.tsx +93 -58
  21. package/dist/template/app/updates/layout.tsx +2 -1
  22. package/dist/template/app/updates/page.tsx +381 -283
  23. package/dist/template/app/updates/releases.test.tsx +156 -0
  24. package/dist/template/components/admin/admin-role.ts +5 -0
  25. package/dist/template/components/admin/admin-shell.tsx +166 -101
  26. package/dist/template/components/admin/confirm-action.tsx +123 -0
  27. package/dist/template/components/admin/language-switcher.tsx +25 -17
  28. package/dist/template/components/admin/release-badges.test.tsx +50 -0
  29. package/dist/template/components/admin/release-badges.tsx +101 -0
  30. package/dist/template/components/ui/alert.tsx +10 -3
  31. package/dist/template/components/ui/avatar.tsx +108 -0
  32. package/dist/template/components/ui/badge.tsx +2 -2
  33. package/dist/template/components/ui/breadcrumb.tsx +108 -0
  34. package/dist/template/components/ui/button.tsx +5 -5
  35. package/dist/template/components/ui/card.tsx +2 -2
  36. package/dist/template/components/ui/chart.tsx +1 -1
  37. package/dist/template/components/ui/collapsible.tsx +7 -0
  38. package/dist/template/components/ui/empty.tsx +103 -0
  39. package/dist/template/components/ui/field.tsx +248 -0
  40. package/dist/template/components/ui/input-group.tsx +170 -0
  41. package/dist/template/components/ui/input.tsx +1 -1
  42. package/dist/template/components/ui/native-select.tsx +1 -1
  43. package/dist/template/components/ui/radio-group.tsx +41 -0
  44. package/dist/template/components/ui/status-tones.ts +15 -0
  45. package/dist/template/components/ui/table.tsx +1 -1
  46. package/dist/template/components/ui/textarea.tsx +1 -1
  47. package/dist/template/docs/admin-ui.md +7 -3
  48. package/dist/template/docs/device-targeting.md +2 -7
  49. package/dist/template/docs/doctor.md +2 -2
  50. package/dist/template/docs/expo-app-setup.md +9 -27
  51. package/dist/template/docs/getting-started.md +3 -4
  52. package/dist/template/docs/installation-telemetry.md +2 -8
  53. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +5 -0
  54. package/dist/template/docs/migrations/2026-11-25-device-favorites.sql +53 -0
  55. package/dist/template/docs/migrations/2026-11-25-download-on-postpone.sql +5 -0
  56. package/dist/template/docs/migrations/2026-11-25-public-distribution-history.sql +283 -0
  57. package/dist/template/docs/migrations/schema.sql +349 -0
  58. package/dist/template/docs/npm-installer.md +3 -3
  59. package/dist/template/docs/operations-guide.md +8 -6
  60. package/dist/template/docs/ota-client-lifecycle.md +30 -68
  61. package/dist/template/docs/ota-update-policy.md +9 -20
  62. package/dist/template/docs/ru/admin-ui.md +7 -3
  63. package/dist/template/docs/ru/device-targeting.md +2 -2
  64. package/dist/template/docs/ru/doctor.md +2 -2
  65. package/dist/template/docs/ru/expo-app-setup.md +9 -9
  66. package/dist/template/docs/ru/getting-started.md +3 -3
  67. package/dist/template/docs/ru/installation-telemetry.md +2 -2
  68. package/dist/template/docs/ru/npm-installer.md +3 -3
  69. package/dist/template/docs/ru/operations-guide.md +8 -3
  70. package/dist/template/docs/ru/ota-client-lifecycle.md +30 -35
  71. package/dist/template/docs/ru/ota-update-policy.md +9 -7
  72. package/dist/template/docs/ru/publishing-npm-installer.md +2 -2
  73. package/dist/template/docs/uk/admin-ui.md +7 -3
  74. package/dist/template/docs/uk/device-targeting.md +2 -2
  75. package/dist/template/docs/uk/doctor.md +2 -2
  76. package/dist/template/docs/uk/expo-app-setup.md +9 -9
  77. package/dist/template/docs/uk/getting-started.md +3 -3
  78. package/dist/template/docs/uk/installation-telemetry.md +2 -2
  79. package/dist/template/docs/uk/npm-installer.md +3 -3
  80. package/dist/template/docs/uk/operations-guide.md +8 -3
  81. package/dist/template/docs/uk/ota-client-lifecycle.md +30 -35
  82. package/dist/template/docs/uk/ota-update-policy.md +9 -7
  83. package/dist/template/docs/uk/publishing-npm-installer.md +2 -2
  84. package/dist/template/lib/audience-ids.ts +4 -0
  85. package/dist/template/package-lock.json +46 -0
  86. package/dist/template/package.json +3 -1
  87. package/dist/template/scripts/configure-expo-app.mjs +3 -3
  88. package/dist/template/scripts/create-access-token.mjs +1 -1
  89. package/dist/template/scripts/lib/doctor.mjs +10 -7
  90. package/dist/template/scripts/lib/doctor.test.mjs +7 -5
  91. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +22 -7
  92. package/dist/template/scripts/lib/expo-app-configurator.mjs +25 -22
  93. package/dist/template/scripts/lib/expo-app-configurator.test.ts +37 -2
  94. package/dist/template/scripts/lib/ota-client-configurator.mjs +152 -55
  95. package/dist/template/scripts/lib/ota-client-configurator.test.ts +60 -20
  96. package/dist/template/scripts/lib/ota-client-package.mjs +25 -0
  97. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +90 -32
  98. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +49 -6
  99. package/dist/template/scripts/tests/device-analytics-migrations.mjs +12 -1
  100. package/dist/template/scripts/tests/device-targeting-activation.mjs +2 -3
  101. package/dist/template/scripts/tests/e2e/client-lifecycle.mjs +161 -0
  102. package/dist/template/scripts/tests/e2e/client-lifecycle.scenario.jsx +465 -0
  103. package/dist/template/scripts/tests/e2e/client-vitest.mts +18 -0
  104. package/dist/template/scripts/tests/e2e/console.mjs +86 -0
  105. package/dist/template/scripts/tests/e2e/delivery.mjs +296 -0
  106. package/dist/template/scripts/tests/e2e/device-favorites.mjs +309 -0
  107. package/dist/template/scripts/tests/e2e/installations.mjs +132 -0
  108. package/dist/template/scripts/tests/e2e/policy.mjs +253 -0
  109. package/dist/template/scripts/tests/e2e/registrar-token.mjs +59 -0
  110. package/dist/template/scripts/tests/e2e/release-matrix.mjs +303 -0
  111. package/dist/template/scripts/tests/e2e/releases.mjs +162 -0
  112. package/dist/template/scripts/tests/e2e/run.mjs +224 -0
  113. package/dist/template/scripts/tests/manifest-identity.sql +7 -5
  114. package/dist/template/scripts/tests/public-distribution-history.mjs +102 -0
  115. package/dist/template/src/client/admin-api.ts +45 -10
  116. package/dist/template/src/client/admin-types.ts +35 -1
  117. package/dist/template/src/client/devices/analytics.tsx +168 -231
  118. package/dist/template/src/client/devices/cohorts.tsx +181 -0
  119. package/dist/template/src/client/devices/device-name.tsx +37 -23
  120. package/dist/template/src/client/devices/favorite-targets.tsx +381 -0
  121. package/dist/template/src/client/devices/registry.tsx +258 -245
  122. package/dist/template/src/client/devices/use-devices-report.test.tsx +98 -0
  123. package/dist/template/src/client/devices/use-devices-report.ts +53 -82
  124. package/dist/template/src/client/devices/version-adoption-chart.tsx +47 -49
  125. package/dist/template/src/client/distribution-control.tsx +89 -57
  126. package/dist/template/src/client/distribution-history.tsx +353 -0
  127. package/dist/template/src/client/guard-action-catalog.tsx +183 -0
  128. package/dist/template/src/client/guard-action-combobox.test.ts +16 -22
  129. package/dist/template/src/client/guard-action-combobox.tsx +133 -239
  130. package/dist/template/src/client/guard-action-options.ts +4 -6
  131. package/dist/template/src/client/i18n/en.json +133 -2
  132. package/dist/template/src/client/i18n/language-switching.test.tsx +12 -3
  133. package/dist/template/src/client/i18n/ru.json +133 -2
  134. package/dist/template/src/client/i18n/uk.json +133 -2
  135. package/dist/template/src/client/logout-button.tsx +3 -3
  136. package/dist/template/src/client/policy-draft.ts +138 -0
  137. package/dist/template/src/client/update-audience-editor.tsx +597 -206
  138. package/dist/template/src/client/update-policy-editor.test.ts +101 -29
  139. package/dist/template/src/client/update-policy-editor.tsx +454 -320
  140. package/dist/template/src/client/use-filtered-results.ts +55 -0
  141. package/dist/template/src/server/controllers/manifest.test.ts +25 -3
  142. package/dist/template/src/server/controllers/manifest.ts +1 -2
  143. package/dist/template/src/server/devices/audience.ts +9 -5
  144. package/dist/template/src/server/lib/admin-audience-activation.test.ts +37 -90
  145. package/dist/template/src/server/lib/admin-release-history.test.ts +138 -0
  146. package/dist/template/src/server/lib/admin-updates.ts +160 -534
  147. package/dist/template/src/server/lib/distribution-history.ts +97 -0
  148. package/dist/template/src/server/lib/supabase.js +24 -0
  149. package/dist/template/src/server/lib/supabase.test.ts +38 -1
  150. package/dist/template/src/server/lib/update-policy.test.ts +20 -0
  151. package/dist/template/src/server/lib/update-policy.ts +23 -10
  152. package/dist/template/src/server/manifest/manifest-repository.ts +2 -2
  153. package/dist/template/src/server/manifest/manifest-values.test.ts +2 -0
  154. package/dist/template/src/server/manifest/manifest-values.ts +21 -13
  155. package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +7 -30
  156. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +2 -1
  157. package/dist/template/tsconfig.json +2 -2
  158. package/dist/template-manifest.json +445 -300
  159. package/package.json +1 -1
  160. package/dist/template/scripts/lib/device-identity.test.ts +0 -29
  161. package/dist/template/scripts/lib/ota-client.test.ts +0 -55
  162. package/dist/template/scripts/lib/ota-update-controller.test.ts +0 -232
  163. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +0 -154
  164. package/dist/template/scripts/tests/ota-client-types.mjs +0 -69
  165. package/dist/template/templates/expo-app/ota-client/README.md +0 -73
  166. package/dist/template/templates/expo-app/ota-client/controller.ts +0 -107
  167. package/dist/template/templates/expo-app/ota-client/device-identity.ts +0 -48
  168. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +0 -61
  169. package/dist/template/templates/expo-app/ota-client/index.ts +0 -16
  170. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +0 -97
  171. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +0 -293
  172. package/dist/template/templates/expo-app/ota-client/runtime.ts +0 -153
  173. package/dist/template/templates/expo-app/ota-client/types.ts +0 -85
  174. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +0 -25
  175. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +0 -196
@@ -0,0 +1,181 @@
1
+ "use client";
2
+
3
+ import { useFormatters } from "@/src/client/i18n/use-formatters";
4
+ import { useI18n } from "@/src/client/i18n/provider";
5
+ import type { DevicesReport } from "@/src/server/devices/report-types";
6
+ import {
7
+ Card,
8
+ CardContent,
9
+ CardDescription,
10
+ CardHeader,
11
+ CardTitle,
12
+ } from "@/components/ui/card";
13
+ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
14
+ import {
15
+ Table,
16
+ TableBody,
17
+ TableCell,
18
+ TableHead,
19
+ TableHeader,
20
+ TableRow,
21
+ } from "@/components/ui/table";
22
+
23
+ export function Cohorts({ report }: { report: DevicesReport }) {
24
+ const { t } = useI18n();
25
+ const { date, number, share } = useFormatters();
26
+ return (
27
+ <Card className="min-w-0 shadow-none">
28
+ <CardHeader>
29
+ <CardTitle>
30
+ <h2>{t("Когорты установок")}</h2>
31
+ </CardTitle>
32
+ <CardDescription>
33
+ {t(
34
+ "Группы по неделе первого heartbeat. Одна установка — одна запись, переустановка может создать новую.",
35
+ )}
36
+ </CardDescription>
37
+ </CardHeader>
38
+ <CardContent>
39
+ <Tabs defaultValue="adoption">
40
+ <TabsList
41
+ className="mb-4 max-w-full"
42
+ aria-label={t("Когорты установок")}
43
+ >
44
+ <TabsTrigger value="adoption">{t("Текущие версии")}</TabsTrigger>
45
+ <TabsTrigger value="retention">{t("Возвращаемость")}</TabsTrigger>
46
+ </TabsList>
47
+ <TabsContent value="adoption">
48
+ <p className="mb-3 text-xs text-muted-foreground">
49
+ {t(
50
+ "Активные за выбранный период, сгруппированные по неделе первого появления. Проценты внутри каждой когорты.",
51
+ )}
52
+ </p>
53
+ <Table>
54
+ <TableHeader>
55
+ <TableRow>
56
+ <TableHead>{t("Неделя · UTC")}</TableHead>
57
+ <TableHead>{t("Установки")}</TableHead>
58
+ <TableHead>OTA</TableHead>
59
+ <TableHead>{t("Embedded")}</TableHead>
60
+ <TableHead>{t("Не определён")}</TableHead>
61
+ </TableRow>
62
+ </TableHeader>
63
+ <TableBody>
64
+ {report.adoptionCohorts.map((c) => (
65
+ <TableRow key={c.weekStart}>
66
+ <TableCell className="font-medium">
67
+ {date(c.weekStart)}
68
+ </TableCell>
69
+ <TableCell className="tabular-nums">
70
+ {number(c.installations)}
71
+ </TableCell>
72
+ {[
73
+ c.otaInstallations,
74
+ c.embeddedInstallations,
75
+ c.unknownInstallations,
76
+ ].map((count, i) => (
77
+ <TableCell key={i}>
78
+ <div
79
+ className="rounded-md px-3 py-2 text-center tabular-nums"
80
+ style={{
81
+ background: `color-mix(in srgb, var(--chart-${i + 1}) ${c.installations ? 5 + (count / c.installations) * 20 : 0}%, transparent)`,
82
+ }}
83
+ >
84
+ {share(count, c.installations)}{" "}
85
+ <span className="ml-1 text-xs text-muted-foreground">
86
+ ({number(count)})
87
+ </span>
88
+ </div>
89
+ </TableCell>
90
+ ))}
91
+ </TableRow>
92
+ ))}
93
+ </TableBody>
94
+ </Table>
95
+ {!report.adoptionCohorts.length && (
96
+ <p className="py-6 text-center text-sm text-muted-foreground">
97
+ {t("Пока нет когорт для этой выборки.")}
98
+ </p>
99
+ )}
100
+ </TabsContent>
101
+ <TabsContent value="retention">
102
+ <p className="mb-3 max-w-4xl text-xs leading-5 text-muted-foreground">
103
+ {t(
104
+ "Новые установки за последние 90 дней после начала сбора. Фильтры платформы, канала, runtime и типа запуска применяются на момент первого heartbeat. D1/D7 — heartbeat ровно через 1/7 дней, даже если версия изменилась. D0 — исходная когорта (100%); для D1 и дальше неполные дни исключены. «—» означает, что день ещё не наблюдался полностью.",
105
+ )}
106
+ </p>
107
+ <Table>
108
+ <TableHeader>
109
+ <TableRow>
110
+ <TableHead>{t("Неделя · UTC")}</TableHead>
111
+ <TableHead>{t("Новые")}</TableHead>
112
+ {[0, 1, 7, 14, 30].map((d) => (
113
+ <TableHead key={d} className="text-center">
114
+ D{d}
115
+ </TableHead>
116
+ ))}
117
+ </TableRow>
118
+ </TableHeader>
119
+ <TableBody>
120
+ {report.cohorts.map((c) => (
121
+ <TableRow key={c.weekStart}>
122
+ <TableCell>{date(c.weekStart)}</TableCell>
123
+ <TableCell>{number(c.installations)}</TableCell>
124
+ {c.cells.map((cell) => (
125
+ <TableCell key={cell.day}>
126
+ <div
127
+ className="rounded-md px-2 py-2 text-center tabular-nums"
128
+ title={
129
+ cell.rate === null
130
+ ? t("Нет полностью наблюдаемых дней")
131
+ : cell.day === 0
132
+ ? t(
133
+ "D0: исходная когорта, включая сегодняшние установки",
134
+ )
135
+ : t(
136
+ "{0} из {1} установок с полностью наблюдаемым днём",
137
+ [
138
+ cell.retainedInstallations,
139
+ cell.eligibleInstallations,
140
+ ],
141
+ )
142
+ }
143
+ style={{
144
+ background:
145
+ cell.rate === null
146
+ ? "var(--muted)"
147
+ : `color-mix(in srgb, var(--chart-1) ${5 + cell.rate * 30}%, transparent)`,
148
+ }}
149
+ >
150
+ {cell.rate === null
151
+ ? "—"
152
+ : share(
153
+ cell.retainedInstallations ?? 0,
154
+ cell.eligibleInstallations,
155
+ )}
156
+ <span className="block text-[10px] text-muted-foreground">
157
+ {cell.rate === null
158
+ ? t("нет данных")
159
+ : `${cell.retainedInstallations}/${cell.eligibleInstallations}`}
160
+ </span>
161
+ </div>
162
+ </TableCell>
163
+ ))}
164
+ </TableRow>
165
+ ))}
166
+ </TableBody>
167
+ </Table>
168
+ {!report.cohorts.length && (
169
+ <p className="py-6 text-center text-sm text-muted-foreground">
170
+ {t(
171
+ "Возвращаемость появится для новых установок после начала сбора",
172
+ )}{" "}
173
+ {date(report.coverage.collectionStartedAt)}.
174
+ </p>
175
+ )}
176
+ </TabsContent>
177
+ </Tabs>
178
+ </CardContent>
179
+ </Card>
180
+ );
181
+ }
@@ -1,7 +1,8 @@
1
1
  "use client";
2
2
  import { useI18n } from "@/src/client/i18n/provider";
3
3
 
4
- import { useEffect, useState } from "react";
4
+ import { AdminRoleContext } from "@/components/admin/admin-role";
5
+ import { useContext, useEffect, useState } from "react";
5
6
  import { Input } from "@/components/ui/input";
6
7
  import { Button } from "@/components/ui/button";
7
8
  export function DeviceName({
@@ -12,6 +13,8 @@ export function DeviceName({
12
13
  platform: string;
13
14
  }) {
14
15
  const { t } = useI18n();
16
+ const role = useContext(AdminRoleContext);
17
+ const canEdit = role === "admin" || role === "operator";
15
18
  const [name, setName] = useState("");
16
19
  const [status, setStatus] = useState("");
17
20
  const [busy, setBusy] = useState(false);
@@ -47,9 +50,7 @@ export function DeviceName({
47
50
  });
48
51
  if (!r.ok)
49
52
  throw new Error((await r.json()).error || "Не удалось сохранить");
50
- setStatus(
51
- "Имя сохранено — устройство можно выбрать в аудитории OTA.",
52
- );
53
+ setStatus("Имя сохранено — устройство можно выбрать в аудитории OTA.");
53
54
  } catch (e) {
54
55
  setStatus((e as Error).message);
55
56
  } finally {
@@ -57,25 +58,38 @@ export function DeviceName({
57
58
  }
58
59
  }
59
60
  return (
60
- <div className="space-y-2 px-6 pb-6">
61
- <label htmlFor="ota-device-name" className="text-sm font-medium">
62
- {t("Имя устройства")}
63
- </label>
64
- <Input
65
- id="ota-device-name"
66
- maxLength={80}
67
- placeholder={t("Мой телефон")}
68
- value={name}
69
- disabled={!loaded || busy}
70
- onChange={(e) => setName(e.target.value)}
71
- />
72
- <Button
73
- variant="outline"
74
- onClick={save}
75
- disabled={!loaded || busy || !name.trim()}
76
- >
77
- {t("Сохранить имя")}
78
- </Button>
61
+ <div className="mx-4 space-y-2 rounded-lg border bg-muted/35 p-4 sm:mx-6">
62
+ {canEdit ? (
63
+ <>
64
+ <label htmlFor="ota-device-name" className="text-sm font-medium">
65
+ {t("Имя устройства")}
66
+ </label>
67
+ <Input
68
+ id="ota-device-name"
69
+ maxLength={80}
70
+ placeholder={t("Мой телефон")}
71
+ value={name}
72
+ disabled={!loaded || busy}
73
+ onChange={(e) => setName(e.target.value)}
74
+ />
75
+ <Button
76
+ variant="outline"
77
+ onClick={save}
78
+ disabled={!loaded || busy || !name.trim()}
79
+ >
80
+ {t("Сохранить имя")}
81
+ </Button>
82
+ </>
83
+ ) : (
84
+ <>
85
+ <p className="text-xs font-medium text-muted-foreground">
86
+ {t("Имя устройства")}
87
+ </p>
88
+ <p className="break-words text-sm">
89
+ {loaded || status ? name || "—" : t("Загрузка...")}
90
+ </p>
91
+ </>
92
+ )}
79
93
  <p className="text-xs text-muted-foreground" role="status">
80
94
  {t(status)}
81
95
  </p>
@@ -0,0 +1,381 @@
1
+ "use client";
2
+
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { Bookmark, BookmarkPlus, Check, Plus, X } from "lucide-react";
5
+ import { Button } from "@/components/ui/button";
6
+ import {
7
+ Dialog,
8
+ DialogClose,
9
+ DialogContent,
10
+ DialogDescription,
11
+ DialogFooter,
12
+ DialogHeader,
13
+ DialogTitle,
14
+ DialogTrigger,
15
+ } from "@/components/ui/dialog";
16
+ import { Input } from "@/components/ui/input";
17
+ import { Label } from "@/components/ui/label";
18
+ import {
19
+ NativeSelect,
20
+ NativeSelectOption,
21
+ } from "@/components/ui/native-select";
22
+ import { useFormatters } from "@/src/client/i18n/use-formatters";
23
+ import { useI18n } from "@/src/client/i18n/provider";
24
+
25
+ type Kind = "device" | "installation";
26
+ type Favorite = {
27
+ target_kind: Kind;
28
+ target_id: string;
29
+ name: string;
30
+ last_seen_at: string | null;
31
+ };
32
+ const endpoint = "/api/admin/device-favorites";
33
+
34
+ async function changeFavorite(method: "PUT" | "DELETE", payload: object) {
35
+ const response = await fetch(endpoint, {
36
+ method,
37
+ headers: { "Content-Type": "application/json" },
38
+ body: JSON.stringify(payload),
39
+ });
40
+ if (!response.ok) {
41
+ const data = await response.json();
42
+ throw new Error(data.error || "Favorites unavailable");
43
+ }
44
+ }
45
+
46
+ export function useFavoriteTargets(
47
+ platform: string,
48
+ enabled: boolean,
49
+ revision: number,
50
+ ) {
51
+ const [favorites, setFavorites] = useState<Favorite[] | null>(null);
52
+ const [error, setError] = useState("");
53
+ const [version, setVersion] = useState(0);
54
+ useEffect(() => {
55
+ if (!enabled) return;
56
+ const abort = new AbortController();
57
+ setError("");
58
+ setFavorites(null);
59
+ async function load() {
60
+ try {
61
+ const response = await fetch(
62
+ endpoint + "?platform=" + encodeURIComponent(platform),
63
+ { signal: abort.signal },
64
+ );
65
+ if (!response.ok) throw new Error("Favorites unavailable");
66
+ const { favorites } = await response.json();
67
+ if (!abort.signal.aborted) setFavorites(favorites);
68
+ } catch {
69
+ if (!abort.signal.aborted) setError("Favorites unavailable");
70
+ }
71
+ }
72
+ void load();
73
+ return () => abort.abort();
74
+ }, [platform, enabled, version, revision]);
75
+ return { favorites, error, refresh: () => setVersion((v) => v + 1) };
76
+ }
77
+
78
+ export function FavoriteList({
79
+ favorites,
80
+ error,
81
+ platform,
82
+ canWrite,
83
+ busy,
84
+ selectedDevices,
85
+ selectedInstallations,
86
+ onAdd,
87
+ onChanged,
88
+ }: {
89
+ favorites: Favorite[] | null;
90
+ error: string;
91
+ platform: string;
92
+ canWrite: boolean;
93
+ busy: boolean;
94
+ selectedDevices: string[];
95
+ selectedInstallations: string[];
96
+ onAdd: (kind: Kind, id: string) => void;
97
+ onChanged: () => void;
98
+ }) {
99
+ const { t } = useI18n();
100
+ const { fullDate } = useFormatters();
101
+ const title = useId();
102
+ const heading = useRef<HTMLHeadingElement>(null);
103
+ const [removing, setRemoving] = useState(false);
104
+ const [failure, setFailure] = useState("");
105
+ async function remove(favorite: Favorite) {
106
+ setFailure("");
107
+ setRemoving(true);
108
+ try {
109
+ await changeFavorite("DELETE", {
110
+ platform,
111
+ target_kind: favorite.target_kind,
112
+ target_id: favorite.target_id,
113
+ });
114
+ heading.current?.focus();
115
+ onChanged();
116
+ } catch (e) {
117
+ setFailure(
118
+ e instanceof TypeError
119
+ ? "Could not remove favorite"
120
+ : (e as Error).message,
121
+ );
122
+ } finally {
123
+ setRemoving(false);
124
+ }
125
+ }
126
+ return (
127
+ <section
128
+ aria-labelledby={title}
129
+ className="space-y-2 rounded-lg border p-3"
130
+ >
131
+ <h3
132
+ id={title}
133
+ ref={heading}
134
+ tabIndex={-1}
135
+ className="flex items-center gap-2 text-sm font-medium"
136
+ >
137
+ <Bookmark aria-hidden="true" className="size-4 text-primary" />
138
+ {t("My favorites")}
139
+ </h3>
140
+ {(error || failure) && (
141
+ <p role="alert" className="text-sm text-destructive">
142
+ {t(error || failure)}
143
+ </p>
144
+ )}
145
+ {!error && !favorites && (
146
+ <p role="status" className="text-sm text-muted-foreground">
147
+ {t("Загрузка...")}
148
+ </p>
149
+ )}
150
+ {favorites?.length === 0 && (
151
+ <p className="text-sm text-muted-foreground">
152
+ {t(
153
+ "Bookmark a recipient in the registry to reuse it across releases.",
154
+ )}
155
+ </p>
156
+ )}
157
+ {Boolean(favorites?.length) && (
158
+ <ul className="max-h-64 divide-y overflow-y-auto">
159
+ {favorites?.map((favorite) => {
160
+ const device = favorite.target_kind === "device";
161
+ const selected = (
162
+ device ? selectedDevices : selectedInstallations
163
+ ).includes(favorite.target_id);
164
+ return (
165
+ <li
166
+ key={favorite.target_kind + favorite.target_id}
167
+ className="flex items-center gap-2 py-2"
168
+ >
169
+ <div className="min-w-0 flex-1">
170
+ <p className="break-words text-sm font-medium">
171
+ {favorite.name}
172
+ </p>
173
+ <p className="break-all text-xs text-muted-foreground">
174
+ {device ? t("Устройство") : t("Установка")} ·{" "}
175
+ {favorite.target_id}
176
+ </p>
177
+ <p className="text-xs text-muted-foreground">
178
+ {favorite.last_seen_at ? (
179
+ <>
180
+ {t("Последний heartbeat")} ·{" "}
181
+ <time dateTime={favorite.last_seen_at}>
182
+ {fullDate(favorite.last_seen_at)}
183
+ </time>
184
+ </>
185
+ ) : (
186
+ t("Target is no longer in the registry")
187
+ )}
188
+ </p>
189
+ </div>
190
+ {canWrite && (
191
+ <>
192
+ <Button
193
+ type="button"
194
+ size="sm"
195
+ variant="outline"
196
+ disabled={busy || !favorite.last_seen_at || selected}
197
+ aria-label={
198
+ selected
199
+ ? t("{0} is selected", [favorite.name])
200
+ : t("Add {0} to audience", [favorite.name])
201
+ }
202
+ onClick={() =>
203
+ onAdd(favorite.target_kind, favorite.target_id)
204
+ }
205
+ >
206
+ {selected ? (
207
+ <Check aria-hidden="true" />
208
+ ) : (
209
+ <Plus aria-hidden="true" />
210
+ )}
211
+ {selected ? t("Selected") : t("Add")}
212
+ </Button>
213
+ <Button
214
+ type="button"
215
+ size="icon"
216
+ variant="ghost"
217
+ disabled={removing}
218
+ aria-label={t("Remove {0} from favorites", [
219
+ favorite.name,
220
+ ])}
221
+ onClick={() => remove(favorite)}
222
+ >
223
+ <X aria-hidden="true" />
224
+ </Button>
225
+ </>
226
+ )}
227
+ </li>
228
+ );
229
+ })}
230
+ </ul>
231
+ )}
232
+ </section>
233
+ );
234
+ }
235
+
236
+ export function BookmarkTarget({
237
+ platform,
238
+ deviceId,
239
+ installationId,
240
+ displayName,
241
+ showLabel = false,
242
+ favorites,
243
+ onChanged,
244
+ }: {
245
+ platform: string;
246
+ deviceId: string | null;
247
+ installationId: string;
248
+ displayName: string | null;
249
+ showLabel?: boolean;
250
+ favorites: Favorite[];
251
+ onChanged: () => void;
252
+ }) {
253
+ const { t } = useI18n();
254
+ const nameId = useId();
255
+ const kindId = useId();
256
+ const [open, setOpen] = useState(false);
257
+ const [name, setName] = useState("");
258
+ const [kind, setKind] = useState<Kind>(deviceId ? "device" : "installation");
259
+ const [saving, setSaving] = useState(false);
260
+ const [error, setError] = useState("");
261
+ const targetId = kind === "device" && deviceId ? deviceId : installationId;
262
+ function chooseKind(nextKind: Kind) {
263
+ setKind(nextKind);
264
+ const id = nextKind === "device" ? deviceId : installationId;
265
+ const existing = favorites.find(
266
+ (f) => f.target_kind === nextKind && f.target_id === id,
267
+ );
268
+ setName(existing?.name || displayName || "");
269
+ }
270
+ async function save(event: React.FormEvent) {
271
+ event.preventDefault();
272
+ if (saving || !name.trim()) return;
273
+ setSaving(true);
274
+ setError("");
275
+ try {
276
+ await changeFavorite("PUT", {
277
+ platform,
278
+ target_kind: kind,
279
+ target_id: targetId,
280
+ name: name.trim(),
281
+ });
282
+ setOpen(false);
283
+ onChanged();
284
+ } catch (e) {
285
+ setError(
286
+ e instanceof TypeError
287
+ ? "Could not save favorite"
288
+ : (e as Error).message,
289
+ );
290
+ } finally {
291
+ setSaving(false);
292
+ }
293
+ }
294
+ return (
295
+ <Dialog
296
+ open={open}
297
+ onOpenChange={(next) => {
298
+ if (saving) return;
299
+ if (next) {
300
+ chooseKind(deviceId ? "device" : "installation");
301
+ setError("");
302
+ }
303
+ setOpen(next);
304
+ }}
305
+ >
306
+ <DialogTrigger asChild>
307
+ <Button
308
+ type="button"
309
+ variant={showLabel ? "outline" : "ghost"}
310
+ size={showLabel ? "sm" : "icon"}
311
+ aria-label={t("Bookmark {0}", [displayName || installationId])}
312
+ title={t("Save favorite")}
313
+ >
314
+ <BookmarkPlus aria-hidden="true" />
315
+ {showLabel && t("Save favorite")}
316
+ </Button>
317
+ </DialogTrigger>
318
+ <DialogContent>
319
+ <DialogHeader>
320
+ <DialogTitle>{t("Save favorite")}</DialogTitle>
321
+ <DialogDescription>
322
+ {t("Only your account sees this name.")}
323
+ </DialogDescription>
324
+ </DialogHeader>
325
+ <form onSubmit={save} className="space-y-4">
326
+ {deviceId && (
327
+ <div className="space-y-2">
328
+ <Label htmlFor={kindId}>{t("Bookmark target")}</Label>
329
+ <NativeSelect
330
+ id={kindId}
331
+ value={kind}
332
+ disabled={saving}
333
+ onChange={(e) =>
334
+ chooseKind(
335
+ e.target.value === "device" ? "device" : "installation",
336
+ )
337
+ }
338
+ >
339
+ <NativeSelectOption value="device">
340
+ {t("Устройство")}
341
+ </NativeSelectOption>
342
+ <NativeSelectOption value="installation">
343
+ {t("Установка")}
344
+ </NativeSelectOption>
345
+ </NativeSelect>
346
+ </div>
347
+ )}
348
+ <p className="break-all text-xs text-muted-foreground">
349
+ {kind === "device" ? t("Устройство") : t("Установка")} · {targetId}
350
+ </p>
351
+ <div className="space-y-2">
352
+ <Label htmlFor={nameId}>{t("Favorite name")}</Label>
353
+ <Input
354
+ id={nameId}
355
+ value={name}
356
+ required
357
+ maxLength={80}
358
+ disabled={saving}
359
+ onChange={(e) => setName(e.target.value)}
360
+ />
361
+ </div>
362
+ {error && (
363
+ <p role="alert" className="text-sm text-destructive">
364
+ {t(error)}
365
+ </p>
366
+ )}
367
+ <DialogFooter>
368
+ <DialogClose asChild>
369
+ <Button type="button" variant="outline" disabled={saving}>
370
+ {t("Отменить")}
371
+ </Button>
372
+ </DialogClose>
373
+ <Button type="submit" disabled={saving || !name.trim()}>
374
+ {t("Save favorite")}
375
+ </Button>
376
+ </DialogFooter>
377
+ </form>
378
+ </DialogContent>
379
+ </Dialog>
380
+ );
381
+ }