@fluid-app/rep-sdk 0.1.1 → 0.1.3

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 (73) hide show
  1. package/dist/ContactsScreen-33AJ5XUB.js +5 -0
  2. package/dist/{ContactsScreen-BYXF74BO.js.map → ContactsScreen-33AJ5XUB.js.map} +1 -1
  3. package/dist/ContactsScreen-ATASCZO2.cjs +18 -0
  4. package/dist/{ContactsScreen-XZOQJVFE.cjs.map → ContactsScreen-ATASCZO2.cjs.map} +1 -1
  5. package/dist/CustomersScreen-E4HXBKV7.js +5 -0
  6. package/dist/{CustomersScreen-VS6LGULO.js.map → CustomersScreen-E4HXBKV7.js.map} +1 -1
  7. package/dist/CustomersScreen-XMPMKSQA.cjs +18 -0
  8. package/dist/{CustomersScreen-53SXRDDK.cjs.map → CustomersScreen-XMPMKSQA.cjs.map} +1 -1
  9. package/dist/MessagingScreen-4H7ZBO3V.js +4 -0
  10. package/dist/{MessagingScreen-O42JEJMW.js.map → MessagingScreen-4H7ZBO3V.js.map} +1 -1
  11. package/dist/MessagingScreen-UPFXQZV3.cjs +17 -0
  12. package/dist/{MessagingScreen-UCVLYWZB.cjs.map → MessagingScreen-UPFXQZV3.cjs.map} +1 -1
  13. package/dist/OrdersScreen-IPPZLEYF.js +5 -0
  14. package/dist/{OrdersScreen-QQJFTTSS.js.map → OrdersScreen-IPPZLEYF.js.map} +1 -1
  15. package/dist/OrdersScreen-X7FYUROL.cjs +18 -0
  16. package/dist/{OrdersScreen-WNT2WDLI.cjs.map → OrdersScreen-X7FYUROL.cjs.map} +1 -1
  17. package/dist/ProductsScreen-4ZIUQNUU.cjs +18 -0
  18. package/dist/{ProductsScreen-CTIAKS3Z.cjs.map → ProductsScreen-4ZIUQNUU.cjs.map} +1 -1
  19. package/dist/ProductsScreen-YTSOZW7B.js +5 -0
  20. package/dist/{ProductsScreen-TRIT2FE3.js.map → ProductsScreen-YTSOZW7B.js.map} +1 -1
  21. package/dist/chunk-424PT5DM.js +21 -0
  22. package/dist/chunk-424PT5DM.js.map +1 -0
  23. package/dist/{chunk-QUVJ3R4T.cjs → chunk-5UBEM3AX.cjs} +4 -4
  24. package/dist/{chunk-QUVJ3R4T.cjs.map → chunk-5UBEM3AX.cjs.map} +1 -1
  25. package/dist/chunk-7JMNKWPN.js +1868 -0
  26. package/dist/chunk-7JMNKWPN.js.map +1 -0
  27. package/dist/chunk-B6S6BEPL.cjs +16 -0
  28. package/dist/chunk-B6S6BEPL.cjs.map +1 -0
  29. package/dist/{chunk-WH7WZXT6.js → chunk-CMF2FYTD.js} +3 -3
  30. package/dist/{chunk-WH7WZXT6.js.map → chunk-CMF2FYTD.js.map} +1 -1
  31. package/dist/{chunk-MEOOAMH2.cjs → chunk-EOXYOOWS.cjs} +4 -4
  32. package/dist/{chunk-MEOOAMH2.cjs.map → chunk-EOXYOOWS.cjs.map} +1 -1
  33. package/dist/{chunk-YII3IXF4.cjs → chunk-FG2CI6HA.cjs} +4 -4
  34. package/dist/{chunk-YII3IXF4.cjs.map → chunk-FG2CI6HA.cjs.map} +1 -1
  35. package/dist/chunk-HDQ2JUQT.cjs +24 -0
  36. package/dist/chunk-HDQ2JUQT.cjs.map +1 -0
  37. package/dist/{chunk-MBUCXIUN.cjs → chunk-MHPK7YQ2.cjs} +4 -4
  38. package/dist/{chunk-MBUCXIUN.cjs.map → chunk-MHPK7YQ2.cjs.map} +1 -1
  39. package/dist/{chunk-2AWTZV3T.js → chunk-QZMWG7EM.js} +3 -3
  40. package/dist/{chunk-2AWTZV3T.js.map → chunk-QZMWG7EM.js.map} +1 -1
  41. package/dist/chunk-RS4OSTES.js +14 -0
  42. package/dist/chunk-RS4OSTES.js.map +1 -0
  43. package/dist/chunk-V3IMQZIG.cjs +1942 -0
  44. package/dist/chunk-V3IMQZIG.cjs.map +1 -0
  45. package/dist/{chunk-PZIHCYDD.js → chunk-WFPYEYC7.js} +3 -3
  46. package/dist/{chunk-PZIHCYDD.js.map → chunk-WFPYEYC7.js.map} +1 -1
  47. package/dist/{chunk-CXRJSGO6.js → chunk-WMBD65GH.js} +3 -3
  48. package/dist/{chunk-CXRJSGO6.js.map → chunk-WMBD65GH.js.map} +1 -1
  49. package/dist/index.cjs +1470 -1055
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.cts +2596 -0
  52. package/dist/index.d.ts +2596 -0
  53. package/dist/index.js +1269 -993
  54. package/dist/index.js.map +1 -1
  55. package/package.json +27 -8
  56. package/dist/ContactsScreen-BYXF74BO.js +0 -4
  57. package/dist/ContactsScreen-XZOQJVFE.cjs +0 -17
  58. package/dist/CustomersScreen-53SXRDDK.cjs +0 -17
  59. package/dist/CustomersScreen-VS6LGULO.js +0 -4
  60. package/dist/MessagingScreen-O42JEJMW.js +0 -4
  61. package/dist/MessagingScreen-UCVLYWZB.cjs +0 -17
  62. package/dist/OrdersScreen-QQJFTTSS.js +0 -4
  63. package/dist/OrdersScreen-WNT2WDLI.cjs +0 -17
  64. package/dist/ProductsScreen-CTIAKS3Z.cjs +0 -17
  65. package/dist/ProductsScreen-TRIT2FE3.js +0 -4
  66. package/dist/chunk-DEQ3PBVX.cjs +0 -29
  67. package/dist/chunk-DEQ3PBVX.cjs.map +0 -1
  68. package/dist/chunk-JZRNKSKT.cjs +0 -19
  69. package/dist/chunk-JZRNKSKT.cjs.map +0 -1
  70. package/dist/chunk-LO2HDG6C.js +0 -26
  71. package/dist/chunk-LO2HDG6C.js.map +0 -1
  72. package/dist/chunk-PJWPO4BJ.js +0 -16
  73. package/dist/chunk-PJWPO4BJ.js.map +0 -1
