@fluid-app/rep-sdk 0.1.2 → 0.1.4

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-5TEWFUX4.js +4 -0
  10. package/dist/{MessagingScreen-O42JEJMW.js.map → MessagingScreen-5TEWFUX4.js.map} +1 -1
  11. package/dist/MessagingScreen-JC7I55NG.cjs +17 -0
  12. package/dist/{MessagingScreen-UCVLYWZB.cjs.map → MessagingScreen-JC7I55NG.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-B6S6BEPL.cjs +16 -0
  26. package/dist/chunk-B6S6BEPL.cjs.map +1 -0
  27. package/dist/{chunk-WH7WZXT6.js → chunk-CMF2FYTD.js} +3 -3
  28. package/dist/{chunk-WH7WZXT6.js.map → chunk-CMF2FYTD.js.map} +1 -1
  29. package/dist/{chunk-MEOOAMH2.cjs → chunk-EOXYOOWS.cjs} +4 -4
  30. package/dist/{chunk-MEOOAMH2.cjs.map → chunk-EOXYOOWS.cjs.map} +1 -1
  31. package/dist/{chunk-YII3IXF4.cjs → chunk-FG2CI6HA.cjs} +4 -4
  32. package/dist/{chunk-YII3IXF4.cjs.map → chunk-FG2CI6HA.cjs.map} +1 -1
  33. package/dist/chunk-HDQ2JUQT.cjs +24 -0
  34. package/dist/chunk-HDQ2JUQT.cjs.map +1 -0
  35. package/dist/{chunk-MBUCXIUN.cjs → chunk-MHPK7YQ2.cjs} +4 -4
  36. package/dist/{chunk-MBUCXIUN.cjs.map → chunk-MHPK7YQ2.cjs.map} +1 -1
  37. package/dist/chunk-OE62VIZU.cjs +1955 -0
  38. package/dist/chunk-OE62VIZU.cjs.map +1 -0
  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-R4SXB6EV.js +1881 -0
  42. package/dist/chunk-R4SXB6EV.js.map +1 -0
  43. package/dist/chunk-RS4OSTES.js +14 -0
  44. package/dist/chunk-RS4OSTES.js.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 +1726 -1194
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.cts +2603 -0
  52. package/dist/index.d.ts +2603 -0
  53. package/dist/index.js +1395 -1021
  54. package/dist/index.js.map +1 -1
  55. package/package.json +26 -7
  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,1881 @@
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 mobileNav = rawProfile?.mobile_navigation;
1030
+ const mobileNavigationItems = (mobileNav?.navigation_items ?? []).map(
1031
+ toNavigationItem
1032
+ );
1033
+ const activeThemeId = getActiveThemeId(rawThemes);
1034
+ return {
1035
+ definition_id: manifest.definition_id,
1036
+ published_version: manifest.published_version ?? 0,
1037
+ screens,
1038
+ profile: {
1039
+ name: rawProfile?.name ?? "Default",
1040
+ definition_id: rawProfile?.definition_id ?? manifest.definition_id,
1041
+ themes: transformThemes(rawThemes),
1042
+ // Conditional spread for exactOptionalPropertyTypes compliance
1043
+ ...activeThemeId !== void 0 ? { activeThemeId } : {},
1044
+ navigation: {
1045
+ definition_id: nav?.definition_id ?? manifest.definition_id,
1046
+ id: nav?.id ?? 0,
1047
+ name: nav?.name ?? "Main Navigation",
1048
+ navigation_items: navigationItems,
1049
+ screens
1050
+ },
1051
+ ...mobileNav ? {
1052
+ mobile_navigation: {
1053
+ definition_id: mobileNav.definition_id ?? manifest.definition_id,
1054
+ id: mobileNav.id ?? 0,
1055
+ name: mobileNav.name ?? "Mobile Navigation",
1056
+ navigation_items: mobileNavigationItems,
1057
+ screens
1058
+ }
1059
+ } : {}
1060
+ }
1061
+ };
1062
+ }
1063
+
1064
+ // src/client/fluid-client.ts
1065
+ var ApiError2 = class _ApiError extends Error {
1066
+ status;
1067
+ data;
1068
+ constructor(message, status, data) {
1069
+ super(message);
1070
+ this.name = "ApiError";
1071
+ this.status = status;
1072
+ this.data = data;
1073
+ const errorWithCapture = Error;
1074
+ if (errorWithCapture.captureStackTrace) {
1075
+ errorWithCapture.captureStackTrace(this, _ApiError);
1076
+ }
1077
+ }
1078
+ toJSON() {
1079
+ return {
1080
+ name: this.name,
1081
+ message: this.message,
1082
+ status: this.status,
1083
+ data: this.data
1084
+ };
1085
+ }
1086
+ };
1087
+ function isApiError2(error) {
1088
+ return error instanceof ApiError2;
1089
+ }
1090
+ function isString(value) {
1091
+ return typeof value === "string";
1092
+ }
1093
+ function extractErrorMessage(data, fallback) {
1094
+ if ("message" in data && isString(data.message)) {
1095
+ return data.message;
1096
+ }
1097
+ if ("error_message" in data && isString(data.error_message)) {
1098
+ return data.error_message;
1099
+ }
1100
+ if ("error" in data && isString(data.error)) {
1101
+ return data.error;
1102
+ }
1103
+ return fallback;
1104
+ }
1105
+ function createFluidClient(config) {
1106
+ const { baseUrl, getAuthToken, onAuthError, defaultHeaders = {} } = config;
1107
+ const effectiveOnAuthError = onAuthError ?? createDefaultAuthRedirect();
1108
+ const fetchClient = createFetchClient({
1109
+ baseUrl,
1110
+ ...getAuthToken ? { getAuthToken } : {},
1111
+ onAuthError: effectiveOnAuthError,
1112
+ defaultHeaders
1113
+ });
1114
+ async function buildHeaders(customHeaders) {
1115
+ const headers = {
1116
+ "Content-Type": "application/json",
1117
+ ...defaultHeaders,
1118
+ ...customHeaders
1119
+ };
1120
+ if (getAuthToken) {
1121
+ const token = await getAuthToken();
1122
+ if (token) {
1123
+ headers.Authorization = `Bearer ${token}`;
1124
+ }
1125
+ }
1126
+ return headers;
1127
+ }
1128
+ function buildUrl(endpoint, params) {
1129
+ const normalizedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
1130
+ const normalizedEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
1131
+ const url = new URL(normalizedBase + normalizedEndpoint);
1132
+ if (params) {
1133
+ for (const [key, value] of Object.entries(params)) {
1134
+ if (value === void 0 || value === null) {
1135
+ continue;
1136
+ }
1137
+ if (Array.isArray(value)) {
1138
+ for (const item of value) {
1139
+ url.searchParams.append(`${key}[]`, String(item));
1140
+ }
1141
+ } else if (typeof value === "object") {
1142
+ for (const [subKey, subValue] of Object.entries(
1143
+ value
1144
+ )) {
1145
+ if (subValue === void 0 || subValue === null) {
1146
+ continue;
1147
+ }
1148
+ if (Array.isArray(subValue)) {
1149
+ for (const item of subValue) {
1150
+ url.searchParams.append(`${key}[${subKey}][]`, String(item));
1151
+ }
1152
+ } else {
1153
+ url.searchParams.append(`${key}[${subKey}]`, String(subValue));
1154
+ }
1155
+ }
1156
+ } else {
1157
+ url.searchParams.append(key, String(value));
1158
+ }
1159
+ }
1160
+ }
1161
+ return url.toString();
1162
+ }
1163
+ const defaultRequestOptions = {
1164
+ method: HTTP_METHODS.GET
1165
+ };
1166
+ async function request(endpoint, options = {}) {
1167
+ const {
1168
+ method = defaultRequestOptions.method,
1169
+ headers: customHeaders,
1170
+ params,
1171
+ body,
1172
+ signal
1173
+ } = options;
1174
+ const url = buildUrl(
1175
+ endpoint,
1176
+ method === HTTP_METHODS.GET ? params : void 0
1177
+ );
1178
+ const headers = await buildHeaders(customHeaders);
1179
+ let response;
1180
+ try {
1181
+ const fetchOptions = {
1182
+ method,
1183
+ headers
1184
+ };
1185
+ if (signal !== void 0) {
1186
+ fetchOptions.signal = signal;
1187
+ }
1188
+ if (body && method !== HTTP_METHODS.GET) {
1189
+ fetchOptions.body = JSON.stringify(body);
1190
+ }
1191
+ response = await fetch(url, fetchOptions);
1192
+ } catch (networkError) {
1193
+ throw new ApiError2(
1194
+ `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
1195
+ 0,
1196
+ null
1197
+ );
1198
+ }
1199
+ if (response.status === 401) {
1200
+ effectiveOnAuthError();
1201
+ throw new ApiError2("Authentication required", 401, null);
1202
+ }
1203
+ if (!response.ok) {
1204
+ try {
1205
+ const contentType = response.headers.get("content-type");
1206
+ if (contentType?.includes("application/json")) {
1207
+ const data = await response.json();
1208
+ const errorMessage = extractErrorMessage(
1209
+ data,
1210
+ `${method} request failed`
1211
+ );
1212
+ throw new ApiError2(
1213
+ errorMessage,
1214
+ response.status,
1215
+ "errors" in data ? data.errors : data
1216
+ );
1217
+ } else {
1218
+ throw new ApiError2(
1219
+ `${method} request failed with status ${response.status}`,
1220
+ response.status,
1221
+ null
1222
+ );
1223
+ }
1224
+ } catch (error) {
1225
+ if (isApiError2(error)) {
1226
+ throw error;
1227
+ }
1228
+ throw new ApiError2(
1229
+ `${method} request failed with status ${response.status}`,
1230
+ response.status,
1231
+ null
1232
+ );
1233
+ }
1234
+ }
1235
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
1236
+ return null;
1237
+ }
1238
+ try {
1239
+ const data = await response.json();
1240
+ if (data === null || data === void 0) {
1241
+ throw new ApiError2(
1242
+ "Unexpected null/undefined in JSON response",
1243
+ response.status,
1244
+ null
1245
+ );
1246
+ }
1247
+ return data;
1248
+ } catch (parseError) {
1249
+ if (isApiError2(parseError)) {
1250
+ throw parseError;
1251
+ }
1252
+ throw new ApiError2(
1253
+ "Failed to parse response as JSON",
1254
+ response.status,
1255
+ null
1256
+ );
1257
+ }
1258
+ }
1259
+ async function requestNullable(endpoint, options = {}) {
1260
+ return request(endpoint, options);
1261
+ }
1262
+ async function safeRequest(endpoint, options = {}) {
1263
+ try {
1264
+ const data = await request(endpoint, options);
1265
+ return { success: true, data };
1266
+ } catch (error) {
1267
+ if (isApiError2(error)) {
1268
+ return { success: false, error };
1269
+ }
1270
+ return {
1271
+ success: false,
1272
+ error: new ApiError2(
1273
+ error instanceof Error ? error.message : "Unknown error",
1274
+ 0,
1275
+ null
1276
+ )
1277
+ };
1278
+ }
1279
+ }
1280
+ function toParams(params) {
1281
+ return params;
1282
+ }
1283
+ const get = (endpoint, params, options) => {
1284
+ const baseOptions = {
1285
+ ...options,
1286
+ method: HTTP_METHODS.GET
1287
+ };
1288
+ const convertedParams = toParams(params);
1289
+ const requestOptions = convertedParams !== void 0 ? { ...baseOptions, params: convertedParams } : baseOptions;
1290
+ return request(endpoint, requestOptions);
1291
+ };
1292
+ const post = (endpoint, body, options) => request(endpoint, {
1293
+ ...options,
1294
+ method: HTTP_METHODS.POST,
1295
+ body
1296
+ });
1297
+ const put = (endpoint, body, options) => request(endpoint, {
1298
+ ...options,
1299
+ method: HTTP_METHODS.PUT,
1300
+ body
1301
+ });
1302
+ const patch = (endpoint, body, options) => request(endpoint, {
1303
+ ...options,
1304
+ method: HTTP_METHODS.PATCH,
1305
+ body
1306
+ });
1307
+ const del = (endpoint, options) => request(endpoint, {
1308
+ ...options,
1309
+ method: HTTP_METHODS.DELETE
1310
+ });
1311
+ return {
1312
+ // Fluidos FetchClient for structured API calls
1313
+ fetchClient,
1314
+ // Low-level methods for custom endpoints
1315
+ request,
1316
+ requestNullable,
1317
+ safeRequest,
1318
+ get,
1319
+ post,
1320
+ put,
1321
+ patch,
1322
+ delete: del,
1323
+ // Products API - matches fluid-admin's /company/v1/products
1324
+ products: {
1325
+ list: (params) => get(
1326
+ "/company/v1/products",
1327
+ params
1328
+ ),
1329
+ get: (id) => get(`/company/v1/products/${id}`),
1330
+ search: (query, params) => get("/company/v1/products", {
1331
+ search_query: query,
1332
+ ...params
1333
+ })
1334
+ },
1335
+ // Orders API
1336
+ orders: {
1337
+ list: (params) => get("/orders", params),
1338
+ get: (id) => get(`/orders/${id}`),
1339
+ create: (data) => post("/orders", data)
1340
+ },
1341
+ // Users API
1342
+ users: {
1343
+ me: () => get("/api/me")
1344
+ },
1345
+ // Reps API
1346
+ reps: {
1347
+ current: () => get("/reps/me"),
1348
+ updateProfile: (data) => patch("/reps/me", data)
1349
+ },
1350
+ // Profile API (themes, navigation, screens) — legacy endpoint
1351
+ profile: {
1352
+ get: () => get("/rep_app/manifest")
1353
+ },
1354
+ // App API — fluidos endpoint (full manifest with transforms)
1355
+ app: {
1356
+ /** Fetch the raw manifest (plain JSON, no Color objects). Cache-safe. */
1357
+ getRaw: async () => {
1358
+ const raw = await fluid_os_exports.getFluidOSManifest(fetchClient, {
1359
+ platform: "browser"
1360
+ });
1361
+ return raw;
1362
+ },
1363
+ /** Fetch the active app definition with full theme/screen/navigation transforms */
1364
+ get: async () => {
1365
+ const raw = await fluid_os_exports.getFluidOSManifest(fetchClient, {
1366
+ platform: "browser"
1367
+ });
1368
+ return transformManifestToRepAppData(
1369
+ raw
1370
+ );
1371
+ }
1372
+ },
1373
+ // Permissions API
1374
+ permissions: {
1375
+ get: () => get("/company/roles/my_permissions")
1376
+ },
1377
+ // Analytics API
1378
+ analytics: {
1379
+ dashboard: () => get("/analytics/dashboard"),
1380
+ sales: (params) => get("/analytics/sales", params)
1381
+ }
1382
+ };
1383
+ }
1384
+
1385
+ // src/themes/index.ts
1386
+ var themes_exports = {};
1387
+ __reExport(themes_exports, theme_star);
1388
+ var ThemeContext = createContext(null);
1389
+ function applyThemeToDOM(theme, mode, container) {
1390
+ const target = container ?? document.documentElement;
1391
+ const resolved = (0, themes_exports.resolveTheme)(theme);
1392
+ (0, themes_exports.applyTheme)(resolved);
1393
+ target.dataset.theme = theme.id;
1394
+ if (mode) {
1395
+ target.dataset.themeMode = mode;
1396
+ } else {
1397
+ delete target.dataset.themeMode;
1398
+ }
1399
+ }
1400
+ function FluidThemeProvider({
1401
+ children,
1402
+ initialTheme,
1403
+ container
1404
+ }) {
1405
+ const [currentTheme, setCurrentTheme] = useState(
1406
+ initialTheme ?? null
1407
+ );
1408
+ const [mode, setMode] = useState(void 0);
1409
+ useEffect(() => {
1410
+ if (currentTheme) {
1411
+ applyThemeToDOM(currentTheme, mode, container ?? null);
1412
+ }
1413
+ return () => {
1414
+ (0, themes_exports.removeAllThemes)();
1415
+ };
1416
+ }, [currentTheme, mode, container]);
1417
+ const setTheme = useCallback((theme) => {
1418
+ setCurrentTheme(theme);
1419
+ }, []);
1420
+ const setThemeMode = useCallback((newMode) => {
1421
+ setMode(newMode);
1422
+ }, []);
1423
+ const value = useMemo(
1424
+ () => ({
1425
+ currentTheme,
1426
+ setTheme,
1427
+ setThemeMode,
1428
+ mode
1429
+ }),
1430
+ [currentTheme, setTheme, setThemeMode, mode]
1431
+ );
1432
+ return /* @__PURE__ */ jsx(ThemeContext.Provider, { value, children });
1433
+ }
1434
+ function useThemeContext() {
1435
+ const context = useContext(ThemeContext);
1436
+ if (!context) {
1437
+ throw new Error("useThemeContext must be used within a FluidThemeProvider");
1438
+ }
1439
+ return context;
1440
+ }
1441
+ var DEFAULT_SDK_WIDGET_REGISTRY = createWidgetRegistry({
1442
+ AlertWidget,
1443
+ CalendarWidget,
1444
+ CarouselWidget,
1445
+ CatchUpWidget,
1446
+ ChartWidget,
1447
+ ContainerWidget,
1448
+ EmbedWidget,
1449
+ ImageWidget,
1450
+ LayoutWidget,
1451
+ ListWidget,
1452
+ MySiteWidget,
1453
+ NestedWidget,
1454
+ QuickShareWidget,
1455
+ RecentActivityWidget,
1456
+ SpacerWidget,
1457
+ TableWidget,
1458
+ TextWidget,
1459
+ ToDoWidget,
1460
+ VideoWidget
1461
+ });
1462
+ var FluidContext = createContext(null);
1463
+ function FluidProvider({
1464
+ config,
1465
+ children,
1466
+ queryClient,
1467
+ initialTheme,
1468
+ themeContainer,
1469
+ widgetRegistry,
1470
+ variables
1471
+ }) {
1472
+ const defaultQueryClient = useMemo(
1473
+ () => new QueryClient({
1474
+ defaultOptions: {
1475
+ queries: {
1476
+ staleTime: 1e3 * 60,
1477
+ // 1 minute
1478
+ retry: 1
1479
+ }
1480
+ }
1481
+ }),
1482
+ []
1483
+ );
1484
+ const configRef = useRef(config);
1485
+ configRef.current = config;
1486
+ const client = useMemo(
1487
+ () => createFluidClient({
1488
+ ...configRef.current,
1489
+ getAuthToken: () => configRef.current.getAuthToken?.() ?? null,
1490
+ onAuthError: () => configRef.current.onAuthError?.()
1491
+ }),
1492
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1493
+ [config.baseUrl]
1494
+ );
1495
+ const contextValue = useMemo(
1496
+ () => ({ client, config: configRef.current }),
1497
+ [client]
1498
+ );
1499
+ const getApiHeaders = useCallback(() => {
1500
+ const headers = {
1501
+ "Content-Type": "application/json"
1502
+ };
1503
+ const getAuthToken = configRef.current.getAuthToken;
1504
+ if (typeof getAuthToken === "function") {
1505
+ const tokenOrPromise = getAuthToken();
1506
+ if (typeof tokenOrPromise === "string") {
1507
+ headers.Authorization = `Bearer ${tokenOrPromise}`;
1508
+ }
1509
+ }
1510
+ return headers;
1511
+ }, []);
1512
+ const dataSourceBaseUrl = useMemo(() => {
1513
+ const base = config.baseUrl.replace(/\/+$/, "");
1514
+ return base.endsWith("/api") ? base : `${base}/api`;
1515
+ }, [config.baseUrl]);
1516
+ const authContext = useFluidAuthOptional();
1517
+ const autoVariables = useMemo(() => {
1518
+ if (authContext?.user?.id != null) {
1519
+ return { rep_id: String(authContext.user.id) };
1520
+ }
1521
+ return void 0;
1522
+ }, [authContext?.user?.id]);
1523
+ const effectiveVariables = variables ?? autoVariables;
1524
+ const themeProviderProps = {
1525
+ ...initialTheme !== void 0 && { initialTheme },
1526
+ ...themeContainer !== void 0 && { container: themeContainer }
1527
+ };
1528
+ const registry = widgetRegistry ?? DEFAULT_SDK_WIDGET_REGISTRY;
1529
+ return /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient ?? defaultQueryClient, children: /* @__PURE__ */ jsx(FluidContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(
1530
+ DataSourceRegistryProvider,
1531
+ {
1532
+ baseUrl: dataSourceBaseUrl,
1533
+ getApiHeaders,
1534
+ variables: effectiveVariables,
1535
+ children: /* @__PURE__ */ jsx(RegistryProvider, { registry, children: /* @__PURE__ */ jsx(FluidThemeProvider, { ...themeProviderProps, children }) })
1536
+ }
1537
+ ) }) });
1538
+ }
1539
+ function useFluidContext() {
1540
+ const context = useContext(FluidContext);
1541
+ if (!context) {
1542
+ throw new Error("useFluidContext must be used within a FluidProvider");
1543
+ }
1544
+ return context;
1545
+ }
1546
+
1547
+ // src/hooks/use-fluid-api.ts
1548
+ function useFluidApi() {
1549
+ const { client } = useFluidContext();
1550
+ return client;
1551
+ }
1552
+
1553
+ // src/messaging/use-messaging-auth.ts
1554
+ var USERS_ME_QUERY_KEY = ["fluid", "users", "me"];
1555
+ function useMessagingAuth() {
1556
+ const auth = useFluidAuthContext();
1557
+ const api = useFluidApi();
1558
+ const {
1559
+ data: userMe,
1560
+ isLoading: isUserMeLoading,
1561
+ isError
1562
+ } = useQuery({
1563
+ queryKey: USERS_ME_QUERY_KEY,
1564
+ queryFn: () => api.users.me(),
1565
+ enabled: auth.isAuthenticated,
1566
+ staleTime: Infinity,
1567
+ retry: 1
1568
+ });
1569
+ if (auth.isLoading || auth.isAuthenticated && isUserMeLoading) {
1570
+ return {
1571
+ recipientId: null,
1572
+ companyId: null,
1573
+ currentUser: null,
1574
+ isLoading: true
1575
+ };
1576
+ }
1577
+ if (!auth.isAuthenticated || isError || !userMe) {
1578
+ return {
1579
+ recipientId: null,
1580
+ companyId: null,
1581
+ currentUser: null,
1582
+ isLoading: false
1583
+ };
1584
+ }
1585
+ const currentUser = userMe.recipient_id ? {
1586
+ id: userMe.id,
1587
+ recipientId: userMe.recipient_id,
1588
+ firstName: userMe.first_name ?? "",
1589
+ lastName: userMe.last_name ?? "",
1590
+ email: userMe.email,
1591
+ ...userMe.image_url != null && { imageUrl: userMe.image_url },
1592
+ ...userMe.affiliate_id != null && {
1593
+ affiliateId: userMe.affiliate_id
1594
+ }
1595
+ } : null;
1596
+ return {
1597
+ recipientId: userMe.recipient_id,
1598
+ companyId: userMe.company_id ?? null,
1599
+ currentUser,
1600
+ isLoading: false
1601
+ };
1602
+ }
1603
+ function deriveWebsocketUrl(baseUrl) {
1604
+ const base = baseUrl.replace(/\/+$/, "").replace(/\/api$/, "");
1605
+ return `${base}/cable`;
1606
+ }
1607
+ function useMessagingConfig() {
1608
+ const { config } = useFluidContext();
1609
+ const auth = useFluidAuthContext();
1610
+ const getHeaders = useCallback(async () => {
1611
+ const headers = {
1612
+ "Content-Type": "application/json",
1613
+ ...config.defaultHeaders
1614
+ };
1615
+ if (config.getAuthToken) {
1616
+ const token = await config.getAuthToken();
1617
+ if (token) {
1618
+ headers.Authorization = `Bearer ${token}`;
1619
+ }
1620
+ }
1621
+ return headers;
1622
+ }, [config]);
1623
+ const apiBaseUrl = useMemo(() => {
1624
+ const base = config.baseUrl.replace(/\/+$/, "");
1625
+ return base.endsWith("/api") ? base : `${base}/api`;
1626
+ }, [config.baseUrl]);
1627
+ const apiConfig = useMemo(
1628
+ () => ({
1629
+ baseUrl: apiBaseUrl,
1630
+ getHeaders,
1631
+ ...config.onAuthError != null && { onAuthError: config.onAuthError }
1632
+ }),
1633
+ [apiBaseUrl, config.onAuthError, getHeaders]
1634
+ );
1635
+ const websocketUrl = useMemo(
1636
+ () => config.websocketUrl ?? deriveWebsocketUrl(config.baseUrl),
1637
+ [config.websocketUrl, config.baseUrl]
1638
+ );
1639
+ return {
1640
+ apiConfig,
1641
+ websocketUrl,
1642
+ token: auth.token
1643
+ };
1644
+ }
1645
+ var FILESTACK_UPLOAD_URL = "https://www.filestackapi.com/api/store/S3";
1646
+ function getImageDimensions(file) {
1647
+ if (!file.type.startsWith("image/")) return Promise.resolve(null);
1648
+ return new Promise((resolve) => {
1649
+ const img = new Image();
1650
+ const url = URL.createObjectURL(file);
1651
+ img.onload = () => {
1652
+ URL.revokeObjectURL(url);
1653
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
1654
+ };
1655
+ img.onerror = () => {
1656
+ URL.revokeObjectURL(url);
1657
+ resolve(null);
1658
+ };
1659
+ img.src = url;
1660
+ });
1661
+ }
1662
+ function uploadToFilestack(file, apiKey, callbacks) {
1663
+ const xhr = new XMLHttpRequest();
1664
+ let aborted = false;
1665
+ getImageDimensions(file).then((metadata) => {
1666
+ if (aborted) return;
1667
+ const url = `${FILESTACK_UPLOAD_URL}?key=${encodeURIComponent(apiKey)}`;
1668
+ xhr.open("POST", url);
1669
+ xhr.setRequestHeader("Content-Type", file.type);
1670
+ xhr.upload.onprogress = (event) => {
1671
+ if (event.lengthComputable) {
1672
+ const progress = Math.round(event.loaded / event.total * 100);
1673
+ callbacks.onProgress(progress);
1674
+ }
1675
+ };
1676
+ xhr.onload = () => {
1677
+ if (xhr.status >= 200 && xhr.status < 300) {
1678
+ try {
1679
+ const response = JSON.parse(xhr.responseText);
1680
+ const result = {
1681
+ url: response.url,
1682
+ size: file.size,
1683
+ mimetype: file.type,
1684
+ kind: getFileTypeFromMimetype(file.type),
1685
+ metadata
1686
+ };
1687
+ callbacks.onSuccess(result);
1688
+ } catch {
1689
+ callbacks.onError(new Error("Failed to parse upload response"));
1690
+ }
1691
+ } else {
1692
+ callbacks.onError(
1693
+ new Error(`Upload failed with status ${xhr.status}`)
1694
+ );
1695
+ }
1696
+ };
1697
+ xhr.onerror = () => {
1698
+ if (!aborted) {
1699
+ callbacks.onError(new Error("Upload failed due to a network error"));
1700
+ }
1701
+ };
1702
+ xhr.onabort = () => {
1703
+ };
1704
+ xhr.send(file);
1705
+ }).catch((error) => {
1706
+ if (!aborted) {
1707
+ callbacks.onError(
1708
+ error instanceof Error ? error : new Error("Upload preparation failed")
1709
+ );
1710
+ }
1711
+ });
1712
+ return {
1713
+ abort: () => {
1714
+ aborted = true;
1715
+ xhr.abort();
1716
+ }
1717
+ };
1718
+ }
1719
+ function createFluidFileUploader(apiKey) {
1720
+ if (!apiKey) {
1721
+ return {
1722
+ uploadFile: (_file, callbacks) => {
1723
+ callbacks.onError(
1724
+ new Error(
1725
+ "File uploads are not configured. Set filestackApiKey in your SDK config to enable attachments."
1726
+ )
1727
+ );
1728
+ return { abort: () => {
1729
+ } };
1730
+ }
1731
+ };
1732
+ }
1733
+ return {
1734
+ uploadFile: (file, callbacks) => uploadToFilestack(file, apiKey, callbacks)
1735
+ };
1736
+ }
1737
+ function renderImage(props) {
1738
+ return /* @__PURE__ */ jsx(
1739
+ "img",
1740
+ {
1741
+ src: props.src,
1742
+ alt: props.alt,
1743
+ width: props.width,
1744
+ height: props.height,
1745
+ className: props.className
1746
+ }
1747
+ );
1748
+ }
1749
+ function defaultToast(message, type) {
1750
+ if (type === "error") {
1751
+ console.warn("[Messaging]", message);
1752
+ }
1753
+ }
1754
+ function MessagingScreen({
1755
+ onToast,
1756
+ filestackApiKey,
1757
+ websocketUrl: websocketUrlOverride,
1758
+ /* eslint-disable @typescript-eslint/no-unused-vars -- destructured to exclude from divProps spread */
1759
+ background,
1760
+ textColor,
1761
+ accentColor,
1762
+ padding,
1763
+ borderRadius,
1764
+ /* eslint-enable @typescript-eslint/no-unused-vars */
1765
+ ...divProps
1766
+ }) {
1767
+ const { config } = useFluidContext();
1768
+ const { apiConfig, websocketUrl, token } = useMessagingConfig();
1769
+ const messagingAuth = useMessagingAuth();
1770
+ const effectiveApiKey = filestackApiKey ?? config.filestackApiKey;
1771
+ const uploader = useMemo(
1772
+ () => createFluidFileUploader(effectiveApiKey),
1773
+ [effectiveApiKey]
1774
+ );
1775
+ const effectiveWsUrl = websocketUrlOverride ?? websocketUrl;
1776
+ const effectiveToast = onToast ?? defaultToast;
1777
+ const searchUsers = useCallback(
1778
+ async (query) => {
1779
+ const result = await listConnectedRecipients(apiConfig, {
1780
+ filterrific: { search_query: query },
1781
+ per_page: 10,
1782
+ page: 1
1783
+ });
1784
+ const recipients = result?.[1]?.items ?? [];
1785
+ return recipients.map((user) => {
1786
+ const hasName = [user.first_name, user.last_name].filter(Boolean).length > 0;
1787
+ const name = hasName ? [user.first_name, user.last_name].filter(Boolean).join(" ") : `User ${user.id}`;
1788
+ return {
1789
+ id: String(user.id),
1790
+ label: name,
1791
+ imageType: "user",
1792
+ userData: {
1793
+ first_name: user.first_name,
1794
+ last_name: user.last_name,
1795
+ image_url: user.avatar_url,
1796
+ phone: user.phone || void 0,
1797
+ email: user.email || void 0
1798
+ },
1799
+ conversationName: name
1800
+ };
1801
+ });
1802
+ },
1803
+ [apiConfig]
1804
+ );
1805
+ const searchChannels = useCallback(
1806
+ async (query) => {
1807
+ const channels = await searchConversations(apiConfig, {
1808
+ filterrific: { search_query: query }
1809
+ }) ?? [];
1810
+ return channels.map((channel) => {
1811
+ const { text: nameWithoutEmoji } = extractEmoji(channel.name);
1812
+ return {
1813
+ id: `channel-${channel.id}`,
1814
+ label: formatMessageChannelName(nameWithoutEmoji),
1815
+ imageType: "channel",
1816
+ userData: {
1817
+ first_name: channel.name,
1818
+ last_name: null,
1819
+ image_url: channel.avatar_url
1820
+ },
1821
+ conversationName: channel.name
1822
+ };
1823
+ });
1824
+ },
1825
+ [apiConfig]
1826
+ );
1827
+ if (messagingAuth.isLoading) {
1828
+ return /* @__PURE__ */ jsx(
1829
+ "div",
1830
+ {
1831
+ ...divProps,
1832
+ className: `flex h-full items-center justify-center ${divProps.className ?? ""}`,
1833
+ children: /* @__PURE__ */ jsx("div", { className: "text-muted-foreground", children: "Loading messaging..." })
1834
+ }
1835
+ );
1836
+ }
1837
+ if (!messagingAuth.recipientId) {
1838
+ return /* @__PURE__ */ jsx(
1839
+ "div",
1840
+ {
1841
+ ...divProps,
1842
+ className: `flex h-full items-center justify-center ${divProps.className ?? ""}`,
1843
+ children: /* @__PURE__ */ jsxs("div", { className: "max-w-sm rounded-lg border border-dashed border-border p-8 text-center", children: [
1844
+ /* @__PURE__ */ jsx("h2", { className: "text-xl font-semibold text-foreground", children: "Messaging" }),
1845
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-muted-foreground", children: "Messaging is not available for your account" })
1846
+ ] })
1847
+ }
1848
+ );
1849
+ }
1850
+ return /* @__PURE__ */ jsx("div", { ...divProps, className: `h-full ${divProps.className ?? ""}`, children: /* @__PURE__ */ jsx(
1851
+ MessagingApp,
1852
+ {
1853
+ config: apiConfig,
1854
+ auth: messagingAuth,
1855
+ websocketUrl: effectiveWsUrl,
1856
+ token,
1857
+ renderImage,
1858
+ showAdminFeatures: false,
1859
+ onToast: effectiveToast,
1860
+ messagesViewProps: {
1861
+ uploader,
1862
+ saveDrafts: true,
1863
+ onToast: effectiveToast
1864
+ },
1865
+ newMessageViewProps: {
1866
+ searchUsers,
1867
+ searchChannels
1868
+ }
1869
+ }
1870
+ ) });
1871
+ }
1872
+ var messagingScreenPropertySchema = {
1873
+ widgetType: "MessagingScreen",
1874
+ displayName: "Messaging Screen",
1875
+ tabsConfig: [{ id: "styling", label: "Styling" }],
1876
+ fields: []
1877
+ };
1878
+
1879
+ 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 };
1880
+ //# sourceMappingURL=chunk-R4SXB6EV.js.map
1881
+ //# sourceMappingURL=chunk-R4SXB6EV.js.map