@eifi1/ui-kit 0.29.0 → 0.30.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 (187) hide show
  1. package/README.md +26 -4
  2. package/dist/account/account-parts.d.ts +21 -0
  3. package/dist/account/account-parts.js +40 -0
  4. package/dist/account/account-parts.js.map +1 -0
  5. package/dist/account/data-export-setting.d.ts +73 -0
  6. package/dist/account/data-export-setting.js +113 -0
  7. package/dist/account/data-export-setting.js.map +1 -0
  8. package/dist/account/delete-account-setting.d.ts +91 -0
  9. package/dist/account/delete-account-setting.js +199 -0
  10. package/dist/account/delete-account-setting.js.map +1 -0
  11. package/dist/account/email-change-setting.d.ts +136 -0
  12. package/dist/account/email-change-setting.js +277 -0
  13. package/dist/account/email-change-setting.js.map +1 -0
  14. package/dist/account/sessions-setting.d.ts +110 -0
  15. package/dist/account/sessions-setting.js +146 -0
  16. package/dist/account/sessions-setting.js.map +1 -0
  17. package/dist/admin/admin-action-confirm.d.ts +91 -0
  18. package/dist/admin/admin-action-confirm.js +276 -0
  19. package/dist/admin/admin-action-confirm.js.map +1 -0
  20. package/dist/admin/admin-action-log.d.ts +105 -0
  21. package/dist/admin/admin-action-log.js +153 -0
  22. package/dist/admin/admin-action-log.js.map +1 -0
  23. package/dist/admin/admin-parts.d.ts +40 -0
  24. package/dist/admin/admin-parts.js +45 -0
  25. package/dist/admin/admin-parts.js.map +1 -0
  26. package/dist/admin/invitations-panel.d.ts +91 -0
  27. package/dist/admin/invitations-panel.js +289 -0
  28. package/dist/admin/invitations-panel.js.map +1 -0
  29. package/dist/admin/reviewer-scope-editor.d.ts +91 -0
  30. package/dist/admin/reviewer-scope-editor.js +134 -0
  31. package/dist/admin/reviewer-scope-editor.js.map +1 -0
  32. package/dist/admin/role-select.d.ts +91 -0
  33. package/dist/admin/role-select.js +128 -0
  34. package/dist/admin/role-select.js.map +1 -0
  35. package/dist/admin/transfer-ownership-dialog.d.ts +91 -0
  36. package/dist/admin/transfer-ownership-dialog.js +83 -0
  37. package/dist/admin/transfer-ownership-dialog.js.map +1 -0
  38. package/dist/admin/user-roster.d.ts +91 -0
  39. package/dist/admin/user-roster.js +285 -0
  40. package/dist/admin/user-roster.js.map +1 -0
  41. package/dist/auth/auth-errors.d.ts +85 -6
  42. package/dist/auth/auth-errors.js +62 -2
  43. package/dist/auth/auth-errors.js.map +1 -1
  44. package/dist/auth/forgot-password-form.d.ts +10 -3
  45. package/dist/auth/forgot-password-form.js +6 -3
  46. package/dist/auth/forgot-password-form.js.map +1 -1
  47. package/dist/auth/register-form.d.ts +17 -12
  48. package/dist/auth/register-form.js +6 -4
  49. package/dist/auth/register-form.js.map +1 -1
  50. package/dist/auth/reset-password-form.d.ts +10 -3
  51. package/dist/auth/reset-password-form.js +6 -3
  52. package/dist/auth/reset-password-form.js.map +1 -1
  53. package/dist/auth/sign-in-form.d.ts +61 -9
  54. package/dist/auth/sign-in-form.js +94 -13
  55. package/dist/auth/sign-in-form.js.map +1 -1
  56. package/dist/auth/verify-email.d.ts +7 -2
  57. package/dist/auth/verify-email.js +44 -8
  58. package/dist/auth/verify-email.js.map +1 -1
  59. package/dist/chart.d.ts +16 -11
  60. package/dist/components/account-chips.d.ts +47 -7
  61. package/dist/components/account-chips.js +19 -3
  62. package/dist/components/account-chips.js.map +1 -1
  63. package/dist/components/account-settings-labels.d.ts +12 -1
  64. package/dist/components/account-settings-labels.js +4 -1
  65. package/dist/components/account-settings-labels.js.map +1 -1
  66. package/dist/components/account-settings.d.ts +61 -6
  67. package/dist/components/account-settings.js +115 -15
  68. package/dist/components/account-settings.js.map +1 -1
  69. package/dist/components/amount-input.d.ts +17 -12
  70. package/dist/components/button-group.d.ts +17 -12
  71. package/dist/components/calculator.d.ts +17 -12
  72. package/dist/components/confirm-dialog.d.ts +17 -12
  73. package/dist/components/copy-button.d.ts +14 -9
  74. package/dist/components/danger-confirm.d.ts +17 -12
  75. package/dist/components/facing-pair.d.ts +17 -12
  76. package/dist/components/file-button.d.ts +17 -12
  77. package/dist/components/file-dropzone.d.ts +17 -12
  78. package/dist/components/form-actions.d.ts +17 -12
  79. package/dist/components/iban-input.d.ts +17 -12
  80. package/dist/components/language-select.d.ts +17 -12
  81. package/dist/components/legal-page.d.ts +17 -12
  82. package/dist/components/legal.d.ts +17 -12
  83. package/dist/components/money-field.d.ts +17 -12
  84. package/dist/components/number-field.d.ts +17 -12
  85. package/dist/components/number-input.d.ts +17 -12
  86. package/dist/components/numpad-sheet.d.ts +17 -12
  87. package/dist/components/phone-input.d.ts +17 -12
  88. package/dist/components/series-chart.d.ts +17 -12
  89. package/dist/components/settings-fields.d.ts +16 -11
  90. package/dist/components/share-card.d.ts +16 -11
  91. package/dist/components/text-link.d.ts +17 -12
  92. package/dist/components/time-input.d.ts +17 -12
  93. package/dist/components/ui.d.ts +13 -8
  94. package/dist/{register-form-V1OeNlMr.d.ts → delete-account-setting-CGVMckMw.d.ts} +6616 -5645
  95. package/dist/feedback/feedback-attachment.d.ts +17 -12
  96. package/dist/feedback/feedback-context.d.ts +17 -12
  97. package/dist/feedback/feedback-crash.d.ts +17 -12
  98. package/dist/feedback/feedback-dialog.d.ts +17 -12
  99. package/dist/feedback/feedback-inbox.d.ts +17 -12
  100. package/dist/feedback/feedback-labels.d.ts +17 -12
  101. package/dist/feedback/feedback-menu.d.ts +17 -12
  102. package/dist/feedback/feedback-record.d.ts +17 -12
  103. package/dist/feedback/feedback-row-detail.d.ts +17 -12
  104. package/dist/feedback/feedback-status-undo.d.ts +17 -12
  105. package/dist/feedback/feedback-submit.d.ts +17 -12
  106. package/dist/feedback/feedback-swipe.d.ts +17 -12
  107. package/dist/feedback/feedback-table.d.ts +14 -9
  108. package/dist/feedback/feedback-thread.d.ts +17 -12
  109. package/dist/feedback.d.ts +17 -12
  110. package/dist/hooks/use-anchored-panel.d.ts +6 -2
  111. package/dist/hooks/use-anchored-panel.js +2 -1
  112. package/dist/hooks/use-anchored-panel.js.map +1 -1
  113. package/dist/hooks/use-file-drop.d.ts +17 -12
  114. package/dist/i18n/defaults.d.ts +17 -12
  115. package/dist/i18n/defaults.js +22 -0
  116. package/dist/i18n/defaults.js.map +1 -1
  117. package/dist/i18n/german.d.ts +17 -12
  118. package/dist/i18n/german.js +215 -11
  119. package/dist/i18n/german.js.map +1 -1
  120. package/dist/i18n/kit-labels.d.ts +10 -5
  121. package/dist/i18n/kit-labels.js.map +1 -1
  122. package/dist/i18n/languages.d.ts +11 -6
  123. package/dist/i18n/locales/de-CH.d.ts +17 -12
  124. package/dist/i18n/locales/en.d.ts +17 -12
  125. package/dist/i18n/locales/es.d.ts +17 -12
  126. package/dist/i18n/locales/es.js +207 -9
  127. package/dist/i18n/locales/es.js.map +1 -1
  128. package/dist/i18n/locales/fr.d.ts +17 -12
  129. package/dist/i18n/locales/fr.js +209 -6
  130. package/dist/i18n/locales/fr.js.map +1 -1
  131. package/dist/i18n/locales/hu.d.ts +17 -12
  132. package/dist/i18n/locales/hu.js +207 -11
  133. package/dist/i18n/locales/hu.js.map +1 -1
  134. package/dist/i18n/locales/it.d.ts +17 -12
  135. package/dist/i18n/locales/it.js +209 -6
  136. package/dist/i18n/locales/it.js.map +1 -1
  137. package/dist/i18n/locales/zh.d.ts +17 -12
  138. package/dist/i18n/locales/zh.js +200 -6
  139. package/dist/i18n/locales/zh.js.map +1 -1
  140. package/dist/i18n/review.d.ts +17 -12
  141. package/dist/i18n/review.js +37 -1
  142. package/dist/i18n/review.js.map +1 -1
  143. package/dist/index.d.ts +8 -3
  144. package/dist/index.js +53 -0
  145. package/dist/index.js.map +1 -1
  146. package/dist/rhf/fields.d.ts +17 -12
  147. package/dist/rhf/form.d.ts +17 -12
  148. package/dist/rhf.d.ts +17 -12
  149. package/dist/shell/app-shell.d.ts +17 -12
  150. package/dist/shell/top-bar-brand.d.ts +17 -12
  151. package/dist/shell.d.ts +11 -6
  152. package/dist/wizard/stepper-nav.d.ts +17 -12
  153. package/dist/wizard.d.ts +17 -12
  154. package/package.json +1 -1
  155. package/src/account/account-parts.ts +67 -0
  156. package/src/account/data-export-setting.tsx +218 -0
  157. package/src/account/delete-account-setting.tsx +362 -0
  158. package/src/account/email-change-setting.tsx +457 -0
  159. package/src/account/sessions-setting.tsx +283 -0
  160. package/src/admin/admin-action-confirm.tsx +495 -0
  161. package/src/admin/admin-action-log.tsx +297 -0
  162. package/src/admin/admin-parts.ts +82 -0
  163. package/src/admin/invitations-panel.tsx +516 -0
  164. package/src/admin/reviewer-scope-editor.tsx +234 -0
  165. package/src/admin/role-select.tsx +286 -0
  166. package/src/admin/transfer-ownership-dialog.tsx +172 -0
  167. package/src/admin/user-roster.tsx +573 -0
  168. package/src/auth/auth-errors.ts +165 -8
  169. package/src/auth/forgot-password-form.tsx +21 -5
  170. package/src/auth/register-form.tsx +24 -6
  171. package/src/auth/reset-password-form.tsx +19 -5
  172. package/src/auth/sign-in-form.tsx +207 -35
  173. package/src/auth/verify-email.tsx +59 -8
  174. package/src/components/account-chips.tsx +64 -7
  175. package/src/components/account-settings-labels.ts +15 -1
  176. package/src/components/account-settings.tsx +199 -23
  177. package/src/hooks/use-anchored-panel.ts +14 -3
  178. package/src/i18n/defaults.ts +22 -0
  179. package/src/i18n/german.ts +241 -5
  180. package/src/i18n/kit-labels.tsx +33 -0
  181. package/src/i18n/locales/es.ts +230 -3
  182. package/src/i18n/locales/fr.ts +232 -0
  183. package/src/i18n/locales/hu.ts +224 -5
  184. package/src/i18n/locales/it.ts +230 -0
  185. package/src/i18n/locales/zh.ts +205 -0
  186. package/src/i18n/review.ts +36 -0
  187. package/src/index.ts +93 -0
