@krak-stack/auth 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +26 -7
  2. package/dist/backend/api.d.ts +80 -6
  3. package/dist/backend/api.d.ts.map +1 -1
  4. package/dist/backend/api.js +31 -4
  5. package/dist/backend/api.js.map +1 -1
  6. package/dist/backend/index.d.ts +100 -41
  7. package/dist/backend/index.d.ts.map +1 -1
  8. package/dist/backend/index.js +5 -12
  9. package/dist/backend/index.js.map +1 -1
  10. package/dist/backend/schema.d.ts +12 -1
  11. package/dist/backend/schema.d.ts.map +1 -1
  12. package/dist/backend/schema.js +11 -3
  13. package/dist/backend/schema.js.map +1 -1
  14. package/dist/components/index.d.ts +3 -0
  15. package/dist/components/index.d.ts.map +1 -0
  16. package/dist/components/index.js +3 -0
  17. package/dist/components/index.js.map +1 -0
  18. package/dist/components/organization-switcher.d.ts +11 -0
  19. package/dist/components/organization-switcher.d.ts.map +1 -0
  20. package/dist/components/organization-switcher.js +569 -0
  21. package/dist/components/organization-switcher.js.map +1 -0
  22. package/dist/components/user-button.d.ts +11 -0
  23. package/dist/components/user-button.d.ts.map +1 -0
  24. package/dist/components/user-button.js +613 -0
  25. package/dist/components/user-button.js.map +1 -0
  26. package/dist/frontend/api.d.ts +18 -2
  27. package/dist/frontend/api.d.ts.map +1 -1
  28. package/dist/frontend/index.d.ts +35 -11
  29. package/dist/frontend/index.d.ts.map +1 -1
  30. package/dist/frontend/index.js +4 -4
  31. package/dist/frontend/index.js.map +1 -1
  32. package/dist/frontend/schema.d.ts +9 -1
  33. package/dist/frontend/schema.d.ts.map +1 -1
  34. package/dist/index.d.ts +2 -2
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +2 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/schema.d.ts +29 -1
  39. package/dist/schema.d.ts.map +1 -1
  40. package/dist/schema.js +61 -2
  41. package/dist/schema.js.map +1 -1
  42. package/package.json +13 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"organization-switcher.d.ts","sourceRoot":"","sources":["../../src/components/organization-switcher.tsx"],"names":[],"mappings":"AAaA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,SAAS,EAIf,MAAM,OAAO,CAAC;AAoBf,OAAO,EAEL,mBAAmB,EAMpB,MAAM,+BAA+B,CAAC;AAmBvC,KAAK,yBAAyB,GAAG;IAC/B,IAAI,CAAC,EAAE,cAAc,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qBAAqB,CAAC,EAAE,MAAM,SAAS,CAAC;IACxC,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AA8NF,wBAAgB,oBAAoB,CAAC,EACnC,IAAe,EACf,SAAS,EACT,qBAAqB,EACrB,MAAc,GACf,EAAE,yBAAyB,+BA8P3B"}