@@ -0,0 +1,1868 @@
1
+ import { __export, __reExport } from './chunk-424PT5DM.js';
2
+ import { createContext, useRef, useState, useEffect, useCallback, useMemo, useContext } from 'react';
3
+ import { MessagingApp } from '@fluid-app/fluid-messaging-ui/app';
4
+ import { extractEmoji, formatMessageChannelName } from '@fluid-app/fluid-messaging-ui';
5
+ import { listConnectedRecipients, searchConversations } from '@fluid-app/fluid-messaging-api-client';
6
+ import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
7
+ import { decodeJwt, createRemoteJWKSet, jwtVerify } from 'jose';
8
+ import { jsx, jsxs } from 'react/jsx-runtime';
9
+ import * as theme_star from '@fluid-app/rep-core/theme';
10
+ import { getActiveThemeId, transformThemes } from '@fluid-app/rep-core/theme';
11
+ export { buildThemeDefinition, getActiveThemeId, transformThemes } from '@fluid-app/rep-core/theme';
12
+ import { DataSourceRegistryProvider } from '@fluid-app/rep-core/data-sources/registry-context';
13
+ import { RegistryProvider } from '@fluid-app/rep-widgets/contexts';
14
+ import { createWidgetRegistry } from '@fluid-app/rep-core/widget-utils';
15
+ import { VideoWidget, ToDoWidget, TextWidget, TableWidget, SpacerWidget, RecentActivityWidget, QuickShareWidget, NestedWidget, MySiteWidget, ListWidget, LayoutWidget, ImageWidget, EmbedWidget, ContainerWidget, ChartWidget, CatchUpWidget, CarouselWidget, CalendarWidget, AlertWidget } from '@fluid-app/rep-widgets/widgets';
16
+ import { getFileTypeFromMimetype } from '@fluid-app/fluid-messaging-core';
17
+
18
+ // src/auth/constants.ts
19
+ var AUTH_CONSTANTS = {
20
+ /**
21
+ * Grace period in milliseconds to account for clock skew
22
+ * when checking token expiration. Tokens are considered valid
23
+ * if they expire within this period.
24
+ */
25
+ TOKEN_GRACE_PERIOD_MS: 30 * 1e3,
26
+ // 30 seconds
27
+ /**
28
+ * Default cookie max age in seconds (9 days).
29
+ * This matches the typical JWT token lifetime from the Fluid API.
30
+ */
31
+ COOKIE_MAX_AGE: 9 * 24 * 60 * 60
32
+ // 9 days = 777600 seconds
33
+ };
34
+ var STORAGE_KEYS = {
35
+ /** localStorage key for user token */
36
+ USER_TOKEN: "fluidUserToken",
37
+ /** localStorage key for company token (legacy) */
38
+ COMPANY_TOKEN: "fluidCompanyToken",
39
+ /** Cookie name for auth token */
40
+ AUTH_COOKIE: "auth_token"
41
+ };
42
+ var URL_PARAMS = {
43
+ /** URL parameter name for user token */
44
+ USER_TOKEN: "fluidUserToken",
45
+ /** URL parameter name for company token (legacy) */
46
+ COMPANY_TOKEN: "fluidCompanyToken"
47
+ };
48
+
49
+ // src/auth/browser-utils.ts
50
+ function isBrowser() {
51
+ return typeof window !== "undefined" && typeof document !== "undefined";
52
+ }
53
+
54
+ // src/auth/url-token.ts
55
+ function extractTokenFromUrl(tokenKey = URL_PARAMS.USER_TOKEN) {
56
+ if (!isBrowser()) {
57
+ return null;
58
+ }
59
+ try {
60
+ const searchParams = new URLSearchParams(window.location.search);
61
+ return searchParams.get(tokenKey);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ function extractCompanyTokenFromUrl(tokenKey = URL_PARAMS.COMPANY_TOKEN) {
67
+ if (!isBrowser()) {
68
+ return null;
69
+ }
70
+ try {
71
+ const searchParams = new URLSearchParams(window.location.search);
72
+ return searchParams.get(tokenKey);
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+ function cleanTokenFromUrl(tokenKey = URL_PARAMS.USER_TOKEN) {
78
+ if (!isBrowser()) {
79
+ return;
80
+ }
81
+ try {
82
+ const url = new URL(window.location.href);
83
+ const hadToken = url.searchParams.has(tokenKey);
84
+ const hadCompanyToken = url.searchParams.has(URL_PARAMS.COMPANY_TOKEN);
85
+ url.searchParams.delete(tokenKey);
86
+ url.searchParams.delete(URL_PARAMS.COMPANY_TOKEN);
87
+ if (hadToken || hadCompanyToken) {
88
+ window.history.replaceState(
89
+ window.history.state,
90
+ document.title,
91
+ url.toString()
92
+ );
93
+ }
94
+ } catch (error) {
95
+ console.warn("[FluidAuth] Failed to clean token from URL:", error);
96
+ }
97
+ }
98
+ function hasTokenInUrl(tokenKey = URL_PARAMS.USER_TOKEN) {
99
+ if (!isBrowser()) {
100
+ return false;
101
+ }
102
+ try {
103
+ const searchParams = new URLSearchParams(window.location.search);
104
+ return searchParams.has(tokenKey);
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ function extractAllTokensFromUrl(userTokenKey = URL_PARAMS.USER_TOKEN, companyTokenKey = URL_PARAMS.COMPANY_TOKEN) {
110
+ if (!isBrowser()) {
111
+ return { userToken: null, companyToken: null };
112
+ }
113
+ try {
114
+ const searchParams = new URLSearchParams(window.location.search);
115
+ return {
116
+ userToken: searchParams.get(userTokenKey),
117
+ companyToken: searchParams.get(companyTokenKey)
118
+ };
119
+ } catch {
120
+ return { userToken: null, companyToken: null };
121
+ }
122
+ }
123
+
124
+ // src/auth/token-storage.ts
125
+ function parseCookies() {
126
+ if (!isBrowser()) {
127
+ return {};
128
+ }
129
+ const cookies = {};
130
+ const cookieString = document.cookie;
131
+ if (!cookieString) {
132
+ return cookies;
133
+ }
134
+ cookieString.split(";").forEach((cookie) => {
135
+ const [name, ...valueParts] = cookie.trim().split("=");
136
+ if (name) {
137
+ cookies[name] = decodeURIComponent(valueParts.join("="));
138
+ }
139
+ });
140
+ return cookies;
141
+ }
142
+ function setCookie(name, value, options = {}) {
143
+ if (!isBrowser()) {
144
+ return;
145
+ }
146
+ const {
147
+ maxAge = AUTH_CONSTANTS.COOKIE_MAX_AGE,
148
+ path = "/",
149
+ sameSite = "lax",
150
+ secure = window.location.protocol === "https:"
151
+ } = options;
152
+ let cookieString = `${name}=${encodeURIComponent(value)}`;
153
+ cookieString += `; path=${path}`;
154
+ cookieString += `; max-age=${maxAge}`;
155
+ cookieString += `; samesite=${sameSite}`;
156
+ if (secure) {
157
+ cookieString += "; secure";
158
+ }
159
+ document.cookie = cookieString;
160
+ }
161
+ function deleteCookie(name, path = "/") {
162
+ if (!isBrowser()) {
163
+ return;
164
+ }
165
+ document.cookie = `${name}=; path=${path}; max-age=0`;
166
+ }
167
+ function getStoredToken(config) {
168
+ if (!isBrowser()) {
169
+ return null;
170
+ }
171
+ const cookieKey = config?.cookieKey ?? STORAGE_KEYS.AUTH_COOKIE;
172
+ const localStorageKey = STORAGE_KEYS.USER_TOKEN;
173
+ const cookies = parseCookies();
174
+ const cookieToken = cookies[cookieKey];
175
+ if (cookieToken) {
176
+ return cookieToken;
177
+ }
178
+ try {
179
+ return localStorage.getItem(localStorageKey);
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
184
+ function storeToken(token, config) {
185
+ if (!isBrowser()) {
186
+ return;
187
+ }
188
+ const cookieKey = config?.cookieKey ?? STORAGE_KEYS.AUTH_COOKIE;
189
+ const maxAge = config?.cookieMaxAge ?? AUTH_CONSTANTS.COOKIE_MAX_AGE;
190
+ try {
191
+ const inIframe = window.self !== window.top;
192
+ const sameSite = inIframe ? "none" : "lax";
193
+ setCookie(cookieKey, token, {
194
+ maxAge,
195
+ path: "/",
196
+ sameSite,
197
+ // SameSite=None requires Secure per RFC 6265bis; browsers silently
198
+ // reject the cookie otherwise (e.g. HTTP localhost in an iframe).
199
+ secure: sameSite === "none" || window.location.protocol === "https:"
200
+ });
201
+ } catch (error) {
202
+ console.warn("[FluidAuth] Failed to store token in cookie:", error);
203
+ }
204
+ try {
205
+ localStorage.setItem(STORAGE_KEYS.USER_TOKEN, token);
206
+ } catch (error) {
207
+ console.warn("[FluidAuth] Failed to store token in localStorage:", error);
208
+ }
209
+ }
210
+ function clearTokens(config) {
211
+ if (!isBrowser()) {
212
+ return;
213
+ }
214
+ const cookieKey = config?.cookieKey ?? STORAGE_KEYS.AUTH_COOKIE;
215
+ try {
216
+ deleteCookie(cookieKey);
217
+ } catch {
218
+ }
219
+ try {
220
+ localStorage.removeItem(STORAGE_KEYS.USER_TOKEN);
221
+ localStorage.removeItem(STORAGE_KEYS.COMPANY_TOKEN);
222
+ } catch {
223
+ }
224
+ }
225
+ function hasStoredToken(config) {
226
+ return getStoredToken(config) !== null;
227
+ }
228
+
229
+ // src/auth/types.ts
230
+ var USER_TYPES = {
231
+ admin: "admin",
232
+ rep: "rep",
233
+ root_admin: "root_admin",
234
+ customer: "customer"
235
+ };
236
+ function isUserType(value) {
237
+ return Object.values(USER_TYPES).includes(value);
238
+ }
239
+
240
+ // src/auth/token-utils.ts
241
+ function extractPayloadFromJose(decoded) {
242
+ const rawUserType = decoded.user_type;
243
+ const rawOgUserType = decoded.og_user_type;
244
+ return {
245
+ id: typeof decoded.id === "number" ? decoded.id : void 0,
246
+ email: typeof decoded.email === "string" ? decoded.email : void 0,
247
+ full_name: typeof decoded.full_name === "string" ? decoded.full_name : void 0,
248
+ user_type: typeof rawUserType === "string" && isUserType(rawUserType) ? rawUserType : "rep",
249
+ og_user_type: typeof rawOgUserType === "string" && isUserType(rawOgUserType) ? rawOgUserType : void 0,
250
+ company_id: typeof decoded.company_id === "number" ? decoded.company_id : void 0,
251
+ exp: decoded.exp,
252
+ auth_type: typeof decoded.auth_type === "string" ? decoded.auth_type : void 0
253
+ };
254
+ }
255
+ function decodeToken(token) {
256
+ try {
257
+ const decoded = decodeJwt(token);
258
+ return extractPayloadFromJose(decoded);
259
+ } catch (error) {
260
+ console.error("[FluidAuth] Failed to decode JWT token:", error);
261
+ return null;
262
+ }
263
+ }
264
+ function isTokenExpired(token, gracePeriodMs = AUTH_CONSTANTS.TOKEN_GRACE_PERIOD_MS) {
265
+ try {
266
+ const decoded = decodeJwt(token);
267
+ if (!decoded.exp) {
268
+ return false;
269
+ }
270
+ const expirationTime = decoded.exp * 1e3;
271
+ const currentTime = Date.now();
272
+ return currentTime > expirationTime + gracePeriodMs;
273
+ } catch {
274
+ return true;
275
+ }
276
+ }
277
+ function validateToken(token, gracePeriodMs = AUTH_CONSTANTS.TOKEN_GRACE_PERIOD_MS) {
278
+ if (!token || token.trim() === "") {
279
+ return {
280
+ isValid: false,
281
+ error: "Token is empty or not provided"
282
+ };
283
+ }
284
+ const payload = decodeToken(token);
285
+ if (!payload) {
286
+ return {
287
+ isValid: false,
288
+ error: "Token has invalid format"
289
+ };
290
+ }
291
+ if (isTokenExpired(token, gracePeriodMs)) {
292
+ return {
293
+ isValid: false,
294
+ payload,
295
+ error: "Token has expired"
296
+ };
297
+ }
298
+ return {
299
+ isValid: true,
300
+ payload
301
+ };
302
+ }
303
+ function isValidToken(result) {
304
+ return result.isValid === true;
305
+ }
306
+ function getTokenExpiration(token) {
307
+ try {
308
+ const decoded = decodeJwt(token);
309
+ if (!decoded.exp) {
310
+ return null;
311
+ }
312
+ return new Date(decoded.exp * 1e3);
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+ function getTokenTimeRemaining(token) {
318
+ try {
319
+ const decoded = decodeJwt(token);
320
+ if (!decoded.exp) {
321
+ return Infinity;
322
+ }
323
+ const expirationTime = decoded.exp * 1e3;
324
+ const remaining = expirationTime - Date.now();
325
+ return Math.max(0, remaining);
326
+ } catch {
327
+ return 0;
328
+ }
329
+ }
330
+ async function verifyToken(token, jwksUrl) {
331
+ try {
332
+ const JWKS = createRemoteJWKSet(new URL(jwksUrl));
333
+ const { payload } = await jwtVerify(token, JWKS);
334
+ const decoded = payload;
335
+ return extractPayloadFromJose(decoded);
336
+ } catch (error) {
337
+ console.error("[FluidAuth] JWT signature verification failed:", error);
338
+ return null;
339
+ }
340
+ }
341
+
342
+ // src/auth/dev-utils.ts
343
+ function isDevBypassActive(devBypass) {
344
+ if (!devBypass) return false;
345
+ try {
346
+ return import.meta.env.DEV === true;
347
+ } catch {
348
+ return false;
349
+ }
350
+ }
351
+ function createDevUser() {
352
+ return {
353
+ id: 99999,
354
+ // Dev placeholder — avoids falsy 0
355
+ email: "dev@localhost",
356
+ full_name: "Dev User",
357
+ user_type: USER_TYPES.rep,
358
+ og_user_type: void 0,
359
+ company_id: 99999,
360
+ // Dev placeholder — avoids falsy 0
361
+ exp: void 0,
362
+ // Never expires
363
+ auth_type: "dev_bypass"
364
+ };
365
+ }
366
+
367
+ // src/auth/auth-redirect.ts
368
+ var DEFAULT_AUTH_URL = "https://auth.fluid.app";
369
+ var AUTH_REDIRECT_TOKEN_KEY = "jwt";
370
+ var REDIRECT_TIMESTAMP_KEY = "__fluid_auth_redirect_ts";
371
+ var REDIRECT_COOLDOWN_S = 10;
372
+ function isRedirectLoop() {
373
+ try {
374
+ const ts = sessionStorage.getItem(REDIRECT_TIMESTAMP_KEY);
375
+ if (!ts) return false;
376
+ const elapsed = (Date.now() - Number(ts)) / 1e3;
377
+ return elapsed < REDIRECT_COOLDOWN_S;
378
+ } catch {
379
+ return false;
380
+ }
381
+ }
382
+ function markRedirect() {
383
+ try {
384
+ sessionStorage.setItem(REDIRECT_TIMESTAMP_KEY, String(Date.now()));
385
+ } catch {
386
+ }
387
+ }
388
+ function createDefaultAuthRedirect(authUrl) {
389
+ return () => {
390
+ if (isRedirectLoop()) {
391
+ console.warn(
392
+ "[FluidAuth] Auth redirect suppressed \u2014 possible redirect loop. Check that your auth server returns a token accepted by the API."
393
+ );
394
+ return;
395
+ }
396
+ markRedirect();
397
+ const base = authUrl ?? DEFAULT_AUTH_URL;
398
+ const currentUrl = encodeURIComponent(window.location.href);
399
+ window.location.href = `${base}/?redirect_url=${currentUrl}`;
400
+ };
401
+ }
402
+ function resolveAuthFailureHandler(onAuthFailure, authUrl) {
403
+ return onAuthFailure ?? createDefaultAuthRedirect(authUrl);
404
+ }
405
+ var FluidAuthContext = createContext(null);
406
+ function FluidAuthProvider({
407
+ children,
408
+ config
409
+ }) {
410
+ const configRef = useRef(config);
411
+ configRef.current = config;
412
+ const [isLoading, setIsLoading] = useState(true);
413
+ const [token, setToken] = useState(null);
414
+ const [user, setUser] = useState(null);
415
+ const [error, setError] = useState(null);
416
+ useEffect(() => {
417
+ const initializeAuth = async () => {
418
+ const handleAuthFailure = () => {
419
+ const current = configRef.current;
420
+ const handler = resolveAuthFailureHandler(
421
+ current?.onAuthFailure,
422
+ current?.authUrl
423
+ );
424
+ handler();
425
+ };
426
+ try {
427
+ if (isDevBypassActive(config?.devBypass)) {
428
+ const envToken = import.meta.env.VITE_DEV_TOKEN;
429
+ if (envToken) {
430
+ const validation = validateToken(envToken, config?.gracePeriodMs);
431
+ if (validation.isValid && validation.payload) {
432
+ storeToken(envToken, config);
433
+ setToken(envToken);
434
+ setUser(validation.payload);
435
+ setError(null);
436
+ return;
437
+ }
438
+ console.warn(
439
+ "[FluidAuth] VITE_DEV_TOKEN is invalid or expired, falling back to mock user"
440
+ );
441
+ }
442
+ console.warn(
443
+ "[FluidAuth] Dev bypass active - using mock user. API calls will fail without a real token."
444
+ );
445
+ const devUser = createDevUser();
446
+ setToken(null);
447
+ setUser(devUser);
448
+ setError(null);
449
+ return;
450
+ }
451
+ const tokenKey = config?.tokenKey ?? "fluidUserToken";
452
+ let candidateToken = extractTokenFromUrl(tokenKey);
453
+ if (!candidateToken && tokenKey !== AUTH_REDIRECT_TOKEN_KEY) {
454
+ candidateToken = extractTokenFromUrl(AUTH_REDIRECT_TOKEN_KEY);
455
+ }
456
+ cleanTokenFromUrl(tokenKey);
457
+ cleanTokenFromUrl(AUTH_REDIRECT_TOKEN_KEY);
458
+ if (!candidateToken) {
459
+ candidateToken = getStoredToken(config);
460
+ }
461
+ if (candidateToken) {
462
+ let payload = null;
463
+ if (config?.jwksUrl) {
464
+ payload = await verifyToken(candidateToken, config.jwksUrl);
465
+ if (!payload) {
466
+ clearTokens(config);
467
+ setToken(null);
468
+ setUser(null);
469
+ setError(new Error("JWT signature verification failed"));
470
+ handleAuthFailure();
471
+ return;
472
+ }
473
+ if (isTokenExpired(candidateToken, config?.gracePeriodMs)) {
474
+ clearTokens(config);
475
+ setToken(null);
476
+ setUser(null);
477
+ setError(new Error("Token has expired"));
478
+ handleAuthFailure();
479
+ return;
480
+ }
481
+ } else {
482
+ const validation = validateToken(
483
+ candidateToken,
484
+ config?.gracePeriodMs
485
+ );
486
+ if (validation.isValid && validation.payload) {
487
+ payload = validation.payload;
488
+ } else {
489
+ clearTokens(config);
490
+ setToken(null);
491
+ setUser(null);
492
+ setError(new Error(validation.error ?? "Invalid token"));
493
+ handleAuthFailure();
494
+ return;
495
+ }
496
+ }
497
+ storeToken(candidateToken, config);
498
+ setToken(candidateToken);
499
+ setUser(payload);
500
+ setError(null);
501
+ } else {
502
+ setToken(null);
503
+ setUser(null);
504
+ setError(new Error("No authentication token found"));
505
+ handleAuthFailure();
506
+ }
507
+ } catch (err) {
508
+ const error2 = err instanceof Error ? err : new Error("Authentication error");
509
+ setError(error2);
510
+ setToken(null);
511
+ setUser(null);
512
+ handleAuthFailure();
513
+ } finally {
514
+ setIsLoading(false);
515
+ }
516
+ };
517
+ void initializeAuth();
518
+ }, []);
519
+ const clearAuth = useCallback(() => {
520
+ clearTokens(configRef.current);
521
+ setToken(null);
522
+ setUser(null);
523
+ setError(null);
524
+ }, []);
525
+ const contextValue = useMemo(
526
+ () => ({
527
+ isAuthenticated: user !== null,
528
+ isLoading,
529
+ user,
530
+ token,
531
+ clearAuth,
532
+ error
533
+ }),
534
+ [token, isLoading, user, clearAuth, error]
535
+ );
536
+ return /* @__PURE__ */ jsx(FluidAuthContext.Provider, { value: contextValue, children });
537
+ }
538
+ function useFluidAuthContext() {
539
+ const context = useContext(FluidAuthContext);
540
+ if (!context) {
541
+ throw new Error(
542
+ "useFluidAuthContext must be used within a FluidAuthProvider. Wrap your app with <FluidAuthProvider> to use authentication features."
543
+ );
544
+ }
545
+ return context;
546
+ }
547
+ function useFluidAuthOptional() {
548
+ return useContext(FluidAuthContext);
549
+ }
550
+
551
+ // ../../platform/api-client-core/src/fetch-client.ts
552
+ var ApiError = class _ApiError extends Error {
553
+ status;
554
+ data;
555
+ constructor(message, status, data) {
556
+ super(message);
557
+ this.name = "ApiError";
558
+ this.status = status;
559
+ this.data = data;
560
+ if ("captureStackTrace" in Error) {
561
+ Error.captureStackTrace(this, _ApiError);
562
+ }
563
+ }
564
+ toJSON() {
565
+ return {
566
+ name: this.name,
567
+ message: this.message,
568
+ status: this.status,
569
+ data: this.data
570
+ };
571
+ }
572
+ };
573
+ function createFetchClient(config) {
574
+ const { baseUrl, getAuthToken, onAuthError, defaultHeaders = {} } = config;
575
+ async function buildHeaders(customHeaders) {
576
+ const headers = {
577
+ "Content-Type": "application/json",
578
+ ...defaultHeaders,
579
+ ...customHeaders
580
+ };
581
+ if (getAuthToken) {
582
+ const token = await getAuthToken();
583
+ if (token) {
584
+ headers.Authorization = `Bearer ${token}`;
585
+ }
586
+ }
587
+ return headers;
588
+ }
589
+ function joinUrl(endpoint) {
590
+ return `${baseUrl}${endpoint}`;
591
+ }
592
+ function buildUrl(endpoint, params) {
593
+ const fullUrl = joinUrl(endpoint);
594
+ if (!params || Object.keys(params).length === 0) {
595
+ return fullUrl;
596
+ }
597
+ const queryString = new URLSearchParams();
598
+ Object.entries(params).forEach(([key, value]) => {
599
+ if (value === void 0 || value === null) {
600
+ return;
601
+ }
602
+ if (Array.isArray(value)) {
603
+ value.forEach((item) => queryString.append(`${key}[]`, String(item)));
604
+ } else if (typeof value === "object") {
605
+ Object.entries(value).forEach(([subKey, subValue]) => {
606
+ if (subValue === void 0 || subValue === null) {
607
+ return;
608
+ }
609
+ if (Array.isArray(subValue)) {
610
+ subValue.forEach(
611
+ (item) => queryString.append(`${key}[${subKey}][]`, String(item))
612
+ );
613
+ } else {
614
+ queryString.append(`${key}[${subKey}]`, String(subValue));
615
+ }
616
+ });
617
+ } else {
618
+ queryString.append(key, String(value));
619
+ }
620
+ });
621
+ const qs = queryString.toString();
622
+ return qs ? `${fullUrl}?${qs}` : fullUrl;
623
+ }
624
+ async function handleResponse(response, method, _url) {
625
+ if (response.status === 401 && onAuthError) {
626
+ onAuthError();
627
+ }
628
+ if (!response.ok) {
629
+ try {
630
+ const contentType2 = response.headers.get("content-type");
631
+ if (contentType2?.includes("application/json")) {
632
+ const data = await response.json();
633
+ throw new ApiError(
634
+ data.message || data.error_message || `${method} request failed`,
635
+ response.status,
636
+ data.errors || data
637
+ );
638
+ } else {
639
+ throw new ApiError(
640
+ `${method} request failed with status ${response.status}`,
641
+ response.status,
642
+ null
643
+ );
644
+ }
645
+ } catch (error) {
646
+ if (error instanceof ApiError) {
647
+ throw error;
648
+ }
649
+ throw new ApiError(
650
+ `${method} request failed with status ${response.status}`,
651
+ response.status,
652
+ null
653
+ );
654
+ }
655
+ }
656
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
657
+ return null;
658
+ }
659
+ const contentType = response.headers.get("content-type");
660
+ if (contentType?.includes("application/json")) {
661
+ try {
662
+ const data = await response.json();
663
+ return data;
664
+ } catch {
665
+ try {
666
+ const text = await response.text();
667
+ return text;
668
+ } catch {
669
+ return null;
670
+ }
671
+ }
672
+ }
673
+ return null;
674
+ }
675
+ async function request(endpoint, options = {}) {
676
+ const {
677
+ method = "GET",
678
+ headers: customHeaders,
679
+ params,
680
+ body,
681
+ signal
682
+ } = options;
683
+ const url = params ? buildUrl(endpoint, params) : joinUrl(endpoint);
684
+ const headers = await buildHeaders(customHeaders);
685
+ let response;
686
+ try {
687
+ const fetchOptions = { method, headers };
688
+ const serializedBody = body && method !== "GET" ? JSON.stringify(body) : null;
689
+ if (serializedBody) fetchOptions.body = serializedBody;
690
+ if (signal) fetchOptions.signal = signal;
691
+ response = await fetch(url, fetchOptions);
692
+ } catch (networkError) {
693
+ throw new ApiError(
694
+ `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
695
+ 0,
696
+ null
697
+ );
698
+ }
699
+ return handleResponse(response, method);
700
+ }
701
+ async function requestWithFormData(endpoint, formData, options = {}) {
702
+ const { method = "POST", headers: customHeaders, signal } = options;
703
+ const url = joinUrl(endpoint);
704
+ const headers = await buildHeaders(customHeaders);
705
+ delete headers["Content-Type"];
706
+ let response;
707
+ try {
708
+ const fetchOptions = { method, headers, body: formData };
709
+ if (signal) fetchOptions.signal = signal;
710
+ response = await fetch(url, fetchOptions);
711
+ } catch (networkError) {
712
+ throw new ApiError(
713
+ `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
714
+ 0,
715
+ null
716
+ );
717
+ }
718
+ return handleResponse(response, method);
719
+ }
720
+ return {
721
+ request,
722
+ requestWithFormData,
723
+ // Convenience methods for common HTTP verbs
724
+ get: (endpoint, params, options) => request(endpoint, {
725
+ ...options,
726
+ method: "GET",
727
+ ...params && { params }
728
+ }),
729
+ post: (endpoint, body, options) => request(endpoint, {
730
+ ...options,
731
+ method: "POST",
732
+ body
733
+ }),
734
+ put: (endpoint, body, options) => request(endpoint, {
735
+ ...options,
736
+ method: "PUT",
737
+ body
738
+ }),
739
+ patch: (endpoint, body, options) => request(endpoint, {
740
+ ...options,
741
+ method: "PATCH",
742
+ body
743
+ }),
744
+ delete: (endpoint, options) => request(endpoint, {
745
+ ...options,
746
+ method: "DELETE"
747
+ })
748
+ };
749
+ }
750
+
751
+ // ../../fluidos/api-client/src/namespaces/fluid_os.ts
752
+ var fluid_os_exports = {};
753
+ __export(fluid_os_exports, {
754
+ createFluidOSDefinition: () => createFluidOSDefinition,
755
+ createFluidOSNavigation: () => createFluidOSNavigation,
756
+ createFluidOSNavigationItem: () => createFluidOSNavigationItem,
757
+ createFluidOSProfile: () => createFluidOSProfile,
758
+ createFluidOSScreen: () => createFluidOSScreen,
759
+ createFluidOSTheme: () => createFluidOSTheme,
760
+ createFluidOSVersion: () => createFluidOSVersion,
761
+ deleteFluidOSDefinition: () => deleteFluidOSDefinition,
762
+ deleteFluidOSNavigation: () => deleteFluidOSNavigation,
763
+ deleteFluidOSNavigationItem: () => deleteFluidOSNavigationItem,
764
+ deleteFluidOSProfile: () => deleteFluidOSProfile,
765
+ deleteFluidOSScreen: () => deleteFluidOSScreen,
766
+ deleteFluidOSTheme: () => deleteFluidOSTheme,
767
+ getDefaultFluidOSProfile: () => getDefaultFluidOSProfile,
768
+ getFluidOSDefinition: () => getFluidOSDefinition,
769
+ getFluidOSManifest: () => getFluidOSManifest,
770
+ getFluidOSNavigation: () => getFluidOSNavigation,
771
+ getFluidOSNavigationItem: () => getFluidOSNavigationItem,
772
+ getFluidOSProfile: () => getFluidOSProfile,
773
+ getFluidOSScreen: () => getFluidOSScreen,
774
+ getFluidOSTheme: () => getFluidOSTheme,
775
+ getFluidOSVersion: () => getFluidOSVersion,
776
+ listFluidOSDefinitions: () => listFluidOSDefinitions,
777
+ listFluidOSNavigationItems: () => listFluidOSNavigationItems,
778
+ listFluidOSNavigations: () => listFluidOSNavigations,
779
+ listFluidOSProfiles: () => listFluidOSProfiles,
780
+ listFluidOSScreens: () => listFluidOSScreens,
781
+ listFluidOSThemes: () => listFluidOSThemes,
782
+ listFluidOSVersions: () => listFluidOSVersions,
783
+ updateFluidOSDefinition: () => updateFluidOSDefinition,
784
+ updateFluidOSNavigation: () => updateFluidOSNavigation,
785
+ updateFluidOSNavigationItem: () => updateFluidOSNavigationItem,
786
+ updateFluidOSProfile: () => updateFluidOSProfile,
787
+ updateFluidOSScreen: () => updateFluidOSScreen,
788
+ updateFluidOSTheme: () => updateFluidOSTheme,
789
+ updateFluidOSVersion: () => updateFluidOSVersion
790
+ });
791
+ async function listFluidOSDefinitions(client, params) {
792
+ return client.get(`/api/company/fluid_os/definitions`, params);
793
+ }
794
+ async function createFluidOSDefinition(client, body) {
795
+ return client.post(`/api/company/fluid_os/definitions`, body);
796
+ }
797
+ async function getFluidOSDefinition(client, id) {
798
+ return client.get(`/api/company/fluid_os/definitions/${id}`);
799
+ }
800
+ async function updateFluidOSDefinition(client, id, body) {
801
+ return client.put(`/api/company/fluid_os/definitions/${id}`, body);
802
+ }
803
+ async function deleteFluidOSDefinition(client, id) {
804
+ return client.delete(`/api/company/fluid_os/definitions/${id}`);
805
+ }
806
+ async function listFluidOSNavigationItems(client, definition_id, navigation_id) {
807
+ return client.get(
808
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items`
809
+ );
810
+ }
811
+ async function createFluidOSNavigationItem(client, definition_id, navigation_id, body) {
812
+ return client.post(
813
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items`,
814
+ body
815
+ );
816
+ }
817
+ async function getFluidOSNavigationItem(client, definition_id, navigation_id, id) {
818
+ return client.get(
819
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items/${id}`
820
+ );
821
+ }
822
+ async function updateFluidOSNavigationItem(client, definition_id, navigation_id, id, body) {
823
+ return client.put(
824
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items/${id}`,
825
+ body
826
+ );
827
+ }
828
+ async function deleteFluidOSNavigationItem(client, definition_id, navigation_id, id) {
829
+ return client.delete(
830
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items/${id}`
831
+ );
832
+ }
833
+ async function listFluidOSNavigations(client, definition_id, params) {
834
+ return client.get(
835
+ `/api/company/fluid_os/definitions/${definition_id}/navigations`,
836
+ params
837
+ );
838
+ }
839
+ async function createFluidOSNavigation(client, definition_id, body) {
840
+ return client.post(
841
+ `/api/company/fluid_os/definitions/${definition_id}/navigations`,
842
+ body
843
+ );
844
+ }
845
+ async function getFluidOSNavigation(client, definition_id, id) {
846
+ return client.get(
847
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${id}`
848
+ );
849
+ }
850
+ async function updateFluidOSNavigation(client, definition_id, id, body) {
851
+ return client.put(
852
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${id}`,
853
+ body
854
+ );
855
+ }
856
+ async function deleteFluidOSNavigation(client, definition_id, id) {
857
+ return client.delete(
858
+ `/api/company/fluid_os/definitions/${definition_id}/navigations/${id}`
859
+ );
860
+ }
861
+ async function listFluidOSProfiles(client, definition_id, params) {
862
+ return client.get(
863
+ `/api/company/fluid_os/definitions/${definition_id}/profiles`,
864
+ params
865
+ );
866
+ }
867
+ async function createFluidOSProfile(client, definition_id, body) {
868
+ return client.post(
869
+ `/api/company/fluid_os/definitions/${definition_id}/profiles`,
870
+ body
871
+ );
872
+ }
873
+ async function getDefaultFluidOSProfile(client, definition_id) {
874
+ return client.get(
875
+ `/api/company/fluid_os/definitions/${definition_id}/profiles/default`
876
+ );
877
+ }
878
+ async function getFluidOSProfile(client, definition_id, id) {
879
+ return client.get(
880
+ `/api/company/fluid_os/definitions/${definition_id}/profiles/${id}`
881
+ );
882
+ }
883
+ async function updateFluidOSProfile(client, definition_id, id, body) {
884
+ return client.put(
885
+ `/api/company/fluid_os/definitions/${definition_id}/profiles/${id}`,
886
+ body
887
+ );
888
+ }
889
+ async function deleteFluidOSProfile(client, definition_id, id) {
890
+ return client.delete(
891
+ `/api/company/fluid_os/definitions/${definition_id}/profiles/${id}`
892
+ );
893
+ }
894
+ async function getFluidOSManifest(client, params) {
895
+ return client.get(`/api/fluid_os/definitions/active`, params);
896
+ }
897
+ async function listFluidOSScreens(client, definition_id, params) {
898
+ return client.get(
899
+ `/api/company/fluid_os/definitions/${definition_id}/screens`,
900
+ params
901
+ );
902
+ }
903
+ async function createFluidOSScreen(client, definition_id, body) {
904
+ return client.post(
905
+ `/api/company/fluid_os/definitions/${definition_id}/screens`,
906
+ body
907
+ );
908
+ }
909
+ async function getFluidOSScreen(client, definition_id, id) {
910
+ return client.get(
911
+ `/api/company/fluid_os/definitions/${definition_id}/screens/${id}`
912
+ );
913
+ }
914
+ async function updateFluidOSScreen(client, definition_id, id, body) {
915
+ return client.put(
916
+ `/api/company/fluid_os/definitions/${definition_id}/screens/${id}`,
917
+ body
918
+ );
919
+ }
920
+ async function deleteFluidOSScreen(client, definition_id, id) {
921
+ return client.delete(
922
+ `/api/company/fluid_os/definitions/${definition_id}/screens/${id}`
923
+ );
924
+ }
925
+ async function listFluidOSThemes(client, definition_id, params) {
926
+ return client.get(
927
+ `/api/company/fluid_os/definitions/${definition_id}/themes`,
928
+ params
929
+ );
930
+ }
931
+ async function createFluidOSTheme(client, definition_id, body) {
932
+ return client.post(
933
+ `/api/company/fluid_os/definitions/${definition_id}/themes`,
934
+ body
935
+ );
936
+ }
937
+ async function getFluidOSTheme(client, definition_id, id) {
938
+ return client.get(
939
+ `/api/company/fluid_os/definitions/${definition_id}/themes/${id}`
940
+ );
941
+ }
942
+ async function updateFluidOSTheme(client, definition_id, id, body) {
943
+ return client.put(
944
+ `/api/company/fluid_os/definitions/${definition_id}/themes/${id}`,
945
+ body
946
+ );
947
+ }
948
+ async function deleteFluidOSTheme(client, definition_id, id) {
949
+ return client.delete(
950
+ `/api/company/fluid_os/definitions/${definition_id}/themes/${id}`
951
+ );
952
+ }
953
+ async function listFluidOSVersions(client, definition_id, params) {
954
+ return client.get(
955
+ `/api/company/fluid_os/definitions/${definition_id}/versions`,
956
+ params
957
+ );
958
+ }
959
+ async function createFluidOSVersion(client, definition_id) {
960
+ return client.post(
961
+ `/api/company/fluid_os/definitions/${definition_id}/versions`
962
+ );
963
+ }
964
+ async function getFluidOSVersion(client, definition_id, id) {
965
+ return client.get(
966
+ `/api/company/fluid_os/definitions/${definition_id}/versions/${id}`
967
+ );
968
+ }
969
+ async function updateFluidOSVersion(client, definition_id, id, body) {
970
+ return client.put(
971
+ `/api/company/fluid_os/definitions/${definition_id}/versions/${id}`,
972
+ body
973
+ );
974
+ }
975
+
976
+ // src/client/types.ts
977
+ var HTTP_METHODS = {
978
+ GET: "GET",
979
+ POST: "POST",
980
+ PUT: "PUT",
981
+ PATCH: "PATCH",
982
+ DELETE: "DELETE"
983
+ };
984
+
985
+ // src/transforms/screen-transforms.ts
986
+ function normalizeComponentTree(componentTree) {
987
+ if (!componentTree) return [];
988
+ if (Array.isArray(componentTree)) return componentTree;
989
+ if (typeof componentTree === "object") {
990
+ return [componentTree];
991
+ }
992
+ return [];
993
+ }
994
+ function toScreenDefinition(screen) {
995
+ return {
996
+ id: Number(screen.id),
997
+ slug: screen.slug ?? "",
998
+ name: screen.name ?? "",
999
+ component_tree: normalizeComponentTree(screen.component_tree)
1000
+ };
1001
+ }
1002
+
1003
+ // src/transforms/navigation-transforms.ts
1004
+ function toNavigationItem(item) {
1005
+ const children = (item.children ?? []).map(toNavigationItem).sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
1006
+ return {
1007
+ id: Number(item.id),
1008
+ label: item.label ?? "Untitled",
1009
+ // Use conditional spread for optional properties (exactOptionalPropertyTypes)
1010
+ ...item.slug != null ? { slug: String(item.slug) } : {},
1011
+ ...item.icon != null ? { icon: String(item.icon) } : {},
1012
+ ...item.screen_id != null ? { screen_id: Number(item.screen_id) } : {},
1013
+ ...item.parent_id != null ? { parent_id: Number(item.parent_id) } : {},
1014
+ position: item.position ?? 0,
1015
+ children
1016
+ };
1017
+ }
1018
+ function transformManifestToRepAppData(response) {
1019
+ const manifest = response.manifest;
1020
+ const rawProfile = manifest.profile;
1021
+ const rawThemes = Array.isArray(rawProfile?.themes) ? rawProfile.themes : [];
1022
+ const screens = (manifest.screens ?? []).map(
1023
+ (screen) => toScreenDefinition(screen)
1024
+ );
1025
+ const navigationItems = (rawProfile?.navigation?.navigation_items ?? []).map(
1026
+ toNavigationItem
1027
+ );
1028
+ const nav = rawProfile?.navigation;
1029
+ const activeThemeId = getActiveThemeId(rawThemes);
1030
+ return {
1031
+ definition_id: manifest.definition_id,
1032
+ published_version: manifest.published_version ?? 0,
1033
+ screens,
1034
+ profile: {
1035
+ name: rawProfile?.name ?? "Default",
1036
+ definition_id: rawProfile?.definition_id ?? manifest.definition_id,
1037
+ themes: transformThemes(rawThemes),
1038
+ // Conditional spread for exactOptionalPropertyTypes compliance
1039
+ ...activeThemeId !== void 0 ? { activeThemeId } : {},
1040
+ navigation: {
1041
+ definition_id: nav?.definition_id ?? manifest.definition_id,
1042
+ id: nav?.id ?? 0,
1043
+ name: nav?.name ?? "Main Navigation",
1044
+ navigation_items: navigationItems,
1045
+ screens
1046
+ }
1047
+ }
1048
+ };
1049
+ }
1050
+
1051
+ // src/client/fluid-client.ts
1052
+ var ApiError2 = class _ApiError extends Error {
1053
+ status;
1054
+ data;
1055
+ constructor(message, status, data) {
1056
+ super(message);
1057
+ this.name = "ApiError";
1058
+ this.status = status;
1059
+ this.data = data;
1060
+ const errorWithCapture = Error;
1061
+ if (errorWithCapture.captureStackTrace) {
1062
+ errorWithCapture.captureStackTrace(this, _ApiError);
1063
+ }
1064
+ }
1065
+ toJSON() {
1066
+ return {
1067
+ name: this.name,
1068
+ message: this.message,
1069
+ status: this.status,
1070
+ data: this.data
1071
+ };
1072
+ }
1073
+ };
1074
+ function isApiError2(error) {
1075
+ return error instanceof ApiError2;
1076
+ }
1077
+ function isString(value) {
1078
+ return typeof value === "string";
1079
+ }
1080
+ function extractErrorMessage(data, fallback) {
1081
+ if ("message" in data && isString(data.message)) {
1082
+ return data.message;
1083
+ }
1084
+ if ("error_message" in data && isString(data.error_message)) {
1085
+ return data.error_message;
1086
+ }
1087
+ if ("error" in data && isString(data.error)) {
1088
+ return data.error;
1089
+ }
1090
+ return fallback;
1091
+ }
1092
+ function createFluidClient(config) {
1093
+ const { baseUrl, getAuthToken, onAuthError, defaultHeaders = {} } = config;
1094
+ const effectiveOnAuthError = onAuthError ?? createDefaultAuthRedirect();
1095
+ const fetchClient = createFetchClient({
1096
+ baseUrl,
1097
+ ...getAuthToken ? { getAuthToken } : {},
1098
+ onAuthError: effectiveOnAuthError,
1099
+ defaultHeaders
1100
+ });
1101
+ async function buildHeaders(customHeaders) {
1102
+ const headers = {
1103
+ "Content-Type": "application/json",
1104
+ ...defaultHeaders,
1105
+ ...customHeaders
1106
+ };
1107
+ if (getAuthToken) {
1108
+ const token = await getAuthToken();
1109
+ if (token) {
1110
+ headers.Authorization = `Bearer ${token}`;
1111
+ }
1112
+ }
1113
+ return headers;
1114
+ }
1115
+ function buildUrl(endpoint, params) {
1116
+ const normalizedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
1117
+ const normalizedEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
1118
+ const url = new URL(normalizedBase + normalizedEndpoint);
1119
+ if (params) {
1120
+ for (const [key, value] of Object.entries(params)) {
1121
+ if (value === void 0 || value === null) {
1122
+ continue;
1123
+ }
1124
+ if (Array.isArray(value)) {
1125
+ for (const item of value) {
1126
+ url.searchParams.append(`${key}[]`, String(item));
1127
+ }
1128
+ } else if (typeof value === "object") {
1129
+ for (const [subKey, subValue] of Object.entries(
1130
+ value
1131
+ )) {
1132
+ if (subValue === void 0 || subValue === null) {
1133
+ continue;
1134
+ }
1135
+ if (Array.isArray(subValue)) {
1136
+ for (const item of subValue) {
1137
+ url.searchParams.append(`${key}[${subKey}][]`, String(item));
1138
+ }
1139
+ } else {
1140
+ url.searchParams.append(`${key}[${subKey}]`, String(subValue));
1141
+ }
1142
+ }
1143
+ } else {
1144
+ url.searchParams.append(key, String(value));
1145
+ }
1146
+ }
1147
+ }
1148
+ return url.toString();
1149
+ }
1150
+ const defaultRequestOptions = {
1151
+ method: HTTP_METHODS.GET
1152
+ };
1153
+ async function request(endpoint, options = {}) {
1154
+ const {
1155
+ method = defaultRequestOptions.method,
1156
+ headers: customHeaders,
1157
+ params,
1158
+ body,
1159
+ signal
1160
+ } = options;
1161
+ const url = buildUrl(
1162
+ endpoint,
1163
+ method === HTTP_METHODS.GET ? params : void 0
1164
+ );
1165
+ const headers = await buildHeaders(customHeaders);
1166
+ let response;
1167
+ try {
1168
+ const fetchOptions = {
1169
+ method,
1170
+ headers
1171
+ };
1172
+ if (signal !== void 0) {
1173
+ fetchOptions.signal = signal;
1174
+ }
1175
+ if (body && method !== HTTP_METHODS.GET) {
1176
+ fetchOptions.body = JSON.stringify(body);
1177
+ }
1178
+ response = await fetch(url, fetchOptions);
1179
+ } catch (networkError) {
1180
+ throw new ApiError2(
1181
+ `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
1182
+ 0,
1183
+ null
1184
+ );
1185
+ }
1186
+ if (response.status === 401) {
1187
+ effectiveOnAuthError();
1188
+ throw new ApiError2("Authentication required", 401, null);
1189
+ }
1190
+ if (!response.ok) {
1191
+ try {
1192
+ const contentType = response.headers.get("content-type");
1193
+ if (contentType?.includes("application/json")) {
1194
+ const data = await response.json();
1195
+ const errorMessage = extractErrorMessage(
1196
+ data,
1197
+ `${method} request failed`
1198
+ );
1199
+ throw new ApiError2(
1200
+ errorMessage,
1201
+ response.status,
1202
+ "errors" in data ? data.errors : data
1203
+ );
1204
+ } else {
1205
+ throw new ApiError2(
1206
+ `${method} request failed with status ${response.status}`,
1207
+ response.status,
1208
+ null
1209
+ );
1210
+ }
1211
+ } catch (error) {
1212
+ if (isApiError2(error)) {
1213
+ throw error;
1214
+ }
1215
+ throw new ApiError2(
1216
+ `${method} request failed with status ${response.status}`,
1217
+ response.status,
1218
+ null
1219
+ );
1220
+ }
1221
+ }
1222
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
1223
+ return null;
1224
+ }
1225
+ try {
1226
+ const data = await response.json();
1227
+ if (data === null || data === void 0) {
1228
+ throw new ApiError2(
1229
+ "Unexpected null/undefined in JSON response",
1230
+ response.status,
1231
+ null
1232
+ );
1233
+ }
1234
+ return data;
1235
+ } catch (parseError) {
1236
+ if (isApiError2(parseError)) {
1237
+ throw parseError;
1238
+ }
1239
+ throw new ApiError2(
1240
+ "Failed to parse response as JSON",
1241
+ response.status,
1242
+ null
1243
+ );
1244
+ }
1245
+ }
1246
+ async function requestNullable(endpoint, options = {}) {
1247
+ return request(endpoint, options);
1248
+ }
1249
+ async function safeRequest(endpoint, options = {}) {
1250
+ try {
1251
+ const data = await request(endpoint, options);
1252
+ return { success: true, data };
1253
+ } catch (error) {
1254
+ if (isApiError2(error)) {
1255
+ return { success: false, error };
1256
+ }
1257
+ return {
1258
+ success: false,
1259
+ error: new ApiError2(
1260
+ error instanceof Error ? error.message : "Unknown error",
1261
+ 0,
1262
+ null
1263
+ )
1264
+ };
1265
+ }
1266
+ }
1267
+ function toParams(params) {
1268
+ return params;
1269
+ }
1270
+ const get = (endpoint, params, options) => {
1271
+ const baseOptions = {
1272
+ ...options,
1273
+ method: HTTP_METHODS.GET
1274
+ };
1275
+ const convertedParams = toParams(params);
1276
+ const requestOptions = convertedParams !== void 0 ? { ...baseOptions, params: convertedParams } : baseOptions;
1277
+ return request(endpoint, requestOptions);
1278
+ };
1279
+ const post = (endpoint, body, options) => request(endpoint, {
1280
+ ...options,
1281
+ method: HTTP_METHODS.POST,
1282
+ body
1283
+ });
1284
+ const put = (endpoint, body, options) => request(endpoint, {
1285
+ ...options,
1286
+ method: HTTP_METHODS.PUT,
1287
+ body
1288
+ });
1289
+ const patch = (endpoint, body, options) => request(endpoint, {
1290
+ ...options,
1291
+ method: HTTP_METHODS.PATCH,
1292
+ body
1293
+ });
1294
+ const del = (endpoint, options) => request(endpoint, {
1295
+ ...options,
1296
+ method: HTTP_METHODS.DELETE
1297
+ });
1298
+ return {
1299
+ // Fluidos FetchClient for structured API calls
1300
+ fetchClient,
1301
+ // Low-level methods for custom endpoints
1302
+ request,
1303
+ requestNullable,
1304
+ safeRequest,
1305
+ get,
1306
+ post,
1307
+ put,
1308
+ patch,
1309
+ delete: del,
1310
+ // Products API - matches fluid-admin's /company/v1/products
1311
+ products: {
1312
+ list: (params) => get(
1313
+ "/company/v1/products",
1314
+ params
1315
+ ),
1316
+ get: (id) => get(`/company/v1/products/${id}`),
1317
+ search: (query, params) => get("/company/v1/products", {
1318
+ search_query: query,
1319
+ ...params
1320
+ })
1321
+ },
1322
+ // Orders API
1323
+ orders: {
1324
+ list: (params) => get("/orders", params),
1325
+ get: (id) => get(`/orders/${id}`),
1326
+ create: (data) => post("/orders", data)
1327
+ },
1328
+ // Users API
1329
+ users: {
1330
+ me: () => get("/api/me")
1331
+ },
1332
+ // Reps API
1333
+ reps: {
1334
+ current: () => get("/reps/me"),
1335
+ updateProfile: (data) => patch("/reps/me", data)
1336
+ },
1337
+ // Profile API (themes, navigation, screens) — legacy endpoint
1338
+ profile: {
1339
+ get: () => get("/rep_app/manifest")
1340
+ },
1341
+ // App API — fluidos endpoint (full manifest with transforms)
1342
+ app: {
1343
+ /** Fetch the raw manifest (plain JSON, no Color objects). Cache-safe. */
1344
+ getRaw: async () => {
1345
+ const raw = await fluid_os_exports.getFluidOSManifest(fetchClient, {
1346
+ platform: "browser"
1347
+ });
1348
+ return raw;
1349
+ },
1350
+ /** Fetch the active app definition with full theme/screen/navigation transforms */
1351
+ get: async () => {
1352
+ const raw = await fluid_os_exports.getFluidOSManifest(fetchClient, {
1353
+ platform: "browser"
1354
+ });
1355
+ return transformManifestToRepAppData(
1356
+ raw
1357
+ );
1358
+ }
1359
+ },
1360
+ // Permissions API
1361
+ permissions: {
1362
+ get: () => get("/company/roles/my_permissions")
1363
+ },
1364
+ // Analytics API
1365
+ analytics: {
1366
+ dashboard: () => get("/analytics/dashboard"),
1367
+ sales: (params) => get("/analytics/sales", params)
1368
+ }
1369
+ };
1370
+ }
1371
+
1372
+ // src/themes/index.ts
1373
+ var themes_exports = {};
1374
+ __reExport(themes_exports, theme_star);
1375
+ var ThemeContext = createContext(null);
1376
+ function applyThemeToDOM(theme, mode, container) {
1377
+ const target = container ?? document.documentElement;
1378
+ const resolved = (0, themes_exports.resolveTheme)(theme);
1379
+ (0, themes_exports.applyTheme)(resolved);
1380
+ target.dataset.theme = theme.id;
1381
+ if (mode) {
1382
+ target.dataset.themeMode = mode;
1383
+ } else {
1384
+ delete target.dataset.themeMode;
1385
+ }
1386
+ }
1387
+ function FluidThemeProvider({
1388
+ children,
1389
+ initialTheme,
1390
+ container
1391
+ }) {
1392
+ const [currentTheme, setCurrentTheme] = useState(
1393
+ initialTheme ?? null
1394
+ );
1395
+ const [mode, setMode] = useState(void 0);
1396
+ useEffect(() => {
1397
+ if (currentTheme) {
1398
+ applyThemeToDOM(currentTheme, mode, container ?? null);
1399
+ }
1400
+ return () => {
1401
+ (0, themes_exports.removeAllThemes)();
1402
+ };
1403
+ }, [currentTheme, mode, container]);
1404
+ const setTheme = useCallback((theme) => {
1405
+ setCurrentTheme(theme);
1406
+ }, []);
1407
+ const setThemeMode = useCallback((newMode) => {
1408
+ setMode(newMode);
1409
+ }, []);
1410
+ const value = useMemo(
1411
+ () => ({
1412
+ currentTheme,
1413
+ setTheme,
1414
+ setThemeMode,
1415
+ mode
1416
+ }),
1417
+ [currentTheme, setTheme, setThemeMode, mode]
1418
+ );
1419
+ return /* @__PURE__ */ jsx(ThemeContext.Provider, { value, children });
1420
+ }
1421
+ function useThemeContext() {
1422
+ const context = useContext(ThemeContext);
1423
+ if (!context) {
1424
+ throw new Error("useThemeContext must be used within a FluidThemeProvider");
1425
+ }
1426
+ return context;
1427
+ }
1428
+ var DEFAULT_SDK_WIDGET_REGISTRY = createWidgetRegistry({
1429
+ AlertWidget,
1430
+ CalendarWidget,
1431
+ CarouselWidget,
1432
+ CatchUpWidget,
1433
+ ChartWidget,
1434
+ ContainerWidget,
1435
+ EmbedWidget,
1436
+ ImageWidget,
1437
+ LayoutWidget,
1438
+ ListWidget,
1439
+ MySiteWidget,
1440
+ NestedWidget,
1441
+ QuickShareWidget,
1442
+ RecentActivityWidget,
1443
+ SpacerWidget,
1444
+ TableWidget,
1445
+ TextWidget,
1446
+ ToDoWidget,
1447
+ VideoWidget
1448
+ });
1449
+ var FluidContext = createContext(null);
1450
+ function FluidProvider({
1451
+ config,
1452
+ children,
1453
+ queryClient,
1454
+ initialTheme,
1455
+ themeContainer,
1456
+ widgetRegistry,
1457
+ variables
1458
+ }) {
1459
+ const defaultQueryClient = useMemo(
1460
+ () => new QueryClient({
1461
+ defaultOptions: {
1462
+ queries: {
1463
+ staleTime: 1e3 * 60,
1464
+ // 1 minute
1465
+ retry: 1
1466
+ }
1467
+ }
1468
+ }),
1469
+ []
1470
+ );
1471
+ const configRef = useRef(config);
1472
+ configRef.current = config;
1473
+ const client = useMemo(
1474
+ () => createFluidClient({
1475
+ ...configRef.current,
1476
+ getAuthToken: () => configRef.current.getAuthToken?.() ?? null,
1477
+ onAuthError: () => configRef.current.onAuthError?.()
1478
+ }),
1479
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1480
+ [config.baseUrl]
1481
+ );
1482
+ const contextValue = useMemo(
1483
+ () => ({ client, config: configRef.current }),
1484
+ [client]
1485
+ );
1486
+ const getApiHeaders = useCallback(() => {
1487
+ const headers = {
1488
+ "Content-Type": "application/json"
1489
+ };
1490
+ const getAuthToken = configRef.current.getAuthToken;
1491
+ if (typeof getAuthToken === "function") {
1492
+ const tokenOrPromise = getAuthToken();
1493
+ if (typeof tokenOrPromise === "string") {
1494
+ headers.Authorization = `Bearer ${tokenOrPromise}`;
1495
+ }
1496
+ }
1497
+ return headers;
1498
+ }, []);
1499
+ const dataSourceBaseUrl = useMemo(() => {
1500
+ const base = config.baseUrl.replace(/\/+$/, "");
1501
+ return base.endsWith("/api") ? base : `${base}/api`;
1502
+ }, [config.baseUrl]);
1503
+ const authContext = useFluidAuthOptional();
1504
+ const autoVariables = useMemo(() => {
1505
+ if (authContext?.user?.id != null) {
1506
+ return { rep_id: String(authContext.user.id) };
1507
+ }
1508
+ return void 0;
1509
+ }, [authContext?.user?.id]);
1510
+ const effectiveVariables = variables ?? autoVariables;
1511
+ const themeProviderProps = {
1512
+ ...initialTheme !== void 0 && { initialTheme },
1513
+ ...themeContainer !== void 0 && { container: themeContainer }
1514
+ };
1515
+ const registry = widgetRegistry ?? DEFAULT_SDK_WIDGET_REGISTRY;
1516
+ return /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient ?? defaultQueryClient, children: /* @__PURE__ */ jsx(FluidContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(
1517
+ DataSourceRegistryProvider,
1518
+ {
1519
+ baseUrl: dataSourceBaseUrl,
1520
+ getApiHeaders,
1521
+ variables: effectiveVariables,
1522
+ children: /* @__PURE__ */ jsx(RegistryProvider, { registry, children: /* @__PURE__ */ jsx(FluidThemeProvider, { ...themeProviderProps, children }) })
1523
+ }
1524
+ ) }) });
1525
+ }
1526
+ function useFluidContext() {
1527
+ const context = useContext(FluidContext);
1528
+ if (!context) {
1529
+ throw new Error("useFluidContext must be used within a FluidProvider");
1530
+ }
1531
+ return context;
1532
+ }
1533
+
1534
+ // src/hooks/use-fluid-api.ts
1535
+ function useFluidApi() {
1536
+ const { client } = useFluidContext();
1537
+ return client;
1538
+ }
1539
+
1540
+ // src/messaging/use-messaging-auth.ts
1541
+ var USERS_ME_QUERY_KEY = ["fluid", "users", "me"];
1542
+ function useMessagingAuth() {
1543
+ const auth = useFluidAuthContext();
1544
+ const api = useFluidApi();
1545
+ const {
1546
+ data: userMe,
1547
+ isLoading: isUserMeLoading,
1548
+ isError
1549
+ } = useQuery({
1550
+ queryKey: USERS_ME_QUERY_KEY,
1551
+ queryFn: () => api.users.me(),
1552
+ enabled: auth.isAuthenticated,
1553
+ staleTime: Infinity,
1554
+ retry: 1
1555
+ });
1556
+ if (auth.isLoading || auth.isAuthenticated && isUserMeLoading) {
1557
+ return {
1558
+ recipientId: null,
1559
+ companyId: null,
1560
+ currentUser: null,
1561
+ isLoading: true
1562
+ };
1563
+ }
1564
+ if (!auth.isAuthenticated || isError || !userMe) {
1565
+ return {
1566
+ recipientId: null,
1567
+ companyId: null,
1568
+ currentUser: null,
1569
+ isLoading: false
1570
+ };
1571
+ }
1572
+ const currentUser = userMe.recipient_id ? {
1573
+ id: userMe.id,
1574
+ recipientId: userMe.recipient_id,
1575
+ firstName: userMe.first_name ?? "",
1576
+ lastName: userMe.last_name ?? "",
1577
+ email: userMe.email,
1578
+ ...userMe.image_url != null && { imageUrl: userMe.image_url },
1579
+ ...userMe.affiliate_id != null && {
1580
+ affiliateId: userMe.affiliate_id
1581
+ }
1582
+ } : null;
1583
+ return {
1584
+ recipientId: userMe.recipient_id,
1585
+ companyId: userMe.company_id ?? null,
1586
+ currentUser,
1587
+ isLoading: false
1588
+ };
1589
+ }
1590
+ function deriveWebsocketUrl(baseUrl) {
1591
+ const base = baseUrl.replace(/\/+$/, "").replace(/\/api$/, "");
1592
+ return `${base}/cable`;
1593
+ }
1594
+ function useMessagingConfig() {
1595
+ const { config } = useFluidContext();
1596
+ const auth = useFluidAuthContext();
1597
+ const getHeaders = useCallback(async () => {
1598
+ const headers = {
1599
+ "Content-Type": "application/json",
1600
+ ...config.defaultHeaders
1601
+ };
1602
+ if (config.getAuthToken) {
1603
+ const token = await config.getAuthToken();
1604
+ if (token) {
1605
+ headers.Authorization = `Bearer ${token}`;
1606
+ }
1607
+ }
1608
+ return headers;
1609
+ }, [config]);
1610
+ const apiBaseUrl = useMemo(() => {
1611
+ const base = config.baseUrl.replace(/\/+$/, "");
1612
+ return base.endsWith("/api") ? base : `${base}/api`;
1613
+ }, [config.baseUrl]);
1614
+ const apiConfig = useMemo(
1615
+ () => ({
1616
+ baseUrl: apiBaseUrl,
1617
+ getHeaders,
1618
+ ...config.onAuthError != null && { onAuthError: config.onAuthError }
1619
+ }),
1620
+ [apiBaseUrl, config.onAuthError, getHeaders]
1621
+ );
1622
+ const websocketUrl = useMemo(
1623
+ () => config.websocketUrl ?? deriveWebsocketUrl(config.baseUrl),
1624
+ [config.websocketUrl, config.baseUrl]
1625
+ );
1626
+ return {
1627
+ apiConfig,
1628
+ websocketUrl,
1629
+ token: auth.token
1630
+ };
1631
+ }
1632
+ var FILESTACK_UPLOAD_URL = "https://www.filestackapi.com/api/store/S3";
1633
+ function getImageDimensions(file) {
1634
+ if (!file.type.startsWith("image/")) return Promise.resolve(null);
1635
+ return new Promise((resolve) => {
1636
+ const img = new Image();
1637
+ const url = URL.createObjectURL(file);
1638
+ img.onload = () => {
1639
+ URL.revokeObjectURL(url);
1640
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
1641
+ };
1642
+ img.onerror = () => {
1643
+ URL.revokeObjectURL(url);
1644
+ resolve(null);
1645
+ };
1646
+ img.src = url;
1647
+ });
1648
+ }
1649
+ function uploadToFilestack(file, apiKey, callbacks) {
1650
+ const xhr = new XMLHttpRequest();
1651
+ let aborted = false;
1652
+ getImageDimensions(file).then((metadata) => {
1653
+ if (aborted) return;
1654
+ const url = `${FILESTACK_UPLOAD_URL}?key=${encodeURIComponent(apiKey)}`;
1655
+ xhr.open("POST", url);
1656
+ xhr.setRequestHeader("Content-Type", file.type);
1657
+ xhr.upload.onprogress = (event) => {
1658
+ if (event.lengthComputable) {
1659
+ const progress = Math.round(event.loaded / event.total * 100);
1660
+ callbacks.onProgress(progress);
1661
+ }
1662
+ };
1663
+ xhr.onload = () => {
1664
+ if (xhr.status >= 200 && xhr.status < 300) {
1665
+ try {
1666
+ const response = JSON.parse(xhr.responseText);
1667
+ const result = {
1668
+ url: response.url,
1669
+ size: file.size,
1670
+ mimetype: file.type,
1671
+ kind: getFileTypeFromMimetype(file.type),
1672
+ metadata
1673
+ };
1674
+ callbacks.onSuccess(result);
1675
+ } catch {
1676
+ callbacks.onError(new Error("Failed to parse upload response"));
1677
+ }
1678
+ } else {
1679
+ callbacks.onError(
1680
+ new Error(`Upload failed with status ${xhr.status}`)
1681
+ );
1682
+ }
1683
+ };
1684
+ xhr.onerror = () => {
1685
+ if (!aborted) {
1686
+ callbacks.onError(new Error("Upload failed due to a network error"));
1687
+ }
1688
+ };
1689
+ xhr.onabort = () => {
1690
+ };
1691
+ xhr.send(file);
1692
+ }).catch((error) => {
1693
+ if (!aborted) {
1694
+ callbacks.onError(
1695
+ error instanceof Error ? error : new Error("Upload preparation failed")
1696
+ );
1697
+ }
1698
+ });
1699
+ return {
1700
+ abort: () => {
1701
+ aborted = true;
1702
+ xhr.abort();
1703
+ }
1704
+ };
1705
+ }
1706
+ function createFluidFileUploader(apiKey) {
1707
+ if (!apiKey) {
1708
+ return {
1709
+ uploadFile: (_file, callbacks) => {
1710
+ callbacks.onError(
1711
+ new Error(
1712
+ "File uploads are not configured. Set filestackApiKey in your SDK config to enable attachments."
1713
+ )
1714
+ );
1715
+ return { abort: () => {
1716
+ } };
1717
+ }
1718
+ };
1719
+ }
1720
+ return {
1721
+ uploadFile: (file, callbacks) => uploadToFilestack(file, apiKey, callbacks)
1722
+ };
1723
+ }
1724
+ function renderImage(props) {
1725
+ return /* @__PURE__ */ jsx(
1726
+ "img",
1727
+ {
1728
+ src: props.src,
1729
+ alt: props.alt,
1730
+ width: props.width,
1731
+ height: props.height,
1732
+ className: props.className
1733
+ }
1734
+ );
1735
+ }
1736
+ function defaultToast(message, type) {
1737
+ if (type === "error") {
1738
+ console.warn("[Messaging]", message);
1739
+ }
1740
+ }
1741
+ function MessagingScreen({
1742
+ onToast,
1743
+ filestackApiKey,
1744
+ websocketUrl: websocketUrlOverride,
1745
+ /* eslint-disable @typescript-eslint/no-unused-vars -- destructured to exclude from divProps spread */
1746
+ background,
1747
+ textColor,
1748
+ accentColor,
1749
+ padding,
1750
+ borderRadius,
1751
+ /* eslint-enable @typescript-eslint/no-unused-vars */
1752
+ ...divProps
1753
+ }) {
1754
+ const { config } = useFluidContext();
1755
+ const { apiConfig, websocketUrl, token } = useMessagingConfig();
1756
+ const messagingAuth = useMessagingAuth();
1757
+ const effectiveApiKey = filestackApiKey ?? config.filestackApiKey;
1758
+ const uploader = useMemo(
1759
+ () => createFluidFileUploader(effectiveApiKey),
1760
+ [effectiveApiKey]
1761
+ );
1762
+ const effectiveWsUrl = websocketUrlOverride ?? websocketUrl;
1763
+ const effectiveToast = onToast ?? defaultToast;
1764
+ const searchUsers = useCallback(
1765
+ async (query) => {
1766
+ const result = await listConnectedRecipients(apiConfig, {
1767
+ filterrific: { search_query: query },
1768
+ per_page: 10,
1769
+ page: 1
1770
+ });
1771
+ const recipients = result?.[1]?.items ?? [];
1772
+ return recipients.map((user) => {
1773
+ const hasName = [user.first_name, user.last_name].filter(Boolean).length > 0;
1774
+ const name = hasName ? [user.first_name, user.last_name].filter(Boolean).join(" ") : `User ${user.id}`;
1775
+ return {
1776
+ id: String(user.id),
1777
+ label: name,
1778
+ imageType: "user",
1779
+ userData: {
1780
+ first_name: user.first_name,
1781
+ last_name: user.last_name,
1782
+ image_url: user.avatar_url,
1783
+ phone: user.phone || void 0,
1784
+ email: user.email || void 0
1785
+ },
1786
+ conversationName: name
1787
+ };
1788
+ });
1789
+ },
1790
+ [apiConfig]
1791
+ );
1792
+ const searchChannels = useCallback(
1793
+ async (query) => {
1794
+ const channels = await searchConversations(apiConfig, {
1795
+ filterrific: { search_query: query }
1796
+ }) ?? [];
1797
+ return channels.map((channel) => {
1798
+ const { text: nameWithoutEmoji } = extractEmoji(channel.name);
1799
+ return {
1800
+ id: `channel-${channel.id}`,
1801
+ label: formatMessageChannelName(nameWithoutEmoji),
1802
+ imageType: "channel",
1803
+ userData: {
1804
+ first_name: channel.name,
1805
+ last_name: null,
1806
+ image_url: channel.avatar_url
1807
+ },
1808
+ conversationName: channel.name
1809
+ };
1810
+ });
1811
+ },
1812
+ [apiConfig]
1813
+ );
1814
+ if (messagingAuth.isLoading) {
1815
+ return /* @__PURE__ */ jsx(
1816
+ "div",
1817
+ {
1818
+ ...divProps,
1819
+ className: `flex h-full items-center justify-center ${divProps.className ?? ""}`,
1820
+ children: /* @__PURE__ */ jsx("div", { className: "text-muted-foreground", children: "Loading messaging..." })
1821
+ }
1822
+ );
1823
+ }
1824
+ if (!messagingAuth.recipientId) {
1825
+ return /* @__PURE__ */ jsx(
1826
+ "div",
1827
+ {
1828
+ ...divProps,
1829
+ className: `flex h-full items-center justify-center ${divProps.className ?? ""}`,
1830
+ children: /* @__PURE__ */ jsxs("div", { className: "max-w-sm rounded-lg border border-dashed border-border p-8 text-center", children: [
1831
+ /* @__PURE__ */ jsx("h2", { className: "text-xl font-semibold text-foreground", children: "Messaging" }),
1832
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-muted-foreground", children: "Messaging is not available for your account" })
1833
+ ] })
1834
+ }
1835
+ );
1836
+ }
1837
+ return /* @__PURE__ */ jsx("div", { ...divProps, className: `h-full ${divProps.className ?? ""}`, children: /* @__PURE__ */ jsx(
1838
+ MessagingApp,
1839
+ {
1840
+ config: apiConfig,
1841
+ auth: messagingAuth,
1842
+ websocketUrl: effectiveWsUrl,
1843
+ token,
1844
+ renderImage,
1845
+ showAdminFeatures: false,
1846
+ onToast: effectiveToast,
1847
+ messagesViewProps: {
1848
+ uploader,
1849
+ saveDrafts: true,
1850
+ onToast: effectiveToast
1851
+ },
1852
+ newMessageViewProps: {
1853
+ searchUsers,
1854
+ searchChannels
1855
+ }
1856
+ }
1857
+ ) });
1858
+ }
1859
+ var messagingScreenPropertySchema = {
1860
+ widgetType: "MessagingScreen",
1861
+ displayName: "Messaging Screen",
1862
+ tabsConfig: [{ id: "styling", label: "Styling" }],
1863
+ fields: []
1864
+ };
1865
+
1866
+ export { AUTH_CONSTANTS, ApiError2 as ApiError, DEFAULT_AUTH_URL, DEFAULT_SDK_WIDGET_REGISTRY, FluidAuthProvider, FluidProvider, FluidThemeProvider, MessagingScreen, STORAGE_KEYS, URL_PARAMS, USER_TYPES, cleanTokenFromUrl, clearTokens, createDefaultAuthRedirect, createFluidClient, createFluidFileUploader, decodeToken, extractAllTokensFromUrl, extractCompanyTokenFromUrl, extractTokenFromUrl, getStoredToken, getTokenExpiration, getTokenTimeRemaining, hasStoredToken, hasTokenInUrl, isApiError2 as isApiError, isTokenExpired, isUserType, isValidToken, messagingScreenPropertySchema, normalizeComponentTree, storeToken, themes_exports, toNavigationItem, toScreenDefinition, transformManifestToRepAppData, useFluidApi, useFluidAuthContext, useFluidContext, useMessagingAuth, useMessagingConfig, useThemeContext, validateToken };
1867
+ //# sourceMappingURL=chunk-7JMNKWPN.js.map
1868
+ //# sourceMappingURL=chunk-7JMNKWPN.js.map