@@ -0,0 +1,285 @@
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { useMemo } from "react";
4
+ import { MoreHorizontal } from "lucide-react";
5
+ import { cn } from "../lib/cn.js";
6
+ import { useKitLabels, useKitLocale } from "../i18n/kit-labels.js";
7
+ import { AccountStateChip, RoleChip, dateColumn } from "../components/account-chips.js";
8
+ import { encodeSorts } from "../components/data-table-sort.js";
9
+ import { Popover } from "../components/popover.js";
10
+ import { Button, IconButton } from "../components/ui.js";
11
+ import { UserAvatar } from "../components/user-avatar.js";
12
+ import { personLabel } from "./admin-parts.js";
13
+ import { RoleSelect } from "./role-select.js";
14
+ function adminUserStates(row) {
15
+ const out = [];
16
+ if (row.deletion_scheduled_at || row.deletion_requested_at) {
17
+ out.push({ state: "deletion", date: row.deletion_scheduled_at ?? null });
18
+ } else if (row.is_active !== void 0) {
19
+ out.push(row.is_active ? "active" : "inactive");
20
+ }
21
+ if (row.email_verified === false) out.push("unverified");
22
+ if (row.password_change_required_at) out.push("passwordChange");
23
+ return out;
24
+ }
25
+ const USER_ROSTER_SORT_KEYS = ["name", "email", "role", "created", "last_login"];
26
+ function userRosterSort(sorts) {
27
+ const first = sorts.find((s) => USER_ROSTER_SORT_KEYS.includes(s.key));
28
+ return first ? encodeSorts([first]) ?? void 0 : void 0;
29
+ }
30
+ const DEFAULT_USER_ROSTER_LABELS = {
31
+ name: "Name",
32
+ email: "Email",
33
+ role: "Role",
34
+ state: "State",
35
+ created: "Created",
36
+ lastLogin: "Last login",
37
+ never: "Never",
38
+ actions: "Actions",
39
+ actionsFor: (name) => `Actions for ${name}`
40
+ };
41
+ function UserIdentityCell({
42
+ person,
43
+ name,
44
+ email,
45
+ avatar = true,
46
+ badge,
47
+ locale: localeProp,
48
+ className
49
+ }) {
50
+ const locale = useKitLocale(localeProp);
51
+ const named = personLabel({ first: person?.first, last: person?.last, name }, locale);
52
+ const address = (email ?? "").trim();
53
+ return /* @__PURE__ */ jsxs("div", { className: cn("flex min-w-0 items-center gap-2.5", className), children: [
54
+ avatar && /* @__PURE__ */ jsx(UserAvatar, { person, name, email, size: "sm" }),
55
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
56
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-center gap-1.5", children: [
57
+ /* @__PURE__ */ jsx("span", { "data-private": true, className: "truncate font-medium text-[var(--text-primary)]", children: named || address }),
58
+ badge
59
+ ] }),
60
+ named && address && /* @__PURE__ */ jsx("div", { "data-private": true, className: "truncate text-xs text-[var(--text-muted)]", children: address })
61
+ ] })
62
+ ] });
63
+ }
64
+ function UserRowActions({ actions, name, labels: labelsProp }) {
65
+ const labels = useKitLabels("userRoster", DEFAULT_USER_ROSTER_LABELS, labelsProp);
66
+ const entries = actions.filter((a) => Boolean(a) && !a.hidden);
67
+ if (entries.length === 0) return null;
68
+ const title = labels.actionsFor(name);
69
+ return /* @__PURE__ */ jsx(
70
+ Popover,
71
+ {
72
+ width: 240,
73
+ "aria-label": title,
74
+ className: "p-1",
75
+ trigger: ({ open, toggle, ref }) => /* @__PURE__ */ jsx(
76
+ IconButton,
77
+ {
78
+ ref,
79
+ size: "xs",
80
+ label: title,
81
+ "aria-haspopup": "dialog",
82
+ "aria-expanded": open,
83
+ stopPropagation: true,
84
+ onClick: toggle,
85
+ children: /* @__PURE__ */ jsx(MoreHorizontal, {})
86
+ }
87
+ ),
88
+ children: (close) => /* @__PURE__ */ jsx("ul", { className: "space-y-0.5", children: entries.map((action) => {
89
+ const Icon = action.icon;
90
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
91
+ Button,
92
+ {
93
+ type: "button",
94
+ variant: "ghost",
95
+ size: "sm",
96
+ stretch: true,
97
+ tone: action.tone === "danger" ? "danger" : void 0,
98
+ disabledReason: action.disabledReason,
99
+ className: "justify-start",
100
+ onClick: () => {
101
+ close();
102
+ action.onSelect();
103
+ },
104
+ children: [
105
+ Icon && /* @__PURE__ */ jsx(Icon, { className: "size-4 shrink-0", "aria-hidden": true }),
106
+ action.label
107
+ ]
108
+ }
109
+ ) }, action.key ?? action.label);
110
+ }) })
111
+ }
112
+ );
113
+ }
114
+ function rolesOf(row, roleOf) {
115
+ const raw = roleOf ? roleOf(row) : row.roles ?? row.role;
116
+ if (raw === null || raw === void 0 || raw === "") return [];
117
+ return typeof raw === "string" ? [raw] : [...raw];
118
+ }
119
+ function RowName({ row, children }) {
120
+ const locale = useKitLocale();
121
+ const name = personLabel(
122
+ { first: row.first_name, last: row.last_name, name: row.display_name, email: row.email },
123
+ locale
124
+ );
125
+ return /* @__PURE__ */ jsx(Fragment, { children: children(name) });
126
+ }
127
+ function StateChips({ states }) {
128
+ if (states.length === 0) return null;
129
+ return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: states.map((entry) => {
130
+ const spec = typeof entry === "string" ? { state: entry } : entry;
131
+ return /* @__PURE__ */ jsx(AccountStateChip, { state: spec.state, date: spec.date, tone: spec.tone, size: "xs", children: spec.label }, spec.state);
132
+ }) });
133
+ }
134
+ function userRosterColumns({
135
+ roles,
136
+ stateOf = adminUserStates,
137
+ extra = [],
138
+ actions,
139
+ editableRole,
140
+ onRoleChange,
141
+ roleOf,
142
+ emailColumn = false,
143
+ labels: labelsProp
144
+ }) {
145
+ const labels = { ...DEFAULT_USER_ROSTER_LABELS, ...labelsProp };
146
+ const roleWords = (row) => rolesOf(row, roleOf).map((role) => roles[role]?.label ?? role).join(", ");
147
+ const columns = [
148
+ {
149
+ key: "name",
150
+ header: labels.name,
151
+ cell: (row) => /* @__PURE__ */ jsx(
152
+ UserIdentityCell,
153
+ {
154
+ person: { first: row.first_name, last: row.last_name },
155
+ name: row.display_name,
156
+ email: row.email
157
+ }
158
+ ),
159
+ // By last name, then first (auth §3.2), as the server sorts `name`.
160
+ sortBy: (row) => `${row.last_name ?? ""} ${row.first_name ?? ""}`.trim().toLocaleLowerCase() || row.email,
161
+ // Either part, in either order, or the address (auth §10.6).
162
+ filterBy: (row) => [row.first_name, row.last_name, row.last_name, row.first_name, row.display_name, row.email].filter(Boolean).join(" "),
163
+ mobilePrimary: true
164
+ }
165
+ ];
166
+ if (emailColumn) {
167
+ columns.push({
168
+ key: "email",
169
+ header: labels.email,
170
+ className: "whitespace-nowrap",
171
+ cell: (row) => /* @__PURE__ */ jsx("span", { "data-private": true, className: "text-[var(--text-secondary)]", children: row.email }),
172
+ sortBy: (row) => row.email.toLowerCase(),
173
+ filterBy: (row) => row.email,
174
+ mobileHidden: true
175
+ });
176
+ }
177
+ columns.push(
178
+ {
179
+ key: "role",
180
+ header: labels.role,
181
+ cell: (row) => {
182
+ const held = rolesOf(row, roleOf);
183
+ const editing = held.length <= 1 ? editableRole?.(row) : false;
184
+ if (editing && onRoleChange) {
185
+ const rules = editing === true ? {} : editing;
186
+ return /* @__PURE__ */ jsx(RowName, { row, children: (name) => /* @__PURE__ */ jsx(
187
+ RoleSelect,
188
+ {
189
+ size: "sm",
190
+ name,
191
+ value: held[0] ?? null,
192
+ roles,
193
+ offered: rules.offered,
194
+ disabledReason: rules.disabledReason,
195
+ optionDisabledReason: rules.optionDisabledReason,
196
+ onChange: (role) => onRoleChange(row, role)
197
+ }
198
+ ) });
199
+ }
200
+ if (held.length === 0) return null;
201
+ return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: held.map((role) => /* @__PURE__ */ jsx(RoleChip, { value: role, roles, size: "xs" }, role)) });
202
+ },
203
+ sortBy: roleWords,
204
+ filter: {
205
+ type: "select",
206
+ getValue: (row) => rolesOf(row, roleOf)[0] ?? "",
207
+ options: Object.keys(roles).map((value) => ({ value, label: roles[value].label }))
208
+ }
209
+ },
210
+ {
211
+ key: "state",
212
+ header: labels.state,
213
+ cell: (row) => /* @__PURE__ */ jsx(StateChips, { states: stateOf(row) })
214
+ },
215
+ dateColumn({
216
+ key: "created",
217
+ header: labels.created,
218
+ value: (row) => row.created_at ?? null,
219
+ column: { mobileHidden: true }
220
+ }),
221
+ // How long ago rather than a date — the question is "recently?" — with the exact
222
+ // time in a tooltip (keksdose's last-seen column, Kurvenschmiede's).
223
+ dateColumn({
224
+ key: "last_login",
225
+ header: labels.lastLogin,
226
+ value: (row) => row.last_login_at ?? null,
227
+ display: "relative",
228
+ empty: labels.never
229
+ }),
230
+ ...extra
231
+ );
232
+ if (actions) {
233
+ columns.push({
234
+ key: "actions",
235
+ header: /* @__PURE__ */ jsx("span", { className: "sr-only", children: labels.actions }),
236
+ headerText: labels.actions,
237
+ // The caller's own words only: the menu reads the provider's itself, and the
238
+ // English defaults merged in above must not shadow them.
239
+ cell: (row) => /* @__PURE__ */ jsx(RowName, { row, children: (name) => /* @__PURE__ */ jsx(UserRowActions, { actions: actions(row), name, labels: labelsProp }) }),
240
+ className: "w-px whitespace-nowrap text-end",
241
+ headClassName: "w-px",
242
+ // The menu button keeps its own click: a row link must not wrap it.
243
+ noRowLink: true
244
+ });
245
+ }
246
+ return columns;
247
+ }
248
+ function useUserRosterColumns({
249
+ roles,
250
+ stateOf,
251
+ extra,
252
+ actions,
253
+ editableRole,
254
+ onRoleChange,
255
+ roleOf,
256
+ emailColumn,
257
+ labels: labelsProp
258
+ }) {
259
+ const labels = useKitLabels("userRoster", DEFAULT_USER_ROSTER_LABELS, labelsProp);
260
+ return useMemo(
261
+ () => userRosterColumns({
262
+ roles,
263
+ stateOf,
264
+ extra,
265
+ actions,
266
+ editableRole,
267
+ onRoleChange,
268
+ roleOf,
269
+ emailColumn,
270
+ labels
271
+ }),
272
+ [roles, stateOf, extra, actions, editableRole, onRoleChange, roleOf, emailColumn, labels]
273
+ );
274
+ }
275
+ export {
276
+ DEFAULT_USER_ROSTER_LABELS,
277
+ USER_ROSTER_SORT_KEYS,
278
+ UserIdentityCell,
279
+ UserRowActions,
280
+ adminUserStates,
281
+ useUserRosterColumns,
282
+ userRosterColumns,
283
+ userRosterSort
284
+ };
285
+ //# sourceMappingURL=user-roster.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/admin/user-roster.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { MoreHorizontal } from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport type { DateInput } from \"../lib/format\";\nimport type { PersonName } from \"../lib/person-name\";\nimport { useKitLabels, useKitLocale } from \"../i18n/kit-labels\";\nimport { AccountStateChip, RoleChip, dateColumn } from \"../components/account-chips\";\nimport type { AccountState, RoleVocabulary } from \"../components/account-chips\";\nimport type { ChipTone } from \"../components/chip\";\nimport type { DataTableColumn } from \"../components/data-table\";\nimport { encodeSorts } from \"../components/data-table-sort\";\nimport type { SortState } from \"../components/data-table-sort\";\nimport { Popover } from \"../components/popover\";\nimport { Button, IconButton } from \"../components/ui\";\nimport { UserAvatar } from \"../components/user-avatar\";\nimport { personLabel } from \"./admin-parts\";\nimport { RoleSelect } from \"./role-select\";\nimport type { RoleLock } from \"./role-select\";\n\n/**\n * The admin's user list (docs/user-admin-harmonization.md §3): a column preset for the\n * kit's `DataTable`, not a table of its own.\n *\n * keksdose built its roster by hand (1150 lines, its own Badge), Kurvenschmiede on the\n * kit `DataTable` with the 0.18 chips, kastlan as a settings page. What the three share\n * is the row — name over address, a role, the account's states, created, last login, the\n * app's own columns, and a handful of actions — so that is what the kit draws, and the\n * table, its paging, its sort and its filters stay the app's `DataTable` wiring:\n *\n * ```tsx\n * const columns = useUserRosterColumns<AdminUserRow, Role>({ roles: ROLES, actions, extra });\n * <DataTable rows={page.users} columns={columns} rowKey={(r) => r.id}\n * serverPagination={{ page, pageSize, total: page.total, onPageChange }}\n * sorts={sorts} onSortsChange={setSorts} />\n * // GET /admin/users?sort=${userRosterSort(sorts)}&…\n * ```\n *\n * The column keys ARE the server's sort keys (§3.1): `name`, `email`, `role`, `created`,\n * `last_login` — so {@link userRosterSort} turns the table's sort state into the query\n * as it is. Phone cards come from the same columns: the identity is the card's headline,\n * the role, states, last login and the actions are its fields, created is left off.\n */\n\n/* ── Rows and states ────────────────────────────────────────────────────────── */\n\n/**\n * The fields of the contract's `AdminUserRow` the preset reads (§3.2, the auth\n * contract's `UserResponse` core). An app's row has more — its `extra` — and the\n * preset passes the whole row to every callback.\n */\nexport interface UserRosterRow extends AdminUserStateFields {\n id: string | number;\n email: string;\n first_name?: string | null;\n last_name?: string | null;\n /** The derived whole name — only the fallback when both parts are blank. */\n display_name?: string | null;\n /** keksdose, Kurvenschmiede: one role. */\n role?: string | null;\n /** kastlan: the account's roles in the current company. Wins over `role`. */\n roles?: readonly string[] | null;\n created_at?: DateInput;\n /** Account-wide; kastlan's comes from its session rows (§3.2). */\n last_login_at?: DateInput;\n}\n\n/** The state fields of the contract's row that {@link adminUserStates} maps (§3.2). */\nexport interface AdminUserStateFields {\n is_active?: boolean;\n email_verified?: boolean;\n password_change_required_at?: string | null;\n /** `after_days` mode: the day the account is erased (§6.4). */\n deletion_scheduled_at?: string | null;\n /** When the user asked. The only deletion field in kastlan's `operator` mode, where\n * nothing is scheduled. */\n deletion_requested_at?: string | null;\n}\n\n/** One state chip of a row: an {@link AccountState}, or one with its `date` (the\n * `deletion` day), a `tone` or the app's own words. */\nexport type RosterState =\n | AccountState\n | { state: AccountState; date?: DateInput; tone?: ChipTone; label?: ReactNode };\n\n/**\n * The contract's row as state chips (§3.2: \"map 1:1 to the kit's AccountStateChip\"):\n *\n * - marked for deletion → `deletion` with the scheduled day (none in `operator` mode),\n * IN PLACE of `inactive` — such an account is always deactivated (§2.1);\n * - else `active` / `inactive` from `is_active`;\n * - `unverified` when `email_verified` is `false` (not when it is missing);\n * - `passwordChange` while `password_change_required_at` is set.\n */\nexport function adminUserStates(row: AdminUserStateFields): RosterState[] {\n const out: RosterState[] = [];\n if (row.deletion_scheduled_at || row.deletion_requested_at) {\n out.push({ state: \"deletion\", date: row.deletion_scheduled_at ?? null });\n } else if (row.is_active !== undefined) {\n out.push(row.is_active ? \"active\" : \"inactive\");\n }\n if (row.email_verified === false) out.push(\"unverified\");\n if (row.password_change_required_at) out.push(\"passwordChange\");\n return out;\n}\n\n/** The server's sort keys, which are the preset's column keys (§3.1). */\nexport const USER_ROSTER_SORT_KEYS = [\"name\", \"email\", \"role\", \"created\", \"last_login\"] as const;\nexport type UserRosterSortKey = (typeof USER_ROSTER_SORT_KEYS)[number];\n\n/**\n * The table's sort state as the `sort` query parameter of `GET /admin/users` (§3.1), in\n * the DataTable's own encoding ({@link encodeSorts}: `\"last_login.desc\"`), which\n * server-kit 0.4 reads beside the `-key` form. Only the first criterion on one of the\n * server's keys: an app's own column (`owned`) is the client's to sort, and the query\n * takes one key — a shift-clicked second criterion is not sent. `undefined` when nothing\n * the server knows is sorted, so its default order applies.\n */\nexport function userRosterSort(sorts: readonly SortState[]): string | undefined {\n const first = sorts.find((s) => (USER_ROSTER_SORT_KEYS as readonly string[]).includes(s.key));\n return first ? (encodeSorts([first]) ?? undefined) : undefined;\n}\n\n/* ── Labels ─────────────────────────────────────────────────────────────────── */\n\n/** The `userRoster` namespace: the preset's headers and the action menu's words. */\nexport interface UserRosterLabels {\n /** The identity column — the name with the address under it. */\n name: string;\n /** The separate address column (`emailColumn`). */\n email: string;\n role: string;\n state: string;\n created: string;\n lastLogin: string;\n /** A last login that never happened. */\n never: string;\n /** The actions column's (hidden) header. */\n actions: string;\n /** The action menu's button and panel — \"Actions for Ada Example\". */\n actionsFor: (name: string) => string;\n}\n\nexport const DEFAULT_USER_ROSTER_LABELS: UserRosterLabels = {\n name: \"Name\",\n email: \"Email\",\n role: \"Role\",\n state: \"State\",\n created: \"Created\",\n lastLogin: \"Last login\",\n never: \"Never\",\n actions: \"Actions\",\n actionsFor: (name) => `Actions for ${name}`,\n};\n\n/* ── UserIdentityCell ───────────────────────────────────────────────────────── */\n\nexport interface UserIdentityCellProps {\n /** First and last name (auth §3.2), shown in the READER's order. */\n person?: PersonName | null;\n /** A whole name, for an API that still sends `display_name` only. */\n name?: string | null;\n email?: string | null;\n /** The initials avatar before the name. Default true. */\n avatar?: boolean;\n /** After the name, on its line — a \"You\" chip, a demo mark. */\n badge?: ReactNode;\n /** Over the provider's locale. */\n locale?: string;\n className?: string;\n}\n\n/**\n * Who an account is, in one cell (§3.3): the initials avatar, the name in the reader's\n * order ({@link formatPersonName} — \"Example Ada\" in Hungarian) and the address under it\n * — the cell both rosters drew by hand. An account with no name yet (a migrated row\n * before `CompleteNameDialog`, an invitee) shows its address once, as the name.\n *\n * Both lines carry `data-private`, so keksdose's demo blur reaches them.\n */\nexport function UserIdentityCell({\n person,\n name,\n email,\n avatar = true,\n badge,\n locale: localeProp,\n className,\n}: UserIdentityCellProps) {\n const locale = useKitLocale(localeProp);\n const named = personLabel({ first: person?.first, last: person?.last, name }, locale);\n const address = (email ?? \"\").trim();\n return (\n <div className={cn(\"flex min-w-0 items-center gap-2.5\", className)}>\n {avatar && <UserAvatar person={person} name={name} email={email} size=\"sm\" />}\n <div className=\"min-w-0\">\n <div className=\"flex min-w-0 items-center gap-1.5\">\n <span data-private className=\"truncate font-medium text-[var(--text-primary)]\">\n {named || address}\n </span>\n {badge}\n </div>\n {named && address && (\n <div data-private className=\"truncate text-xs text-[var(--text-muted)]\">\n {address}\n </div>\n )}\n </div>\n </div>\n );\n}\n\n/* ── The row's actions ──────────────────────────────────────────────────────── */\n\n/** One entry of a row's action menu (§4). */\nexport interface UserRowAction {\n /** React key. Default: the label. */\n key?: string;\n label: string;\n /** Runs it — usually opens `AdminActionConfirm` with the level the server states. */\n onSelect: () => void;\n icon?: LucideIcon;\n /** `danger` for deactivate, transfer, erase. */\n tone?: \"default\" | \"danger\";\n /** Why it is not available for this row (\"You can’t deactivate yourself\"). The entry\n * stays in the menu, focusable, and says so — an action that silently vanished\n * would leave the admin looking for it. */\n disabledReason?: ReactNode;\n /** Leave it out for this row. */\n hidden?: boolean;\n}\n\n/** What `actions(row)` may return: entries, and `false` / `null` for the ones a\n * condition left out (`row.is_active && {…}`). */\nexport type UserRowActionList = readonly (UserRowAction | false | null | undefined)[];\n\nexport interface UserRowActionsProps {\n actions: UserRowActionList;\n /** The account's name, for the menu's name — \"Actions for Ada Example\". */\n name: string;\n labels?: Partial<UserRosterLabels>;\n}\n\n/**\n * A row's actions as one \"…\" button and a menu of them: keksdose had a strip of icon\n * buttons in the expanded row, Kurvenschmiede five text buttons in a cell — neither fits\n * a phone card, and both grow with every action §2.4 adds. The menu is portalled, so a\n * table's scroller cannot clip it; Escape and an outside press close it, and focus goes\n * back to the button, which is where a confirmation dialog then returns it.\n */\nexport function UserRowActions({ actions, name, labels: labelsProp }: UserRowActionsProps) {\n const labels = useKitLabels(\"userRoster\", DEFAULT_USER_ROSTER_LABELS, labelsProp);\n const entries = actions.filter((a): a is UserRowAction => Boolean(a) && !(a as UserRowAction).hidden);\n if (entries.length === 0) return null;\n const title = labels.actionsFor(name);\n return (\n <Popover\n width={240}\n aria-label={title}\n className=\"p-1\"\n trigger={({ open, toggle, ref }) => (\n <IconButton\n ref={ref}\n size=\"xs\"\n label={title}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n stopPropagation\n onClick={toggle}\n >\n <MoreHorizontal />\n </IconButton>\n )}\n >\n {(close) => (\n <ul className=\"space-y-0.5\">\n {entries.map((action) => {\n const Icon = action.icon;\n return (\n <li key={action.key ?? action.label}>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n stretch\n tone={action.tone === \"danger\" ? \"danger\" : undefined}\n disabledReason={action.disabledReason}\n className=\"justify-start\"\n onClick={() => {\n close();\n action.onSelect();\n }}\n >\n {Icon && <Icon className=\"size-4 shrink-0\" aria-hidden />}\n {action.label}\n </Button>\n </li>\n );\n })}\n </ul>\n )}\n </Popover>\n );\n}\n\n/* ── The preset ─────────────────────────────────────────────────────────────── */\n\n/** How a row's role may be changed inline: `true`, or with reasons. */\nexport interface RoleEditing<R extends string> {\n /** Why the whole select is locked for this row — `\"self\"`, `\"last_admin\"`, or words. */\n disabledReason?: RoleLock;\n /** Why one role cannot be chosen for this row (a string: it goes inside an option). */\n optionDisabledReason?: (role: R) => string | undefined;\n /** The roles that may be chosen. Default: the whole vocabulary. */\n offered?: readonly R[];\n}\n\nexport interface UserRosterColumnsOptions<T extends UserRosterRow, R extends string = string> {\n /** The app's roles, as `RoleChip` reads them. */\n roles: RoleVocabulary<R>;\n /** The row's state chips. Default {@link adminUserStates}, which reads the contract's\n * fields (`is_active`, `email_verified`, `password_change_required_at`,\n * `deletion_scheduled_at`, `deletion_requested_at`). */\n stateOf?: (row: T) => readonly RosterState[];\n /** The app's own columns — keksdose's plan and key custody, Kurvenschmiede's owned\n * counts — after the dates, before the actions. */\n extra?: readonly DataTableColumn<T>[];\n /** The row's action menu (§4). Left out: no actions column. */\n actions?: (row: T) => UserRowActionList;\n /**\n * Whether this row's role is a select rather than a chip, and with which reasons.\n * Left out, or `false`: a chip. kastlan's several roles are never a select here — they\n * are a \"Manage roles\" action that opens `RolesEditor`.\n */\n editableRole?: (row: T) => boolean | RoleEditing<R>;\n /** A role was picked in a row's select. The app confirms (`acknowledge`) and sends it. */\n onRoleChange?: (row: T, role: R) => void;\n /** The row's role(s). Default `row.roles ?? row.role`. */\n roleOf?: (row: T) => R | readonly R[] | null | undefined;\n /** A separate, sortable \"Email\" column (the server's `email` sort key) beside the\n * identity. Default false: the address is under the name already. */\n emailColumn?: boolean;\n /** The words, already resolved. Default English; {@link useUserRosterColumns} reads\n * the provider's `userRoster` namespace. */\n labels?: Partial<UserRosterLabels>;\n}\n\nfunction rolesOf<T extends UserRosterRow, R extends string>(\n row: T,\n roleOf: UserRosterColumnsOptions<T, R>[\"roleOf\"],\n): R[] {\n const raw = roleOf ? roleOf(row) : ((row.roles ?? row.role) as R | readonly R[] | null | undefined);\n if (raw === null || raw === undefined || raw === \"\") return [];\n return typeof raw === \"string\" ? [raw as R] : [...(raw as readonly R[])];\n}\n\n/** The row's name in the reader's order — a component, because the order is the\n * READER's and the locale comes from the provider. */\nfunction RowName<T extends UserRosterRow>({ row, children }: { row: T; children: (name: string) => ReactNode }) {\n const locale = useKitLocale();\n const name = personLabel(\n { first: row.first_name, last: row.last_name, name: row.display_name, email: row.email },\n locale,\n );\n return <>{children(name)}</>;\n}\n\nfunction StateChips({ states }: { states: readonly RosterState[] }) {\n if (states.length === 0) return null;\n return (\n <div className=\"flex flex-wrap gap-1\">\n {states.map((entry) => {\n const spec = typeof entry === \"string\" ? { state: entry } : entry;\n return (\n <AccountStateChip key={spec.state} state={spec.state} date={spec.date} tone={spec.tone} size=\"xs\">\n {spec.label}\n </AccountStateChip>\n );\n })}\n </div>\n );\n}\n\n/**\n * The roster's columns, in the contract's order (§3.3):\n *\n * | key | cell | sort | phone |\n * |---|---|---|---|\n * | `name` | {@link UserIdentityCell} | last, first | the card's headline |\n * | `email` | the address (`emailColumn` only) | address | hidden |\n * | `role` | `RoleChip`(s), or {@link RoleSelect} where `editableRole` | role | field |\n * | `state` | `AccountStateChip`s from `stateOf` | — | field |\n * | `created` | `dateColumn` | instant | hidden |\n * | `last_login` | `dateColumn`, relative, \"Never\" | instant | field |\n * | …`extra` | the app's | the app's | the app's |\n * | `actions` | {@link UserRowActions} | — | field |\n *\n * Pure: hand it resolved words, or use {@link useUserRosterColumns}. The keys are stable,\n * so an app may drop or move a column (`columns.filter((c) => c.key !== \"created\")`).\n * Under `serverPagination` the `sortBy`s only make the headers clickable; the app sends\n * the sort ({@link userRosterSort}).\n */\nexport function userRosterColumns<T extends UserRosterRow, R extends string = string>({\n roles,\n stateOf = adminUserStates,\n extra = [],\n actions,\n editableRole,\n onRoleChange,\n roleOf,\n emailColumn = false,\n labels: labelsProp,\n}: UserRosterColumnsOptions<T, R>): DataTableColumn<T>[] {\n const labels: UserRosterLabels = { ...DEFAULT_USER_ROSTER_LABELS, ...labelsProp };\n const roleWords = (row: T) =>\n rolesOf(row, roleOf)\n .map((role) => roles[role]?.label ?? role)\n .join(\", \");\n const columns: DataTableColumn<T>[] = [\n {\n key: \"name\",\n header: labels.name,\n cell: (row) => (\n <UserIdentityCell\n person={{ first: row.first_name, last: row.last_name }}\n name={row.display_name}\n email={row.email}\n />\n ),\n // By last name, then first (auth §3.2), as the server sorts `name`.\n sortBy: (row) => `${row.last_name ?? \"\"} ${row.first_name ?? \"\"}`.trim().toLocaleLowerCase() || row.email,\n // Either part, in either order, or the address (auth §10.6).\n filterBy: (row) =>\n [row.first_name, row.last_name, row.last_name, row.first_name, row.display_name, row.email]\n .filter(Boolean)\n .join(\" \"),\n mobilePrimary: true,\n },\n ];\n if (emailColumn) {\n columns.push({\n key: \"email\",\n header: labels.email,\n className: \"whitespace-nowrap\",\n cell: (row) => (\n <span data-private className=\"text-[var(--text-secondary)]\">\n {row.email}\n </span>\n ),\n sortBy: (row) => row.email.toLowerCase(),\n filterBy: (row) => row.email,\n mobileHidden: true,\n });\n }\n columns.push(\n {\n key: \"role\",\n header: labels.role,\n cell: (row) => {\n const held = rolesOf(row, roleOf);\n const editing = held.length <= 1 ? editableRole?.(row) : false;\n if (editing && onRoleChange) {\n const rules: RoleEditing<R> = editing === true ? {} : editing;\n return (\n <RowName row={row}>\n {(name) => (\n <RoleSelect<R>\n size=\"sm\"\n name={name}\n value={held[0] ?? null}\n roles={roles}\n offered={rules.offered}\n disabledReason={rules.disabledReason}\n optionDisabledReason={rules.optionDisabledReason}\n onChange={(role) => onRoleChange(row, role)}\n />\n )}\n </RowName>\n );\n }\n if (held.length === 0) return null;\n return (\n <div className=\"flex flex-wrap gap-1\">\n {held.map((role) => (\n <RoleChip<R> key={role} value={role} roles={roles} size=\"xs\" />\n ))}\n </div>\n );\n },\n sortBy: roleWords,\n filter: {\n type: \"select\",\n getValue: (row) => rolesOf(row, roleOf)[0] ?? \"\",\n options: (Object.keys(roles) as R[]).map((value) => ({ value, label: roles[value].label })),\n },\n },\n {\n key: \"state\",\n header: labels.state,\n cell: (row) => <StateChips states={stateOf(row)} />,\n },\n dateColumn<T>({\n key: \"created\",\n header: labels.created,\n value: (row) => row.created_at ?? null,\n column: { mobileHidden: true },\n }),\n // How long ago rather than a date — the question is \"recently?\" — with the exact\n // time in a tooltip (keksdose's last-seen column, Kurvenschmiede's).\n dateColumn<T>({\n key: \"last_login\",\n header: labels.lastLogin,\n value: (row) => row.last_login_at ?? null,\n display: \"relative\",\n empty: labels.never,\n }),\n ...extra,\n );\n if (actions) {\n columns.push({\n key: \"actions\",\n header: <span className=\"sr-only\">{labels.actions}</span>,\n headerText: labels.actions,\n // The caller's own words only: the menu reads the provider's itself, and the\n // English defaults merged in above must not shadow them.\n cell: (row) => (\n <RowName row={row}>\n {(name) => <UserRowActions actions={actions(row)} name={name} labels={labelsProp} />}\n </RowName>\n ),\n className: \"w-px whitespace-nowrap text-end\",\n headClassName: \"w-px\",\n // The menu button keeps its own click: a row link must not wrap it.\n noRowLink: true,\n });\n }\n return columns;\n}\n\n/**\n * {@link userRosterColumns} with the `userRoster` words from the provider, memoised on\n * the options — pass stable callbacks (`useCallback`) and a module-level vocabulary, or\n * the columns are rebuilt on every render.\n */\nexport function useUserRosterColumns<T extends UserRosterRow, R extends string = string>({\n roles,\n stateOf,\n extra,\n actions,\n editableRole,\n onRoleChange,\n roleOf,\n emailColumn,\n labels: labelsProp,\n}: UserRosterColumnsOptions<T, R>): DataTableColumn<T>[] {\n const labels = useKitLabels(\"userRoster\", DEFAULT_USER_ROSTER_LABELS, labelsProp);\n return useMemo(\n () =>\n userRosterColumns<T, R>({\n roles,\n stateOf,\n extra,\n actions,\n editableRole,\n onRoleChange,\n roleOf,\n emailColumn,\n labels,\n }),\n [roles, stateOf, extra, actions, editableRole, onRoleChange, roleOf, emailColumn, labels],\n );\n}\n"],"mappings":";AAmMiB,SA0KR,UA1KQ,KAET,YAFS;AAnMjB,SAAS,eAAe;AAExB,SAAS,sBAAsB;AAE/B,SAAS,UAAU;AAGnB,SAAS,cAAc,oBAAoB;AAC3C,SAAS,kBAAkB,UAAU,kBAAkB;AAIvD,SAAS,mBAAmB;AAE5B,SAAS,eAAe;AACxB,SAAS,QAAQ,kBAAkB;AACnC,SAAS,kBAAkB;AAC3B,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB;AA6EpB,SAAS,gBAAgB,KAA0C;AACxE,QAAM,MAAqB,CAAC;AAC5B,MAAI,IAAI,yBAAyB,IAAI,uBAAuB;AAC1D,QAAI,KAAK,EAAE,OAAO,YAAY,MAAM,IAAI,yBAAyB,KAAK,CAAC;AAAA,EACzE,WAAW,IAAI,cAAc,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,MACX,eAAe;AAAA;AAAA,MAEf,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAOO,SAAS,qBAAyE;AAAA,EACvF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AACV,GAAyD;AACvD,QAAM,SAAS,aAAa,cAAc,4BAA4B,UAAU;AAChF,SAAO;AAAA,IACL,MACE,kBAAwB;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,IACH,CAAC,OAAO,SAAS,OAAO,SAAS,cAAc,cAAc,QAAQ,aAAa,MAAM;AAAA,EAC1F;AACF;","names":[]}
@@ -23,9 +23,36 @@
23
23
  * password would confirm a leaked one. It stays in the union only for a future server