@@ -0,0 +1,569 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import {} from "@tanstack/react-table";
3
+ import { Schema } from "effect";
4
+ import { Building2, ChevronsUpDown, KeyRound, PencilIcon, Trash2, UserPlus, Users, } from "lucide-react";
5
+ import { useEffect, useEffectEvent, useState, } from "react";
6
+ import { createDataTableActionsColumn, DataTable, } from "@/components/ui/data-table";
7
+ import { EditingLocaleSwitcher, } from "@/components/ui/editing-locale-switcher";
8
+ import { AppBrand } from "@/components/ui/app-brand";
9
+ import { useAppForm } from "@/components/ui/form";
10
+ import { Badge } from "@/components/ui/badge";
11
+ import { Button } from "@/components/ui/button";
12
+ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
13
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu";
14
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
15
+ import { Separator } from "@/components/ui/separator";
16
+ import { cn } from "@/lib/utils";
17
+ import { m } from "@/paraglide/messages";
18
+ import { getLocale } from "@/paraglide/runtime";
19
+ import { centralAuthClient } from "@/services/auth/client/central";
20
+ import { OrganizationMetadata, } from "@krak-stack/auth/schema";
21
+ const slugify = (value) => value
22
+ .trim()
23
+ .toLowerCase()
24
+ .replace(/[^a-z0-9]+/g, "-")
25
+ .replace(/^-+|-+$/g, "");
26
+ const nullableString = (value) => typeof value === "string" && value.trim() ? value.trim() : null;
27
+ const centralAuthUrl = (path) => new URL(path, import.meta.env.VITE_KRAKSTACK_AUTH_URL).toString();
28
+ const parsePresignedUpload = (value) => {
29
+ if (!isRecord(value) ||
30
+ typeof value.uploadUrl !== "string" ||
31
+ typeof value.url !== "string") {
32
+ throw new Error(m.organization_logo_upload_error());
33
+ }
34
+ return { uploadUrl: value.uploadUrl, url: value.url };
35
+ };
36
+ const isRecord = (value) => typeof value === "object" && value !== null;
37
+ const uploadOrganizationLogo = async (file) => {
38
+ const contentType = file.type || "image/png";
39
+ const presignResponse = await fetch(centralAuthUrl("/api/organizations/logo/presign"), {
40
+ method: "POST",
41
+ credentials: "include",
42
+ headers: { "Content-Type": "application/json" },
43
+ body: JSON.stringify({ fileName: file.name, contentType }),
44
+ });
45
+ if (!presignResponse.ok) {
46
+ throw new Error(m.organization_logo_upload_error());
47
+ }
48
+ const presigned = parsePresignedUpload(await presignResponse.json());
49
+ const uploadResponse = await fetch(presigned.uploadUrl, {
50
+ method: "PUT",
51
+ headers: { "Content-Type": contentType },
52
+ body: file,
53
+ });
54
+ if (!uploadResponse.ok) {
55
+ throw new Error(m.organization_logo_upload_error());
56
+ }
57
+ return centralAuthUrl(presigned.url);
58
+ };
59
+ const currentOrganizationLocale = () => getLocale() === "fr" ? "fr" : "en";
60
+ const parseOrganizationMetadata = (metadata) => {
61
+ try {
62
+ return Schema.decodeUnknownSync(OrganizationMetadata)(metadata);
63
+ }
64
+ catch {
65
+ return { translations: [] };
66
+ }
67
+ };
68
+ const findOrganizationTranslation = (organization, locale = currentOrganizationLocale()) => {
69
+ const translations = parseOrganizationMetadata(organization.metadata).translations;
70
+ return (translations.find((translation) => translation.locale === locale) ??
71
+ translations.find((translation) => translation.locale === "en") ??
72
+ translations[0]);
73
+ };
74
+ const organizationDisplay = (organization) => {
75
+ const translation = organization
76
+ ? findOrganizationTranslation(organization)
77
+ : undefined;
78
+ return {
79
+ name: translation?.name ||
80
+ organization?.name ||
81
+ m.organization_switcher_label(),
82
+ subtitle: organization?.slug ?? m.organization_switcher_label(),
83
+ logo: translation?.logo || undefined,
84
+ };
85
+ };
86
+ const organizationFormDefaults = (organization) => {
87
+ const translations = parseOrganizationMetadata(organization?.metadata).translations;
88
+ const en = translations.find((translation) => translation.locale === "en");
89
+ const fr = translations.find((translation) => translation.locale === "fr");
90
+ return {
91
+ name: organization?.name ?? "",
92
+ slug: organization?.slug ?? "",
93
+ enName: en?.name || organization?.name || "",
94
+ enLogo: null,
95
+ enLogoUrl: en?.logo ?? "",
96
+ enContactEmail: en?.contactEmail ?? "",
97
+ enLocation: en?.location ?? "",
98
+ frName: fr?.name ?? "",
99
+ frLogo: null,
100
+ frLogoUrl: fr?.logo ?? "",
101
+ frContactEmail: fr?.contactEmail ?? "",
102
+ frLocation: fr?.location ?? "",
103
+ };
104
+ };
105
+ const organizationLogoFromForm = async (file, fallback) => file ? await uploadOrganizationLogo(file) : nullableString(fallback);
106
+ const organizationRoles = ["owner", "admin", "member"];
107
+ const normalizeOrganizationRole = (role) => role === "owner" || role === "admin" || role === "member" ? role : "member";
108
+ const organizationRoleLabel = (role) => {
109
+ switch (normalizeOrganizationRole(role)) {
110
+ case "owner":
111
+ return m.organization_role_owner();
112
+ case "admin":
113
+ return m.organization_role_admin();
114
+ case "member":
115
+ return m.organization_role_member();
116
+ }
117
+ };
118
+ const formatOrganizationDate = (date) => new Intl.DateTimeFormat(getLocale(), { dateStyle: "medium" }).format(new Date(date));
119
+ const initialsFromName = (name) => name
120
+ .trim()
121
+ .split(/\s+/)
122
+ .slice(0, 2)
123
+ .map((part) => part[0])
124
+ .join("")
125
+ .toUpperCase() || "?";
126
+ const organizationMetadataFromForm = async (value) => {
127
+ const translations = [];
128
+ const enName = value.enName.trim() || value.name.trim();
129
+ const frName = value.frName.trim();
130
+ const enLogo = await organizationLogoFromForm(value.enLogo, value.enLogoUrl);
131
+ const frLogo = await organizationLogoFromForm(value.frLogo, value.frLogoUrl);
132
+ if (enName) {
133
+ translations.push({
134
+ locale: "en",
135
+ name: enName,
136
+ logo: enLogo,
137
+ contactEmail: nullableString(value.enContactEmail),
138
+ location: nullableString(value.enLocation),
139
+ });
140
+ }
141
+ if (frName) {
142
+ translations.push({
143
+ locale: "fr",
144
+ name: frName,
145
+ logo: frLogo,
146
+ contactEmail: nullableString(value.frContactEmail),
147
+ location: nullableString(value.frLocation),
148
+ });
149
+ }
150
+ return { translations };
151
+ };
152
+ export function OrganizationSwitcher({ side = "bottom", className, renderUnauthenticated, locked = false, }) {
153
+ const session = centralAuthClient.useSession();
154
+ const organizations = centralAuthClient.useListOrganizations();
155
+ const activeOrganization = centralAuthClient.useActiveOrganization();
156
+ const [dialog, setDialog] = useState(null);
157
+ if (!session.data) {
158
+ return _jsx(_Fragment, { children: renderUnauthenticated?.() });
159
+ }
160
+ const active = activeOrganization.data;
161
+ const activeName = active?.name;
162
+ const selectableOrganizations = !locked
163
+ ? (organizations.data?.filter((organization) => organization.id !== active?.id) ?? [])
164
+ : [];
165
+ const hasOrganizationListItems = organizations.isPending || Boolean(organizations.error) || !locked;
166
+ const refresh = async () => {
167
+ await organizations.refetch();
168
+ await activeOrganization.refetch();
169
+ };
170
+ const activeDisplay = organizationDisplay(active ?? null);
171
+ return (_jsxs(_Fragment, { children: [_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsxs(Button, { variant: "ghost", className: cn("h-11 w-full justify-between gap-2 !px-1 !py-0 group-data-[collapsible=icon]:size-8 group-data-[collapsible=icon]:justify-start group-data-[collapsible=icon]:!p-0", className), children: [_jsx(AppBrand, { to: null, label: activeName
172
+ ? activeDisplay.name
173
+ : m.organization_switcher_label(), subtitle: activeDisplay.subtitle, icon: Building2, variant: "sidebar", className: "min-w-0 flex-1 !p-0 text-left group-data-[collapsible=icon]:flex-none group-data-[collapsible=icon]:justify-start", ...(activeDisplay.logo
174
+ ? { imageSrc: activeDisplay.logo }
175
+ : {}) }), _jsx(ChevronsUpDown, { className: "text-muted-foreground size-4 shrink-0 group-data-[collapsible=icon]:hidden" })] }) }), _jsx(DropdownMenuContent, { className: "min-w-64 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: activeDisplay.name, subtitle: activeDisplay.subtitle, icon: Building2, variant: "sidebar", className: "px-1 py-1.5 text-left text-sm", ...(activeDisplay.logo
176
+ ? { imageSrc: activeDisplay.logo }
177
+ : {}) }) }), hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizations.error ? (_jsx(DropdownMenuItem, { disabled: true, children: organizations.error.message })) : null, !locked && selectableOrganizations.length ? (selectableOrganizations.map((organization) => {
178
+ const display = organizationDisplay(organization);
179
+ return (_jsx(DropdownMenuItem, { onClick: async () => {
180
+ const result = await centralAuthClient.organization.setActive({
181
+ organizationId: organization.id,
182
+ });
183
+ if (!result.error)
184
+ await refresh();
185
+ }, children: _jsx(AppBrand, { to: null, label: display.name, subtitle: display.subtitle, icon: Building2, className: "w-full text-left [&>div:first-child]:size-7", ...(display.logo ? { imageSrc: display.logo } : {}) }) }, organization.id));
186
+ })) : !locked && !organizations.isPending ? (_jsx(DropdownMenuItem, { disabled: true, children: active
187
+ ? m.organization_switcher_no_other_organizations()
188
+ : m.organization_switcher_empty() })) : null, !locked ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuItem, { onClick: () => setDialog("create"), children: [_jsx(Building2, {}), m.organization_create_title()] })] })) : null, activeOrganization.data ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuItem, { onClick: () => setDialog("manage"), children: [_jsx(PencilIcon, {}), m.organization_switcher_manage()] }), _jsxs(DropdownMenuItem, { onClick: () => setDialog("members"), children: [_jsx(Users, {}), m.organization_members_title()] }), _jsxs(DropdownMenuItem, { onClick: () => setDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] })] })) : null] }) })] }), _jsx(Dialog, { open: dialog === "create", onOpenChange: (open) => {
189
+ setDialog((current) => open ? "create" : current === "create" ? null : current);
190
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_create_title() }), _jsx(DialogDescription, { children: m.organization_create_description() })] }), _jsx(Separator, {}), _jsx(CreateOrganizationSection, { onCreated: async () => {
191
+ await refresh();
192
+ setDialog(null);
193
+ } })] }) }), _jsx(Dialog, { open: dialog === "manage", onOpenChange: (open) => {
194
+ setDialog((current) => open ? "manage" : current === "manage" ? null : current);
195
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_switcher_manage() }), _jsx(DialogDescription, { children: m.organization_edit_description() })] }), _jsx(Separator, {}), activeOrganization.data ? (_jsx(EditOrganizationSection, { organization: activeOrganization.data, onUpdated: refresh })) : null] }) }), _jsx(Dialog, { open: dialog === "members", onOpenChange: (open) => {
196
+ setDialog((current) => open ? "members" : current === "members" ? null : current);
197
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-4xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_members_title() }), _jsx(DialogDescription, { children: activeOrganization.data?.name })] }), _jsx(Separator, {}), activeOrganization.data ? (_jsx(OrganizationMembersManager, { organization: activeOrganization.data, currentUserId: session.data.user.id })) : null] }) }), _jsx(Dialog, { open: dialog === "apiKeys", onOpenChange: (open) => {
198
+ setDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
199
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_api_keys_title() }), _jsx(DialogDescription, { children: activeOrganization.data?.name })] }), _jsx(Separator, {}), activeOrganization.data ? (_jsx(OrganizationApiKeyManager, { organization: activeOrganization.data })) : null] }) })] }));
200
+ }
201
+ function EditOrganizationSection({ organization, onUpdated, }) {
202
+ const [editingLocale, setEditingLocale] = useState(currentOrganizationLocale());
203
+ const defaultValues = organizationFormDefaults(organization);
204
+ const form = useAppForm({
205
+ defaultValues,
206
+ onSubmit: async ({ value, formApi }) => {
207
+ formApi.setErrorMap({ onSubmit: undefined });
208
+ const name = value.name.trim();
209
+ const slug = value.slug.trim().toLowerCase();
210
+ const metadata = await organizationMetadataFromForm(value);
211
+ const result = await centralAuthClient.organization.update({
212
+ organizationId: organization.id,
213
+ data: { name, slug, metadata },
214
+ });
215
+ if (result.error) {
216
+ formApi.setErrorMap({
217
+ onSubmit: {
218
+ form: result.error.message ?? m.organization_update_error(),
219
+ fields: {},
220
+ },
221
+ });
222
+ return;
223
+ }
224
+ await onUpdated();
225
+ },
226
+ });
227
+ return (_jsx("section", { className: "flex flex-col gap-4", children: _jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
228
+ event.preventDefault();
229
+ event.stopPropagation();
230
+ form.handleSubmit();
231
+ }, children: [_jsx(form.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.organization_name(), required: true })) }), _jsx(form.AppField, { name: "slug", children: (field) => (_jsx(field.TextField, { label: m.organization_slug(), required: true })) }), _jsx(Separator, { className: "my-2" }), editingLocale === "en" ? (_jsxs(_Fragment, { children: [_jsx(OrganizationTranslationHeader, { locale: "en", editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsx(form.AppField, { name: "enName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name(), required: true })) }), _jsx(form.AppField, { name: "enLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), defaultImageUrl: defaultValues.enLogoUrl, size: {
232
+ width: 96,
233
+ height: 96,
234
+ suggestedWidth: 512,
235
+ suggestedHeight: 512,
236
+ } })) }), _jsx(form.AppField, { name: "enContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "enLocation", children: (field) => (_jsx(field.TextField, { label: m.organization_location() })) })] })) : (_jsxs(_Fragment, { children: [_jsx(OrganizationTranslationHeader, { locale: "fr", editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsx(form.AppField, { name: "frName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name() })) }), _jsx(form.AppField, { name: "frLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), defaultImageUrl: defaultValues.frLogoUrl, size: {
237
+ width: 96,
238
+ height: 96,
239
+ suggestedWidth: 512,
240
+ suggestedHeight: 512,
241
+ } })) }), _jsx(form.AppField, { name: "frContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "frLocation", children: (field) => (_jsx(field.TextField, { label: m.organization_location() })) })] })), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }) }));
242
+ }
243
+ function CreateOrganizationSection({ onCreated, }) {
244
+ const [editingLocale, setEditingLocale] = useState(currentOrganizationLocale());
245
+ const defaultValues = organizationFormDefaults();
246
+ const form = useAppForm({
247
+ defaultValues,
248
+ onSubmit: async ({ value, formApi }) => {
249
+ formApi.setErrorMap({ onSubmit: undefined });
250
+ const name = value.name.trim();
251
+ const slug = (value.slug.trim() || slugify(name)).toLowerCase();
252
+ const metadata = await organizationMetadataFromForm({
253
+ ...value,
254
+ name,
255
+ slug,
256
+ });
257
+ const result = await centralAuthClient.organization.create({
258
+ name,
259
+ slug,
260
+ metadata,
261
+ });
262
+ if (result.error) {
263
+ formApi.setErrorMap({
264
+ onSubmit: {
265
+ form: result.error.message ?? m.organization_create_error(),
266
+ fields: {},
267
+ },
268
+ });
269
+ return;
270
+ }
271
+ form.reset();
272
+ await onCreated();
273
+ },
274
+ });
275
+ return (_jsx("section", { className: "flex flex-col gap-4", children: _jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
276
+ event.preventDefault();
277
+ event.stopPropagation();
278
+ form.handleSubmit();
279
+ }, children: [_jsx(form.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.organization_name(), required: true })) }), _jsx(form.AppField, { name: "slug", children: (field) => (_jsx(field.TextField, { label: m.organization_slug(), description: m.organization_slug_description() })) }), _jsx(Separator, { className: "my-2" }), editingLocale === "en" ? (_jsxs(_Fragment, { children: [_jsx(OrganizationTranslationHeader, { locale: "en", editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsx(form.AppField, { name: "enName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name(), required: true })) }), _jsx(form.AppField, { name: "enLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), defaultImageUrl: defaultValues.enLogoUrl, size: {
280
+ width: 96,
281
+ height: 96,
282
+ suggestedWidth: 512,
283
+ suggestedHeight: 512,
284
+ } })) }), _jsx(form.AppField, { name: "enContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "enLocation", children: (field) => (_jsx(field.TextField, { label: m.organization_location() })) })] })) : (_jsxs(_Fragment, { children: [_jsx(OrganizationTranslationHeader, { locale: "fr", editingLocale: editingLocale, onEditingLocaleChange: setEditingLocale }), _jsx(form.AppField, { name: "frName", children: (field) => (_jsx(field.TextField, { label: m.organization_translation_name() })) }), _jsx(form.AppField, { name: "frLogo", children: (field) => (_jsx(field.ImageField, { label: m.organization_logo(), defaultImageUrl: defaultValues.frLogoUrl, size: {
285
+ width: 96,
286
+ height: 96,
287
+ suggestedWidth: 512,
288
+ suggestedHeight: 512,
289
+ } })) }), _jsx(form.AppField, { name: "frContactEmail", children: (field) => (_jsx(field.TextField, { label: m.organization_contact_email(), placeholder: "team@example.com", type: "email" })) }), _jsx(form.AppField, { name: "frLocation", children: (field) => (_jsx(field.TextField, { label: m.organization_location() })) })] })), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }) }));
290
+ }
291
+ function OrganizationTranslationHeader({ locale, editingLocale, onEditingLocaleChange, }) {
292
+ const title = locale === "en"
293
+ ? m.organization_translation_english()
294
+ : m.organization_translation_french();
295
+ return (_jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium", children: title }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_translation_description() })] }), _jsx(EditingLocaleSwitcher, { value: editingLocale, onValueChange: onEditingLocaleChange })] }));
296
+ }
297
+ function OrganizationMembersManager({ organization, currentUserId, }) {
298
+ const [members, setMembers] = useState([]);
299
+ const [invitations, setInvitations] = useState([]);
300
+ const [error, setError] = useState(null);
301
+ const [loading, setLoading] = useState(true);
302
+ const [updatingMemberId, setUpdatingMemberId] = useState(null);
303
+ const [cancellingInvitationId, setCancellingInvitationId] = useState(null);
304
+ const loadMembers = useEffectEvent(async () => {
305
+ setLoading(true);
306
+ setError(null);
307
+ const [membersResult, invitationsResult] = await Promise.all([
308
+ centralAuthClient.organization.listMembers({
309
+ query: { organizationId: organization.id },
310
+ }),
311
+ centralAuthClient.organization.listInvitations({
312
+ query: { organizationId: organization.id },
313
+ }),
314
+ ]);
315
+ if (membersResult.error) {
316
+ setError(membersResult.error.message ?? m.organization_members_load_error());
317
+ setLoading(false);
318
+ return;
319
+ }
320
+ if (invitationsResult.error) {
321
+ setError(invitationsResult.error.message ??
322
+ m.organization_invitations_load_error());
323
+ setLoading(false);
324
+ return;
325
+ }
326
+ setMembers(membersResult.data?.members ?? []);
327
+ setInvitations(invitationsResult.data ?? []);
328
+ setLoading(false);
329
+ });
330
+ useEffect(() => {
331
+ void loadMembers();
332
+ }, [organization.id]);
333
+ const inviteForm = useAppForm({
334
+ defaultValues: { email: "", role: "member" },
335
+ onSubmit: async ({ value, formApi }) => {
336
+ formApi.setErrorMap({ onSubmit: undefined });
337
+ const result = await centralAuthClient.organization.inviteMember({
338
+ email: value.email.trim(),
339
+ role: normalizeOrganizationRole(value.role),
340
+ organizationId: organization.id,
341
+ });
342
+ if (result.error) {
343
+ formApi.setErrorMap({
344
+ onSubmit: {
345
+ form: result.error.message ?? m.organization_invite_error(),
346
+ fields: {},
347
+ },
348
+ });
349
+ return;
350
+ }
351
+ inviteForm.reset();
352
+ await loadMembers();
353
+ },
354
+ });
355
+ const updateRole = async (member, role) => {
356
+ setUpdatingMemberId(member.id);
357
+ setError(null);
358
+ const result = await centralAuthClient.organization.updateMemberRole({
359
+ memberId: member.id,
360
+ role,
361
+ organizationId: organization.id,
362
+ });
363
+ setUpdatingMemberId(null);
364
+ if (result.error) {
365
+ setError(result.error.message ?? m.organization_member_role_error());
366
+ return;
367
+ }
368
+ await loadMembers();
369
+ };
370
+ const removeMember = async (member) => {
371
+ setUpdatingMemberId(member.id);
372
+ setError(null);
373
+ const result = await centralAuthClient.organization.removeMember({
374
+ memberIdOrEmail: member.id,
375
+ organizationId: organization.id,
376
+ });
377
+ setUpdatingMemberId(null);
378
+ if (result.error) {
379
+ setError(result.error.message ?? m.organization_member_remove_error());
380
+ return;
381
+ }
382
+ await loadMembers();
383
+ };
384
+ const cancelInvitation = async (invitation) => {
385
+ setCancellingInvitationId(invitation.id);
386
+ setError(null);
387
+ const result = await centralAuthClient.organization.cancelInvitation({
388
+ invitationId: invitation.id,
389
+ });
390
+ setCancellingInvitationId(null);
391
+ if (result.error) {
392
+ setError(result.error.message ?? m.organization_invitation_cancel_error());
393
+ return;
394
+ }
395
+ await loadMembers();
396
+ };
397
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(inviteForm.AppForm, { children: _jsxs("form", { className: "grid gap-4 rounded-lg border p-4 sm:grid-cols-[minmax(0,1fr)_12rem_auto] sm:items-end", onSubmit: (event) => {
398
+ event.preventDefault();
399
+ event.stopPropagation();
400
+ inviteForm.handleSubmit();
401
+ }, children: [_jsxs("div", { className: "sm:col-span-3", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(UserPlus, { className: "size-4" }), m.organization_invite_member_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_invite_member_description() })] }), _jsx(inviteForm.AppField, { name: "email", children: (field) => (_jsx(field.TextField, { label: m.organization_member_email(), placeholder: "teammate@example.com", type: "email", required: true })) }), _jsx(inviteForm.AppField, { name: "role", children: (field) => (_jsx(field.SelectField, { label: m.organization_member_role(), options: organizationRoles.map((role) => ({
402
+ label: organizationRoleLabel(role),
403
+ value: role,
404
+ })) })) }), _jsx("div", { className: "self-end", children: _jsx(inviteForm.SubmitButton, {}) }), _jsx(inviteForm.FormError, {})] }) }), error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsxs("section", { className: "flex flex-col gap-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium", children: m.organization_members_heading() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_members_description() })] }), _jsx(DataTable, { columns: memberColumns({
405
+ currentUserId,
406
+ updatingMemberId,
407
+ onRemove: removeMember,
408
+ onRoleChange: updateRole,
409
+ }), data: members, emptyLabel: loading ? m.user_loading() : m.organization_members_empty(), exportFileName: `${organization.slug}-members.csv`, features: { gallery: false } })] }), _jsxs("section", { className: "flex flex-col gap-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium", children: m.organization_invitations_heading() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.organization_invitations_description() })] }), _jsx(DataTable, { columns: invitationColumns({
410
+ cancellingInvitationId,
411
+ onCancel: cancelInvitation,
412
+ }), data: invitations, emptyLabel: loading ? m.user_loading() : m.organization_invitations_empty(), exportFileName: `${organization.slug}-invitations.csv`, features: { gallery: false } })] })] }));
413
+ }
414
+ const memberColumns = ({ currentUserId, updatingMemberId, onRemove, onRoleChange, }) => [
415
+ {
416
+ id: "user",
417
+ header: m.organization_member_user(),
418
+ cell: ({ row }) => (_jsxs("div", { className: "flex min-w-0 items-center gap-3", children: [row.original.user.image ? (_jsx("img", { src: row.original.user.image, alt: row.original.user.name, className: "size-9 shrink-0 rounded-full border object-cover" })) : (_jsx("span", { className: "bg-muted flex size-9 shrink-0 items-center justify-center rounded-full border text-sm font-semibold", children: initialsFromName(row.original.user.name) })), _jsxs("div", { className: "min-w-0", children: [_jsx("p", { className: "truncate font-medium", children: row.original.user.name }), _jsx("p", { className: "text-muted-foreground truncate text-sm", children: row.original.user.email })] })] })),
419
+ },
420
+ {
421
+ accessorKey: "role",
422
+ header: m.organization_member_role(),
423
+ cell: ({ row }) => {
424
+ const member = row.original;
425
+ const disabled = updatingMemberId === member.id;
426
+ return (_jsxs(Select, { items: organizationRoles.map((role) => ({
427
+ label: organizationRoleLabel(role),
428
+ value: role,
429
+ })), value: normalizeOrganizationRole(member.role), onValueChange: (value) => {
430
+ if (value === "owner" || value === "admin" || value === "member") {
431
+ onRoleChange(member, value);
432
+ }
433
+ }, disabled: disabled, children: [_jsx(SelectTrigger, { className: "w-36", onClick: (event) => event.stopPropagation(), children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: organizationRoles.map((role) => (_jsx(SelectItem, { value: role, children: organizationRoleLabel(role) }, role))) })] }));
434
+ },
435
+ },
436
+ {
437
+ accessorKey: "createdAt",
438
+ header: m.organization_member_joined(),
439
+ cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: formatOrganizationDate(row.original.createdAt) })),
440
+ },
441
+ createDataTableActionsColumn([
442
+ {
443
+ name: m.organization_member_remove(),
444
+ icon: _jsx(Trash2, {}),
445
+ variant: "destructive",
446
+ visible: (member) => member.userId !== currentUserId,
447
+ onClick: onRemove,
448
+ },
449
+ ]),
450
+ ];
451
+ const invitationColumns = ({ cancellingInvitationId, onCancel, }) => [
452
+ {
453
+ accessorKey: "email",
454
+ header: m.organization_member_email(),
455
+ cell: ({ row }) => (_jsx("p", { className: "truncate font-medium", children: row.original.email })),
456
+ },
457
+ {
458
+ accessorKey: "role",
459
+ header: m.organization_member_role(),
460
+ cell: ({ row }) => (_jsx(Badge, { variant: "secondary", children: organizationRoleLabel(row.original.role) })),
461
+ },
462
+ {
463
+ accessorKey: "status",
464
+ header: m.organization_invitation_status(),
465
+ cell: ({ row }) => _jsx(Badge, { children: row.original.status }),
466
+ },
467
+ {
468
+ accessorKey: "expiresAt",
469
+ header: m.organization_invitation_expires(),
470
+ cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: formatOrganizationDate(row.original.expiresAt) })),
471
+ },
472
+ createDataTableActionsColumn([
473
+ {
474
+ name: m.organization_invitation_cancel(),
475
+ icon: _jsx(Trash2, {}),
476
+ variant: "destructive",
477
+ visible: (invitation) => cancellingInvitationId !== invitation.id,
478
+ onClick: onCancel,
479
+ },
480
+ ]),
481
+ ];
482
+ function OrganizationApiKeyManager({ organization, }) {
483
+ const [keys, setKeys] = useState([]);
484
+ const [createdKey, setCreatedKey] = useState(null);
485
+ const [error, setError] = useState(null);
486
+ const [loading, setLoading] = useState(true);
487
+ const loadKeys = useEffectEvent(async () => {
488
+ setLoading(true);
489
+ setError(null);
490
+ const result = await centralAuthClient.apiKey.list({
491
+ query: { configId: "organization", organizationId: organization.id },
492
+ });
493
+ if (result.error) {
494
+ setError(result.error.message ?? m.user_api_keys_load_error());
495
+ setLoading(false);
496
+ return;
497
+ }
498
+ setKeys(result.data?.apiKeys ?? []);
499
+ setLoading(false);
500
+ });
501
+ useEffect(() => {
502
+ void loadKeys();
503
+ }, [organization.id]);
504
+ const createForm = useAppForm({
505
+ defaultValues: { name: "" },
506
+ onSubmit: async ({ value, formApi }) => {
507
+ formApi.setErrorMap({ onSubmit: undefined });
508
+ setCreatedKey(null);
509
+ const result = await centralAuthClient.apiKey.create({
510
+ configId: "organization",
511
+ organizationId: organization.id,
512
+ name: value.name.trim(),
513
+ });
514
+ if (result.error || !result.data) {
515
+ formApi.setErrorMap({
516
+ onSubmit: {
517
+ form: result.error?.message ?? m.user_api_key_create_error(),
518
+ fields: {},
519
+ },
520
+ });
521
+ return;
522
+ }
523
+ setCreatedKey(result.data.key);
524
+ createForm.reset();
525
+ await loadKeys();
526
+ },
527
+ });
528
+ const deleteKey = async (key) => {
529
+ const result = await centralAuthClient.apiKey.delete({
530
+ configId: "organization",
531
+ keyId: key.id,
532
+ });
533
+ if (result.error) {
534
+ setError(result.error.message ?? m.user_api_key_delete_error());
535
+ return;
536
+ }
537
+ await loadKeys();
538
+ };
539
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(createForm.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
540
+ event.preventDefault();
541
+ event.stopPropagation();
542
+ createForm.handleSubmit();
543
+ }, children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.api_key_rate_limit_notice() }), _jsx(createForm.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.user_api_key_name(), required: true })) }), _jsx(createForm.FormError, {}), _jsx(createForm.SubmitButton, {})] }) }), createdKey ? (_jsxs("div", { className: "flex flex-col gap-2 rounded-lg border p-4", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(KeyRound, {}), m.user_api_key_created_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_api_key_created_description() }), _jsx("code", { className: "bg-muted overflow-x-auto rounded-md p-3 text-sm", children: createdKey })] })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsx(Separator, {}), _jsx(DataTable, { columns: apiKeyColumns({ onDelete: deleteKey }), data: keys, emptyLabel: loading ? m.user_loading() : m.table_empty(), exportFileName: `${organization.slug}-api-keys.csv`, features: { gallery: false } })] }));
544
+ }
545
+ const apiKeyColumns = ({ onDelete, }) => [
546
+ {
547
+ accessorKey: "name",
548
+ header: m.user_api_key_name(),
549
+ cell: ({ row }) => (_jsxs("div", { className: "min-w-0", children: [_jsx("p", { className: "truncate font-medium", children: row.original.name }), _jsx("p", { className: "text-muted-foreground text-sm", children: row.original.start
550
+ ? m.user_api_key_starts_with({ start: row.original.start })
551
+ : m.user_api_key_hidden() })] })),
552
+ },
553
+ {
554
+ accessorKey: "enabled",
555
+ header: m.user_api_key_status(),
556
+ cell: ({ row }) => (_jsx(Badge, { variant: row.original.enabled ? "default" : "secondary", children: row.original.enabled
557
+ ? m.user_api_key_enabled()
558
+ : m.user_api_key_disabled() })),
559
+ },
560
+ createDataTableActionsColumn([
561
+ {
562
+ name: m.user_delete(),
563
+ icon: _jsx(Trash2, {}),
564
+ variant: "destructive",
565
+ onClick: onDelete,
566
+ },
567
+ ]),
568
+ ];
569
+ //# sourceMappingURL=organization-switcher.js.map