24
24
  * step that is past the password (an admin view, a signed-in refresh) and may say so.
25
25
  */
26
- type AuthErrorCode = "invalid_credentials" | "registration_closed" | "email_taken" | "invitation_invalid" | "invitation_expired" | "token_invalid" | "account_inactive";
26
+ type AuthErrorCode = "invalid_credentials" | "registration_closed" | "email_taken" | "invitation_invalid" | "invitation_expired" | "token_invalid"
27
+ /** 0.29.1: a link that WAS valid and ran out (verification, reset) — keksdose's step-3
28
+ * refusals tell it from `token_invalid`, so a page can say "expired, ask for a new one". */
29
+ | "token_expired" | "account_inactive";
27
30
  /**
28
- * The {@link AuthErrorCode} an error carries, or `undefined` when it carries none.
31
+ * 0.30.0: the coded refusals of user administration and the account's own settings
32
+ * (docs/user-admin-harmonization.md §4, §6) — server-kit 0.4.0's `AccountErrorCode`,
33
+ * value for value. The same family of answer as the sign-in codes (`{detail, code}`,
34
+ * plus `companies` on kastlan's `last_admin`), read by the same {@link authErrorCode}.
35
+ *
36
+ * - `last_admin` — the action would leave no active admin: deactivating, demoting or
37
+ * deleting the last one (in kastlan, of a company; the answer names the `companies`).
38
+ * - `self_action` — an admin acting on their own account where that is never allowed.
39
+ * - `other_companies` — kastlan: the account belongs to other companies too, so a
40
+ * company admin may not deactivate it; "Remove from company" instead (§9.6).
41
+ * - `household_has_members` — keksdose's guard on a deletion request (§6.4).
42
+ * - `confirmation_required`, `confirmation_mismatch` — the action's confirmation level
43
+ * asked for a typed address (or a tick), and the request carried none, or another
44
+ * address (§4.2).
45
+ * - `password_incorrect` — the CURRENT password is wrong on a signed-in route (the email
46
+ * change, the deletion request). `400`, not `401`: an app's client reads a 401 as an
47
+ * ended session and signs the user out, the wrong answer to a typo. Every other one
48
+ * is a `409`.
49
+ */
50
+ type AccountErrorCode = "last_admin" | "self_action" | "other_companies" | "household_has_members" | "confirmation_required" | "confirmation_mismatch" | "password_incorrect";
51
+ /** Every code the kit reads: the sign-in refusals and the account ones (0.30.0). */
52
+ type KitErrorCode = AuthErrorCode | AccountErrorCode;
53
+ /**
54
+ * The code an error carries — an {@link AuthErrorCode}, or since 0.30.0 an
55
+ * {@link AccountErrorCode} — or `undefined` when it carries none.
29
56
  *
30
57
  * Reads the parsed response body wherever the apps' HTTP clients put it, without
31
58
  * depending on any of them:
@@ -42,7 +69,7 @@ type AuthErrorCode = "invalid_credentials" | "registration_closed" | "email_take
42
69
  * read as a refusal. The HTTP status is not checked: the code is the contract, and the
43
70
  * status differs per refusal (401, 403, 409, 410).
44
71
  */
45
- declare function authErrorCode(err: unknown): AuthErrorCode | undefined;
72
+ declare function authErrorCode(err: unknown): KitErrorCode | undefined;
46
73
  /**
47
74
  * Whether `err` is a coded auth refusal — any of them, or the one named:
48
75
  *
@@ -53,8 +80,60 @@ declare function authErrorCode(err: unknown): AuthErrorCode | undefined;
53
80
  *
54
81
  * The kit's `SignInForm` and `RegisterForm` call it on what their callbacks reject
55
82
  * with, so an app's `onSubmit` can simply let its client's error through. See
56
- * {@link authErrorCode} for the shapes it reads.
83
+ * {@link authErrorCode} for the shapes it reads. Since 0.30.0 it knows the account codes
84
+ * too: `isAuthError(err, "last_admin")`.
85
+ */
86
+ declare function isAuthError(err: unknown, code?: KitErrorCode): boolean;
87
+ /**
88
+ * Whether `err` is a throttled request — HTTP `429 Too Many Requests` (0.30.0, from the
89
+ * apps' 0.29 adoption: every app answered a throttled sign-in, sign-up or reset through
90
+ * its own `describeError`, with three wordings of one sentence).
91
+ *
92
+ * A throttle carries no `code` in the contract — the STATUS is the answer, set by the
93
+ * apps' limiters (server-kit's `AuthLimiters`, keksdose's per-IP limit) — so this reads
94
+ * the status, wherever the apps' HTTP clients put it, without depending on any of them:
95
+ *
96
+ * 1. `err.response.status` — axios (all three apps' clients);
97
+ * 2. `err.status` — ofetch's `FetchError`, the generated OpenAPI clients' `ApiError`, and
98
+ * a `Response` thrown as it came;
99
+ * 3. `err.statusCode` — ofetch's alias, and Node-style errors.
100
+ *
101
+ * There is no `rate_limited` code: keksdose answers its 429s uncoded, with a
102
+ * `Retry-After` header, and the status is the one signal every limiter gives.
103
+ *
104
+ * The kit's `SignInForm`, `RegisterForm`, `ForgotPasswordForm` and `ResetPasswordForm`
105
+ * call it AFTER the app's `describeError` — an app with words of its own keeps them —
106
+ * and before their generic failure, so "Too many attempts. Try again in 30 s." (with
107
+ * {@link retryAfterSeconds}) or "… Wait a moment and try again." needs no app code.
108
+ */
109
+ declare function isRateLimited(err: unknown): boolean;
110
+ /**
111
+ * How long a throttled request asks to wait, in whole seconds — its `Retry-After`
112
+ * header (0.30.0, keksdose: its 429s carry no code, only the header) — or `undefined`
113
+ * when there is none, or none that parses.
114
+ *
115
+ * Read where the apps' clients keep the response headers, without depending on any of
116
+ * them: `err.response.headers` (axios' `AxiosHeaders` or a plain record; ofetch's
117
+ * `FetchError.response`, a fetch `Headers`), then `err.headers` (a `Response` thrown as
118
+ * it came). The value is delta-seconds, or an HTTP date turned into seconds from `now`
119
+ * (default: the present moment) — never below 0.
120
+ *
121
+ * The forms hand it to their `rateLimited` label when {@link isRateLimited} is true:
122
+ * "Too many attempts. Try again in 30 s." — and, without one, "… Wait a moment and try
123
+ * again." A browser only exposes `Retry-After` to a cross-origin page when the server
124
+ * lists it in `Access-Control-Expose-Headers`.
125
+ */
126
+ declare function retryAfterSeconds(err: unknown, now?: number | Date): number | undefined;
127
+ /**
128
+ * The English of every `rateLimited` label (0.30.0): "Too many attempts. Try again in
129
+ * 30 s." with a wait under a minute, in whole minutes from one minute up (keksdose's
130
+ * reset throttle answers in hours, and "3600 s" is a number nobody reads), and "Wait a
131
+ * moment and try again." without one — or with a `0`.
132
+ *
133
+ * @internal The namespaces' English; not part of the barrel.
57
134
  */
58
- declare function isAuthError(err: unknown, code?: AuthErrorCode): boolean;
135
+ declare function englishRateLimited(seconds?: number): string;
136
+ /** "30 s", "2 min" — a wait in English, rounded up. @internal */
137
+ declare function englishWait(seconds: number): string;
59
138
 
60
- export { type AuthErrorCode, authErrorCode, isAuthError };
139
+ export { type AccountErrorCode, type AuthErrorCode, type KitErrorCode, authErrorCode, englishRateLimited, englishWait, isAuthError, isRateLimited, retryAfterSeconds };
@@ -6,7 +6,15 @@ const CODES = /* @__PURE__ */ new Set([
6
6
  "invitation_invalid",
7
7
  "invitation_expired",
8
8
  "token_invalid",
9
- "account_inactive"
9
+ "token_expired",
10
+ "account_inactive",
11
+ "last_admin",
12
+ "self_action",
13
+ "other_companies",
14
+ "household_has_members",
15
+ "confirmation_required",
16
+ "confirmation_mismatch",
17
+ "password_incorrect"
10
18
  ]);
11
19
  const isBag = (value) => typeof value === "object" && value !== null;
12
20
  function known(value) {
@@ -25,8 +33,60 @@ function isAuthError(err, code) {
25
33
  const found = authErrorCode(err);
26
34
  return found !== void 0 && (code === void 0 || found === code);
27
35
  }
36
+ function statusOf(value) {
37
+ return typeof value === "number" && Number.isInteger(value) ? value : void 0;
38
+ }
39
+ function isRateLimited(err) {
40
+ if (!isBag(err)) return false;
41
+ const response = err.response;
42
+ const status = (isBag(response) ? statusOf(response.status) : void 0) ?? statusOf(err.status) ?? statusOf(err.statusCode);
43
+ return status === 429;
44
+ }
45
+ function headerOf(headers, name) {
46
+ if (!isBag(headers)) return void 0;
47
+ if (typeof headers.get === "function") {
48
+ try {
49
+ const value = headers.get.call(headers, name);
50
+ if (value !== void 0 && value !== null) return value;
51
+ } catch {
52
+ }
53
+ }
54
+ for (const [key, value] of Object.entries(headers)) {
55
+ if (key.toLowerCase() === name) return value;
56
+ }
57
+ return void 0;
58
+ }
59
+ function parseRetryAfter(value, now) {
60
+ const raw = Array.isArray(value) ? value[0] : value;
61
+ if (typeof raw === "number") return Number.isFinite(raw) && raw >= 0 ? Math.ceil(raw) : void 0;
62
+ if (typeof raw !== "string") return void 0;
63
+ const text = raw.trim();
64
+ if (/^\d+$/.test(text)) return Number(text);
65
+ if (!/[a-z]/i.test(text)) return void 0;
66
+ const at = Date.parse(text);
67
+ if (Number.isNaN(at)) return void 0;
68
+ return Math.max(0, Math.ceil((at - now) / 1e3));
69
+ }
70
+ function retryAfterSeconds(err, now = Date.now()) {
71
+ if (!isBag(err)) return void 0;
72
+ const at = typeof now === "number" ? now : now.getTime();
73
+ const response = err.response;
74
+ const value = (isBag(response) ? headerOf(response.headers, "retry-after") : void 0) ?? headerOf(err.headers, "retry-after");
75
+ return value === void 0 ? void 0 : parseRetryAfter(value, at);
76
+ }
77
+ function englishRateLimited(seconds) {
78
+ if (!seconds || seconds <= 0) return "Too many attempts. Wait a moment and try again.";
79
+ return `Too many attempts. Try again in ${englishWait(seconds)}.`;
80
+ }
81
+ function englishWait(seconds) {
82
+ return seconds < 60 ? `${Math.ceil(seconds)} s` : `${Math.ceil(seconds / 60)} min`;
83
+ }
28
84
  export {
29
85
  authErrorCode,
30
- isAuthError
86
+ englishRateLimited,
87
+ englishWait,
88
+ isAuthError,
89
+ isRateLimited,
90
+ retryAfterSeconds
31
91
  };
32
92
  //# sourceMappingURL=auth-errors.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/auth-errors.ts"],"sourcesContent":["/**\n * The coded refusals of sign-in and sign-up (docs/auth-harmonization.md §5.2): every\n * refusal the auth routes answer carries a machine-readable `code`, and the pages\n * recognise the CODE, never the server's sentence.\n *\n * Today each app's pages print the server's `detail` string (keksdose's\n * `extractApiErrorMessage`), which is English on every locale and, on a credential\n * check, would be an account-enumeration oracle if it ever said more than one thing.\n * keksdose already keys one refusal on a code (`features/budgets/plan-limit.ts`,\n * `402 {detail, code: \"plan_budget_limit\"}`); §5.2 makes that the rule for auth. Each\n * app switches its server and its pages together (§9).\n *\n * - `invalid_credentials` — unknown address, wrong password AND deactivated account:\n * one answer, in the same time (§2.10). `401`.\n * - `registration_closed` — the sign-up gate refused the address. `403`.\n * - `email_taken` — an account with this address exists. `409`.\n * - `invitation_invalid`, `invitation_expired` — the `invite` token of a sign-up or an\n * accept (§4.4).\n * - `token_invalid` — a one-time token (reset, verification, a sign-in challenge) is\n * unknown, spent or expired.\n * - `account_inactive` — **no server answers it.** §2.10 decided that a deactivated\n * account gets `invalid_credentials`, because a separate answer after a correct\n * password would confirm a leaked one. It stays in the union only for a future server\n * step that is past the password (an admin view, a signed-in refresh) and may say so.\n */\nexport type AuthErrorCode =\n | \"invalid_credentials\"\n | \"registration_closed\"\n | \"email_taken\"\n | \"invitation_invalid\"\n | \"invitation_expired\"\n | \"token_invalid\"\n | \"account_inactive\";\n\nconst CODES: ReadonlySet<string> = new Set<AuthErrorCode>([\n \"invalid_credentials\",\n \"registration_closed\",\n \"email_taken\",\n \"invitation_invalid\",\n \"invitation_expired\",\n \"token_invalid\",\n \"account_inactive\",\n]);\n\ntype Bag = Record<string, unknown>;\n\nconst isBag = (value: unknown): value is Bag => typeof value === \"object\" && value !== null;\n\n/** A known code, or undefined. */\nfunction known(value: unknown): AuthErrorCode | undefined {\n return typeof value === \"string\" && CODES.has(value) ? (value as AuthErrorCode) : undefined;\n}\n\n/** `{code}` on a parsed body, or FastAPI's `{detail: {code}}` — what an\n * `HTTPException(detail={\"code\": …})` serialises to. */\nfunction codeOfBody(body: unknown): AuthErrorCode | undefined {\n if (!isBag(body)) return undefined;\n return known(body.code) ?? (isBag(body.detail) ? known(body.detail.code) : undefined);\n}\n\n/**\n * The {@link AuthErrorCode} an error carries, or `undefined` when it carries none.\n *\n * Reads the parsed response body wherever the apps' HTTP clients put it, without\n * depending on any of them:\n *\n * 1. `err.response.data` — axios (keksdose's, kastlan's and Kurvenschmiede's clients;\n * keksdose's `isPlanBudgetLimitRefusal` reads the same path);\n * 2. `err.data` — ofetch's `FetchError`, and most `fetch` wrappers that parse the body;\n * 3. `err.body` — the generated OpenAPI clients' `ApiError`;\n * 4. `err` itself — a body thrown as it came (`throw await res.json()`).\n *\n * In each, `code` or FastAPI's nested `detail.code`. Last, `err.code` — but only when\n * it is one of the codes above: axios writes its OWN codes there (`ERR_NETWORK`,\n * `ECONNABORTED`, `ERR_BAD_REQUEST`), and so does Node, so an unknown value is never\n * read as a refusal. The HTTP status is not checked: the code is the contract, and the\n * status differs per refusal (401, 403, 409, 410).\n */\nexport function authErrorCode(err: unknown): AuthErrorCode | undefined {\n if (!isBag(err)) return undefined;\n const response = err.response;\n return (\n (isBag(response) ? codeOfBody(response.data) : undefined) ??\n codeOfBody(err.data) ??\n codeOfBody(err.body) ??\n codeOfBody(err)\n );\n}\n\n/**\n * Whether `err` is a coded auth refusal — any of them, or the one named:\n *\n * ```ts\n * try { await api.register(values) }\n * catch (err) { if (isAuthError(err, \"email_taken\")) … }\n * ```\n *\n * The kit's `SignInForm` and `RegisterForm` call it on what their callbacks reject\n * with, so an app's `onSubmit` can simply let its client's error through. See\n * {@link authErrorCode} for the shapes it reads.\n */\nexport function isAuthError(err: unknown, code?: AuthErrorCode): boolean {\n const found = authErrorCode(err);\n return found !== undefined && (code === undefined || found === code);\n}\n"],"mappings":";AAkCA,MAAM,QAA6B,oBAAI,IAAmB;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,QAAQ,CAAC,UAAiC,OAAO,UAAU,YAAY,UAAU;AAGvF,SAAS,MAAM,OAA2C;AACxD,SAAO,OAAO,UAAU,YAAY,MAAM,IAAI,KAAK,IAAK,QAA0B;AACpF;AAIA,SAAS,WAAW,MAA0C;AAC5D,MAAI,CAAC,MAAM,IAAI,EAAG,QAAO;AACzB,SAAO,MAAM,KAAK,IAAI,MAAM,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,OAAO,IAAI,IAAI;AAC7E;AAoBO,SAAS,cAAc,KAAyC;AACrE,MAAI,CAAC,MAAM,GAAG,EAAG,QAAO;AACxB,QAAM,WAAW,IAAI;AACrB,UACG,MAAM,QAAQ,IAAI,WAAW,SAAS,IAAI,IAAI,WAC/C,WAAW,IAAI,IAAI,KACnB,WAAW,IAAI,IAAI,KACnB,WAAW,GAAG;AAElB;AAcO,SAAS,YAAY,KAAc,MAA+B;AACvE,QAAM,QAAQ,cAAc,GAAG;AAC/B,SAAO,UAAU,WAAc,SAAS,UAAa,UAAU;AACjE;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/auth-errors.ts"],"sourcesContent":["/**\n * The coded refusals of sign-in and sign-up (docs/auth-harmonization.md §5.2): every\n * refusal the auth routes answer carries a machine-readable `code`, and the pages\n * recognise the CODE, never the server's sentence.\n *\n * Today each app's pages print the server's `detail` string (keksdose's\n * `extractApiErrorMessage`), which is English on every locale and, on a credential\n * check, would be an account-enumeration oracle if it ever said more than one thing.\n * keksdose already keys one refusal on a code (`features/budgets/plan-limit.ts`,\n * `402 {detail, code: \"plan_budget_limit\"}`); §5.2 makes that the rule for auth. Each\n * app switches its server and its pages together (§9).\n *\n * - `invalid_credentials` — unknown address, wrong password AND deactivated account:\n * one answer, in the same time (§2.10). `401`.\n * - `registration_closed` — the sign-up gate refused the address. `403`.\n * - `email_taken` — an account with this address exists. `409`.\n * - `invitation_invalid`, `invitation_expired` — the `invite` token of a sign-up or an\n * accept (§4.4).\n * - `token_invalid` — a one-time token (reset, verification, a sign-in challenge) is\n * unknown, spent or expired.\n * - `account_inactive` — **no server answers it.** §2.10 decided that a deactivated\n * account gets `invalid_credentials`, because a separate answer after a correct\n * password would confirm a leaked one. It stays in the union only for a future server\n * step that is past the password (an admin view, a signed-in refresh) and may say so.\n */\nexport type AuthErrorCode =\n | \"invalid_credentials\"\n | \"registration_closed\"\n | \"email_taken\"\n | \"invitation_invalid\"\n | \"invitation_expired\"\n | \"token_invalid\"\n /** 0.29.1: a link that WAS valid and ran out (verification, reset) — keksdose's step-3\n * refusals tell it from `token_invalid`, so a page can say \"expired, ask for a new one\". */\n | \"token_expired\"\n | \"account_inactive\";\n\n/**\n * 0.30.0: the coded refusals of user administration and the account's own settings\n * (docs/user-admin-harmonization.md §4, §6) — server-kit 0.4.0's `AccountErrorCode`,\n * value for value. The same family of answer as the sign-in codes (`{detail, code}`,\n * plus `companies` on kastlan's `last_admin`), read by the same {@link authErrorCode}.\n *\n * - `last_admin` — the action would leave no active admin: deactivating, demoting or\n * deleting the last one (in kastlan, of a company; the answer names the `companies`).\n * - `self_action` — an admin acting on their own account where that is never allowed.\n * - `other_companies` — kastlan: the account belongs to other companies too, so a\n * company admin may not deactivate it; \"Remove from company\" instead (§9.6).\n * - `household_has_members` — keksdose's guard on a deletion request (§6.4).\n * - `confirmation_required`, `confirmation_mismatch` — the action's confirmation level\n * asked for a typed address (or a tick), and the request carried none, or another\n * address (§4.2).\n * - `password_incorrect` — the CURRENT password is wrong on a signed-in route (the email\n * change, the deletion request). `400`, not `401`: an app's client reads a 401 as an\n * ended session and signs the user out, the wrong answer to a typo. Every other one\n * is a `409`.\n */\nexport type AccountErrorCode =\n | \"last_admin\"\n | \"self_action\"\n | \"other_companies\"\n | \"household_has_members\"\n | \"confirmation_required\"\n | \"confirmation_mismatch\"\n | \"password_incorrect\";\n\n/** Every code the kit reads: the sign-in refusals and the account ones (0.30.0). */\nexport type KitErrorCode = AuthErrorCode | AccountErrorCode;\n\nconst CODES: ReadonlySet<string> = new Set<KitErrorCode>([\n \"invalid_credentials\",\n \"registration_closed\",\n \"email_taken\",\n \"invitation_invalid\",\n \"invitation_expired\",\n \"token_invalid\",\n \"token_expired\",\n \"account_inactive\",\n \"last_admin\",\n \"self_action\",\n \"other_companies\",\n \"household_has_members\",\n \"confirmation_required\",\n \"confirmation_mismatch\",\n \"password_incorrect\",\n]);\n\ntype Bag = Record<string, unknown>;\n\nconst isBag = (value: unknown): value is Bag => typeof value === \"object\" && value !== null;\n\n/** A known code, or undefined. */\nfunction known(value: unknown): KitErrorCode | undefined {\n return typeof value === \"string\" && CODES.has(value) ? (value as KitErrorCode) : undefined;\n}\n\n/** `{code}` on a parsed body, or FastAPI's `{detail: {code}}` — what an\n * `HTTPException(detail={\"code\": …})` serialises to. */\nfunction codeOfBody(body: unknown): KitErrorCode | undefined {\n if (!isBag(body)) return undefined;\n return known(body.code) ?? (isBag(body.detail) ? known(body.detail.code) : undefined);\n}\n\n/**\n * The code an error carries — an {@link AuthErrorCode}, or since 0.30.0 an\n * {@link AccountErrorCode} — or `undefined` when it carries none.\n *\n * Reads the parsed response body wherever the apps' HTTP clients put it, without\n * depending on any of them:\n *\n * 1. `err.response.data` — axios (keksdose's, kastlan's and Kurvenschmiede's clients;\n * keksdose's `isPlanBudgetLimitRefusal` reads the same path);\n * 2. `err.data` — ofetch's `FetchError`, and most `fetch` wrappers that parse the body;\n * 3. `err.body` — the generated OpenAPI clients' `ApiError`;\n * 4. `err` itself — a body thrown as it came (`throw await res.json()`).\n *\n * In each, `code` or FastAPI's nested `detail.code`. Last, `err.code` — but only when\n * it is one of the codes above: axios writes its OWN codes there (`ERR_NETWORK`,\n * `ECONNABORTED`, `ERR_BAD_REQUEST`), and so does Node, so an unknown value is never\n * read as a refusal. The HTTP status is not checked: the code is the contract, and the\n * status differs per refusal (401, 403, 409, 410).\n */\nexport function authErrorCode(err: unknown): KitErrorCode | undefined {\n if (!isBag(err)) return undefined;\n const response = err.response;\n return (\n (isBag(response) ? codeOfBody(response.data) : undefined) ??\n codeOfBody(err.data) ??\n codeOfBody(err.body) ??\n codeOfBody(err)\n );\n}\n\n/**\n * Whether `err` is a coded auth refusal — any of them, or the one named:\n *\n * ```ts\n * try { await api.register(values) }\n * catch (err) { if (isAuthError(err, \"email_taken\")) … }\n * ```\n *\n * The kit's `SignInForm` and `RegisterForm` call it on what their callbacks reject\n * with, so an app's `onSubmit` can simply let its client's error through. See\n * {@link authErrorCode} for the shapes it reads. Since 0.30.0 it knows the account codes\n * too: `isAuthError(err, \"last_admin\")`.\n */\nexport function isAuthError(err: unknown, code?: KitErrorCode): boolean {\n const found = authErrorCode(err);\n return found !== undefined && (code === undefined || found === code);\n}\n\n/** An HTTP status as a number, or undefined. */\nfunction statusOf(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isInteger(value) ? value : undefined;\n}\n\n/**\n * Whether `err` is a throttled request — HTTP `429 Too Many Requests` (0.30.0, from the\n * apps' 0.29 adoption: every app answered a throttled sign-in, sign-up or reset through\n * its own `describeError`, with three wordings of one sentence).\n *\n * A throttle carries no `code` in the contract — the STATUS is the answer, set by the\n * apps' limiters (server-kit's `AuthLimiters`, keksdose's per-IP limit) — so this reads\n * the status, wherever the apps' HTTP clients put it, without depending on any of them:\n *\n * 1. `err.response.status` — axios (all three apps' clients);\n * 2. `err.status` — ofetch's `FetchError`, the generated OpenAPI clients' `ApiError`, and\n * a `Response` thrown as it came;\n * 3. `err.statusCode` — ofetch's alias, and Node-style errors.\n *\n * There is no `rate_limited` code: keksdose answers its 429s uncoded, with a\n * `Retry-After` header, and the status is the one signal every limiter gives.\n *\n * The kit's `SignInForm`, `RegisterForm`, `ForgotPasswordForm` and `ResetPasswordForm`\n * call it AFTER the app's `describeError` — an app with words of its own keeps them —\n * and before their generic failure, so \"Too many attempts. Try again in 30 s.\" (with\n * {@link retryAfterSeconds}) or \"… Wait a moment and try again.\" needs no app code.\n */\nexport function isRateLimited(err: unknown): boolean {\n if (!isBag(err)) return false;\n const response = err.response;\n const status =\n (isBag(response) ? statusOf(response.status) : undefined) ?? statusOf(err.status) ?? statusOf(err.statusCode);\n return status === 429;\n}\n\n/** A header's value from a `Headers` (fetch, ofetch's `response`), axios' `AxiosHeaders`\n * or a plain record — whose keys may come in any case. */\nfunction headerOf(headers: unknown, name: string): unknown {\n if (!isBag(headers)) return undefined;\n if (typeof headers.get === \"function\") {\n try {\n const value: unknown = (headers.get as (key: string) => unknown).call(headers, name);\n if (value !== undefined && value !== null) return value;\n } catch {\n // A `get` that is not a header lookup; the record below is.\n }\n }\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) return value;\n }\n return undefined;\n}\n\n/** `Retry-After` as seconds from `now`: delta-seconds (\"30\"), or an HTTP date\n * (\"Wed, 07 Oct 2026 10:00:00 GMT\") counted from now, never below 0 (RFC 9110 §10.2.3). */\nfunction parseRetryAfter(value: unknown, now: number): number | undefined {\n const raw = Array.isArray(value) ? (value as unknown[])[0] : value;\n if (typeof raw === \"number\") return Number.isFinite(raw) && raw >= 0 ? Math.ceil(raw) : undefined;\n if (typeof raw !== \"string\") return undefined;\n const text = raw.trim();\n if (/^\\d+$/.test(text)) return Number(text);\n // An HTTP date names its day and month (\"Wed, 07 Oct 2026 …\"). Without a letter it is\n // a malformed number (\"-5\", \"1.5\"), which `Date.parse` would happily read as a year.\n if (!/[a-z]/i.test(text)) return undefined;\n const at = Date.parse(text);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, Math.ceil((at - now) / 1000));\n}\n\n/**\n * How long a throttled request asks to wait, in whole seconds — its `Retry-After`\n * header (0.30.0, keksdose: its 429s carry no code, only the header) — or `undefined`\n * when there is none, or none that parses.\n *\n * Read where the apps' clients keep the response headers, without depending on any of\n * them: `err.response.headers` (axios' `AxiosHeaders` or a plain record; ofetch's\n * `FetchError.response`, a fetch `Headers`), then `err.headers` (a `Response` thrown as\n * it came). The value is delta-seconds, or an HTTP date turned into seconds from `now`\n * (default: the present moment) — never below 0.\n *\n * The forms hand it to their `rateLimited` label when {@link isRateLimited} is true:\n * \"Too many attempts. Try again in 30 s.\" — and, without one, \"… Wait a moment and try\n * again.\" A browser only exposes `Retry-After` to a cross-origin page when the server\n * lists it in `Access-Control-Expose-Headers`.\n */\nexport function retryAfterSeconds(err: unknown, now: number | Date = Date.now()): number | undefined {\n if (!isBag(err)) return undefined;\n const at = typeof now === \"number\" ? now : now.getTime();\n const response = err.response;\n const value =\n (isBag(response) ? headerOf(response.headers, \"retry-after\") : undefined) ?? headerOf(err.headers, \"retry-after\");\n return value === undefined ? undefined : parseRetryAfter(value, at);\n}\n\n/**\n * The English of every `rateLimited` label (0.30.0): \"Too many attempts. Try again in\n * 30 s.\" with a wait under a minute, in whole minutes from one minute up (keksdose's\n * reset throttle answers in hours, and \"3600 s\" is a number nobody reads), and \"Wait a\n * moment and try again.\" without one — or with a `0`.\n *\n * @internal The namespaces' English; not part of the barrel.\n */\nexport function englishRateLimited(seconds?: number): string {\n if (!seconds || seconds <= 0) return \"Too many attempts. Wait a moment and try again.\";\n return `Too many attempts. Try again in ${englishWait(seconds)}.`;\n}\n\n/** \"30 s\", \"2 min\" — a wait in English, rounded up. @internal */\nexport function englishWait(seconds: number): string {\n return seconds < 60 ? `${Math.ceil(seconds)} s` : `${Math.ceil(seconds / 60)} min`;\n}\n"],"mappings":";AAqEA,MAAM,QAA6B,oBAAI,IAAkB;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,QAAQ,CAAC,UAAiC,OAAO,UAAU,YAAY,UAAU;AAGvF,SAAS,MAAM,OAA0C;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,IAAI,KAAK,IAAK,QAAyB;AACnF;AAIA,SAAS,WAAW,MAAyC;AAC3D,MAAI,CAAC,MAAM,IAAI,EAAG,QAAO;AACzB,SAAO,MAAM,KAAK,IAAI,MAAM,MAA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O,OAAO,SAAS,GAAG,KAAK,OAAO,IAAI,KAAK,KAAK,GAAG,IAAI;AACxF,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,OAAO,IAAI,KAAK;AACtB,MAAI,QAAQ,KAAK,IAAI,EAAG,QAAO,OAAO,IAAI;AAG1C,MAAI,CAAC,SAAS,KAAK,IAAI,EAAG,QAAO;AACjC,QAAM,KAAK,KAAK,MAAM,IAAI;AAC1B,MAAI,OAAO,MAAM,EAAE,EAAG,QAAO;AAC7B,SAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,OAAO,GAAI,CAAC;AACjD;AAkBO,SAAS,kBAAkB,KAAc,MAAqB,KAAK,IAAI,GAAuB;AACnG,MAAI,CAAC,MAAM,GAAG,EAAG,QAAO;AACxB,QAAM,KAAK,OAAO,QAAQ,WAAW,MAAM,IAAI,QAAQ;AACvD,QAAM,WAAW,IAAI;AACrB,QAAM,SACH,MAAM,QAAQ,IAAI,SAAS,SAAS,SAAS,aAAa,IAAI,WAAc,SAAS,IAAI,SAAS,aAAa;AAClH,SAAO,UAAU,SAAY,SAAY,gBAAgB,OAAO,EAAE;AACpE;AAUO,SAAS,mBAAmB,SAA0B;AAC3D,MAAI,CAAC,WAAW,WAAW,EAAG,QAAO;AACrC,SAAO,mCAAmC,YAAY,OAAO,CAAC;AAChE;AAGO,SAAS,YAAY,SAAyB;AACnD,SAAO,UAAU,KAAK,GAAG,KAAK,KAAK,OAAO,CAAC,OAAO,GAAG,KAAK,KAAK,UAAU,EAAE,CAAC;AAC9E;","names":[]}
@@ -21,8 +21,14 @@ interface ForgotPasswordLabels {
21
21
  /** A request that did not go through: a throttle, an outage. Never "unknown
22
22
  * address" — the endpoint does not say. */
23
23
  error: string;
24
+ /** 0.30.0: the request was throttled — HTTP 429 ({@link isRateLimited}) — given the
25
+ * `Retry-After` wait in seconds, or `undefined` without one. OPTIONAL, like every key
26
+ * added to a shipped interface; the provider's `forgotPassword`, then English, fill
27
+ * it. */
28
+ rateLimited?: (seconds?: number) => string;
24
29
  }
25
- declare const DEFAULT_FORGOT_PASSWORD_LABELS: ForgotPasswordLabels;
30
+ /** `Required`: every key, the 0.30 one included, has its English here. */
31
+ declare const DEFAULT_FORGOT_PASSWORD_LABELS: Required<ForgotPasswordLabels>;
26
32
  interface ForgotPasswordFormProps extends Omit<ComponentPropsWithoutRef<"div">, "onSubmit" | "children" | "title"> {
27
33
  /**
28
34
  * The address was submitted, trimmed: send `POST /auth/password-reset/request`.
@@ -38,8 +44,9 @@ interface ForgotPasswordFormProps extends Omit<ComponentPropsWithoutRef<"div">,
38
44
  * whose password just failed need not type it twice. */
39
45
  defaultEmail?: string;
40
46
  /**
41
- * The app's words for a failed request (a `429`: "Too many requests — try again in
42
- * an hour"), or `undefined` for the kit's `error`. The same hook as `SignInForm`'s.
47
+ * The app's words for a failed request ("Too many requests — try again in an hour"),
48
+ * or `undefined` for the kit's: `rateLimited` for a bare `429` (0.30.0), else `error`.
49
+ * The same hook as `SignInForm`'s.
43
50
  */
44
51
  describeError?: (error: unknown) => ReactNode | undefined;
45
52
  /** App content under the intro — a notice, a support address. */