@fluid-app/rep-sdk 0.1.9 → 0.1.11

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 (85) hide show
  1. package/dist/ContactsScreen-CB6l0Lf1.mjs +24 -0
  2. package/dist/ContactsScreen-CB6l0Lf1.mjs.map +1 -0
  3. package/dist/ContactsScreen-UfrdOORn.cjs +41 -0
  4. package/dist/ContactsScreen-UfrdOORn.cjs.map +1 -0
  5. package/dist/CoreScreenPlaceholder-D93ZYKt2.mjs +32 -0
  6. package/dist/CoreScreenPlaceholder-D93ZYKt2.mjs.map +1 -0
  7. package/dist/CoreScreenPlaceholder-DBZqxDsK.cjs +38 -0
  8. package/dist/CoreScreenPlaceholder-DBZqxDsK.cjs.map +1 -0
  9. package/dist/CustomersScreen-BEar6Leg.mjs +24 -0
  10. package/dist/CustomersScreen-BEar6Leg.mjs.map +1 -0
  11. package/dist/CustomersScreen-DXXPpWZW.cjs +41 -0
  12. package/dist/CustomersScreen-DXXPpWZW.cjs.map +1 -0
  13. package/dist/MessagingScreen-CsDvKkLC.cjs +1458 -0
  14. package/dist/MessagingScreen-CsDvKkLC.cjs.map +1 -0
  15. package/dist/MessagingScreen-xO9YudMx.mjs +1285 -0
  16. package/dist/MessagingScreen-xO9YudMx.mjs.map +1 -0
  17. package/dist/OrdersScreen-DB1v051q.mjs +24 -0
  18. package/dist/OrdersScreen-DB1v051q.mjs.map +1 -0
  19. package/dist/OrdersScreen-fcxcnpNU.cjs +41 -0
  20. package/dist/OrdersScreen-fcxcnpNU.cjs.map +1 -0
  21. package/dist/ProductsScreen-BaEng3LB.cjs +41 -0
  22. package/dist/ProductsScreen-BaEng3LB.cjs.map +1 -0
  23. package/dist/ProductsScreen-nVDsY6kf.mjs +24 -0
  24. package/dist/ProductsScreen-nVDsY6kf.mjs.map +1 -0
  25. package/dist/chunk-D1SwGrFN.mjs +27 -0
  26. package/dist/index.cjs +3397 -2850
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1026 -955
  29. package/dist/index.d.cts.map +1 -0
  30. package/dist/index.d.mts +2207 -0
  31. package/dist/index.d.mts.map +1 -0
  32. package/dist/index.mjs +2921 -0
  33. package/dist/index.mjs.map +1 -0
  34. package/package.json +8 -8
  35. package/dist/ContactsScreen-7RGAMMGN.cjs +0 -18
  36. package/dist/ContactsScreen-7RGAMMGN.cjs.map +0 -1
  37. package/dist/ContactsScreen-XKZE5HTP.js +0 -5
  38. package/dist/ContactsScreen-XKZE5HTP.js.map +0 -1
  39. package/dist/CustomersScreen-BBQ3YHI4.js +0 -5
  40. package/dist/CustomersScreen-BBQ3YHI4.js.map +0 -1
  41. package/dist/CustomersScreen-EMGCQ2PV.cjs +0 -18
  42. package/dist/CustomersScreen-EMGCQ2PV.cjs.map +0 -1
  43. package/dist/MessagingScreen-I3GVOGKY.js +0 -4
  44. package/dist/MessagingScreen-I3GVOGKY.js.map +0 -1
  45. package/dist/MessagingScreen-ZRD4WEOE.cjs +0 -17
  46. package/dist/MessagingScreen-ZRD4WEOE.cjs.map +0 -1
  47. package/dist/OrdersScreen-ANDGND6F.js +0 -5
  48. package/dist/OrdersScreen-ANDGND6F.js.map +0 -1
  49. package/dist/OrdersScreen-NNE6OSRS.cjs +0 -18
  50. package/dist/OrdersScreen-NNE6OSRS.cjs.map +0 -1
  51. package/dist/ProductsScreen-5PMFLPWS.js +0 -5
  52. package/dist/ProductsScreen-5PMFLPWS.js.map +0 -1
  53. package/dist/ProductsScreen-ALQYD7ID.cjs +0 -18
  54. package/dist/ProductsScreen-ALQYD7ID.cjs.map +0 -1
  55. package/dist/chunk-2RIDFKS3.cjs +0 -19
  56. package/dist/chunk-2RIDFKS3.cjs.map +0 -1
  57. package/dist/chunk-424PT5DM.js +0 -21
  58. package/dist/chunk-424PT5DM.js.map +0 -1
  59. package/dist/chunk-4LTH3NNT.js +0 -16
  60. package/dist/chunk-4LTH3NNT.js.map +0 -1
  61. package/dist/chunk-4PHR2M6A.js +0 -14
  62. package/dist/chunk-4PHR2M6A.js.map +0 -1
  63. package/dist/chunk-EKMZ4NIA.cjs +0 -19
  64. package/dist/chunk-EKMZ4NIA.cjs.map +0 -1
  65. package/dist/chunk-HDQ2JUQT.cjs +0 -24
  66. package/dist/chunk-HDQ2JUQT.cjs.map +0 -1
  67. package/dist/chunk-HFPPHLOO.cjs +0 -19
  68. package/dist/chunk-HFPPHLOO.cjs.map +0 -1
  69. package/dist/chunk-HMOWQQDX.cjs +0 -19
  70. package/dist/chunk-HMOWQQDX.cjs.map +0 -1
  71. package/dist/chunk-JXEED3FK.js +0 -16
  72. package/dist/chunk-JXEED3FK.js.map +0 -1
  73. package/dist/chunk-LU42Y4H3.cjs +0 -1597
  74. package/dist/chunk-LU42Y4H3.cjs.map +0 -1
  75. package/dist/chunk-NGOEPTWZ.js +0 -16
  76. package/dist/chunk-NGOEPTWZ.js.map +0 -1
  77. package/dist/chunk-NNZKBXNB.cjs +0 -16
  78. package/dist/chunk-NNZKBXNB.cjs.map +0 -1
  79. package/dist/chunk-SYZUEL6B.js +0 -1538
  80. package/dist/chunk-SYZUEL6B.js.map +0 -1
  81. package/dist/chunk-TB6OK3WH.js +0 -16
  82. package/dist/chunk-TB6OK3WH.js.map +0 -1
  83. package/dist/index.d.ts +0 -2138
  84. package/dist/index.js +0 -2536
  85. package/dist/index.js.map +0 -1
@@ -1,1538 +0,0 @@
1
- import { __export, __reExport } from './chunk-424PT5DM.js';
2
- import { createContext, useRef, useReducer, useEffect, useCallback, useMemo, useContext, useState } from 'react';
3
- import { MessagingApp } from '@fluid-app/messaging-ui/app';
4
- import { extractEmoji, formatMessageChannelName } from '@fluid-app/messaging-ui';
5
- import { listConnectedRecipients, searchConversations } from '@fluid-app/messaging-api-client';
6
- import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
7
- import { clearTokens, createDefaultAuthRedirect, isDevBypassActive, validateToken, storeToken, createDevUser, extractTokenFromUrl, AUTH_REDIRECT_TOKEN_KEY, cleanTokenFromUrl, getStoredToken, verifyToken, isTokenExpired, resolveAuthFailureHandler } from '@fluid-app/auth';
8
- export { DEFAULT_AUTH_URL, createDefaultAuthRedirect } from '@fluid-app/auth';
9
- import { jsx, jsxs } from 'react/jsx-runtime';
10
- import * as theme_star from '@fluid-app/rep-core/theme';
11
- import { getActiveThemeId, transformThemes } from '@fluid-app/rep-core/theme';
12
- export { buildThemeDefinition, getActiveThemeId, transformThemes } from '@fluid-app/rep-core/theme';
13
- import { DataSourceRegistryProvider } from '@fluid-app/rep-core/data-sources/registry-context';
14
- import { RegistryProvider } from '@fluid-app/rep-widgets/contexts';
15
- import { createWidgetRegistry } from '@fluid-app/rep-core/widget-utils';
16
- 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';
17
- import { getFileTypeFromMimetype } from '@fluid-app/messaging-core';
18
-
19
- var FluidAuthContext = createContext(null);
20
- function authReducer(state, action) {
21
- switch (action.type) {
22
- case "SET_AUTH":
23
- return {
24
- isLoading: false,
25
- token: action.token,
26
- user: action.user,
27
- error: action.error
28
- };
29
- case "CLEAR_AUTH":
30
- return { ...state, token: null, user: null, error: null };
31
- case "DONE_LOADING":
32
- return { ...state, isLoading: false };
33
- }
34
- }
35
- var initialAuthState = {
36
- isLoading: true,
37
- token: null,
38
- user: null,
39
- error: null
40
- };
41
- function FluidAuthProvider({
42
- children,
43
- config
44
- }) {
45
- const configRef = useRef(config);
46
- configRef.current = config;
47
- const [state, dispatch] = useReducer(authReducer, initialAuthState);
48
- const { isLoading, token, user, error } = state;
49
- useEffect(() => {
50
- const initializeAuth = async () => {
51
- const handleAuthFailure = () => {
52
- const current = configRef.current;
53
- const handler = resolveAuthFailureHandler(
54
- current?.onAuthFailure,
55
- current?.authUrl
56
- );
57
- handler();
58
- };
59
- try {
60
- if (isDevBypassActive(config?.devBypass)) {
61
- const envToken = import.meta.env.VITE_DEV_TOKEN;
62
- if (envToken) {
63
- const validation = validateToken(envToken, config?.gracePeriodMs);
64
- if (validation.isValid && validation.payload) {
65
- storeToken(envToken, config);
66
- dispatch({
67
- type: "SET_AUTH",
68
- token: envToken,
69
- user: validation.payload,
70
- error: null
71
- });
72
- return;
73
- }
74
- console.warn(
75
- "[FluidAuth] VITE_DEV_TOKEN is invalid or expired, falling back to mock user"
76
- );
77
- }
78
- console.warn(
79
- "[FluidAuth] Dev bypass active - using mock user. API calls will fail without a real token."
80
- );
81
- const devUser = createDevUser();
82
- dispatch({
83
- type: "SET_AUTH",
84
- token: null,
85
- user: devUser,
86
- error: null
87
- });
88
- return;
89
- }
90
- const tokenKey = config?.tokenKey ?? "fluidUserToken";
91
- let candidateToken = extractTokenFromUrl(tokenKey);
92
- if (!candidateToken && tokenKey !== AUTH_REDIRECT_TOKEN_KEY) {
93
- candidateToken = extractTokenFromUrl(AUTH_REDIRECT_TOKEN_KEY);
94
- }
95
- cleanTokenFromUrl(tokenKey);
96
- cleanTokenFromUrl(AUTH_REDIRECT_TOKEN_KEY);
97
- if (!candidateToken) {
98
- candidateToken = getStoredToken(config);
99
- }
100
- if (candidateToken) {
101
- let payload = null;
102
- if (config?.jwksUrl) {
103
- payload = await verifyToken(candidateToken, config.jwksUrl);
104
- if (!payload) {
105
- clearTokens(config);
106
- dispatch({
107
- type: "SET_AUTH",
108
- token: null,
109
- user: null,
110
- error: new Error("JWT signature verification failed")
111
- });
112
- handleAuthFailure();
113
- return;
114
- }
115
- if (isTokenExpired(candidateToken, config?.gracePeriodMs)) {
116
- clearTokens(config);
117
- dispatch({
118
- type: "SET_AUTH",
119
- token: null,
120
- user: null,
121
- error: new Error("Token has expired")
122
- });
123
- handleAuthFailure();
124
- return;
125
- }
126
- } else {
127
- const validation = validateToken(
128
- candidateToken,
129
- config?.gracePeriodMs
130
- );
131
- if (validation.isValid && validation.payload) {
132
- payload = validation.payload;
133
- } else {
134
- clearTokens(config);
135
- dispatch({
136
- type: "SET_AUTH",
137
- token: null,
138
- user: null,
139
- error: new Error(validation.error ?? "Invalid token")
140
- });
141
- handleAuthFailure();
142
- return;
143
- }
144
- }
145
- storeToken(candidateToken, config);
146
- dispatch({
147
- type: "SET_AUTH",
148
- token: candidateToken,
149
- user: payload,
150
- error: null
151
- });
152
- } else {
153
- dispatch({
154
- type: "SET_AUTH",
155
- token: null,
156
- user: null,
157
- error: new Error("No authentication token found")
158
- });
159
- handleAuthFailure();
160
- }
161
- } catch (err) {
162
- const authError = err instanceof Error ? err : new Error("Authentication error");
163
- dispatch({
164
- type: "SET_AUTH",
165
- token: null,
166
- user: null,
167
- error: authError
168
- });
169
- handleAuthFailure();
170
- } finally {
171
- dispatch({ type: "DONE_LOADING" });
172
- }
173
- };
174
- void initializeAuth();
175
- }, []);
176
- const clearAuth = useCallback(() => {
177
- clearTokens(configRef.current);
178
- dispatch({ type: "CLEAR_AUTH" });
179
- }, []);
180
- const contextValue = useMemo(
181
- () => ({
182
- isAuthenticated: user !== null,
183
- isLoading,
184
- user,
185
- token,
186
- clearAuth,
187
- error
188
- }),
189
- [token, isLoading, user, clearAuth, error]
190
- );
191
- return /* @__PURE__ */ jsx(FluidAuthContext.Provider, { value: contextValue, children });
192
- }
193
- function useFluidAuthContext() {
194
- const context = useContext(FluidAuthContext);
195
- if (!context) {
196
- throw new Error(
197
- "useFluidAuthContext must be used within a FluidAuthProvider. Wrap your app with <FluidAuthProvider> to use authentication features."
198
- );
199
- }
200
- return context;
201
- }
202
- function useFluidAuthOptional() {
203
- return useContext(FluidAuthContext);
204
- }
205
-
206
- // ../../platform/api-client-core/src/fetch-client.ts
207
- var ApiError = class _ApiError extends Error {
208
- status;
209
- data;
210
- constructor(message, status, data) {
211
- super(message);
212
- this.name = "ApiError";
213
- this.status = status;
214
- this.data = data;
215
- if ("captureStackTrace" in Error) {
216
- Error.captureStackTrace(this, _ApiError);
217
- }
218
- }
219
- toJSON() {
220
- return {
221
- name: this.name,
222
- message: this.message,
223
- status: this.status,
224
- data: this.data
225
- };
226
- }
227
- };
228
- function createFetchClient(config) {
229
- const { baseUrl, getAuthToken, onAuthError, defaultHeaders = {} } = config;
230
- async function buildHeaders(customHeaders) {
231
- const headers = {
232
- Accept: "application/json",
233
- "Content-Type": "application/json",
234
- ...defaultHeaders,
235
- ...customHeaders
236
- };
237
- if (getAuthToken) {
238
- const token = await getAuthToken();
239
- if (token) {
240
- headers.Authorization = `Bearer ${token}`;
241
- }
242
- }
243
- return headers;
244
- }
245
- function joinUrl(endpoint) {
246
- return `${baseUrl}${endpoint}`;
247
- }
248
- function buildUrl(endpoint, params) {
249
- const fullUrl = joinUrl(endpoint);
250
- if (!params || Object.keys(params).length === 0) {
251
- return fullUrl;
252
- }
253
- const queryString = new URLSearchParams();
254
- Object.entries(params).forEach(([key, value]) => {
255
- if (value === void 0 || value === null) {
256
- return;
257
- }
258
- if (Array.isArray(value)) {
259
- value.forEach((item) => queryString.append(`${key}[]`, String(item)));
260
- } else if (typeof value === "object") {
261
- Object.entries(value).forEach(([subKey, subValue]) => {
262
- if (subValue === void 0 || subValue === null) {
263
- return;
264
- }
265
- if (Array.isArray(subValue)) {
266
- subValue.forEach(
267
- (item) => queryString.append(`${key}[${subKey}][]`, String(item))
268
- );
269
- } else {
270
- queryString.append(`${key}[${subKey}]`, String(subValue));
271
- }
272
- });
273
- } else {
274
- queryString.append(key, String(value));
275
- }
276
- });
277
- const qs = queryString.toString();
278
- return qs ? `${fullUrl}?${qs}` : fullUrl;
279
- }
280
- async function handleResponse(response, method, _url) {
281
- if (response.status === 401 && onAuthError) {
282
- onAuthError();
283
- }
284
- if (!response.ok) {
285
- try {
286
- const contentType2 = response.headers.get("content-type");
287
- if (contentType2?.includes("application/json")) {
288
- const data = await response.json();
289
- throw new ApiError(
290
- data.message || data.error_message || `${method} request failed`,
291
- response.status,
292
- data.errors || data
293
- );
294
- } else {
295
- throw new ApiError(
296
- `${method} request failed with status ${response.status}`,
297
- response.status,
298
- null
299
- );
300
- }
301
- } catch (error) {
302
- if (error instanceof ApiError) {
303
- throw error;
304
- }
305
- throw new ApiError(
306
- `${method} request failed with status ${response.status}`,
307
- response.status,
308
- null
309
- );
310
- }
311
- }
312
- if (response.status === 204 || response.headers.get("content-length") === "0") {
313
- return null;
314
- }
315
- const contentType = response.headers.get("content-type");
316
- if (contentType?.includes("application/json")) {
317
- try {
318
- const data = await response.json();
319
- return data;
320
- } catch {
321
- try {
322
- const text = await response.text();
323
- return text;
324
- } catch {
325
- return null;
326
- }
327
- }
328
- }
329
- return null;
330
- }
331
- async function request(endpoint, options = {}) {
332
- const {
333
- method = "GET",
334
- headers: customHeaders,
335
- params,
336
- body,
337
- signal
338
- } = options;
339
- const url = params ? buildUrl(endpoint, params) : joinUrl(endpoint);
340
- const headers = await buildHeaders(customHeaders);
341
- let response;
342
- try {
343
- const fetchOptions = { method, headers };
344
- const serializedBody = body && method !== "GET" ? JSON.stringify(body) : null;
345
- if (serializedBody) fetchOptions.body = serializedBody;
346
- if (signal) fetchOptions.signal = signal;
347
- response = await fetch(url, fetchOptions);
348
- } catch (networkError) {
349
- throw new ApiError(
350
- `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
351
- 0,
352
- null
353
- );
354
- }
355
- return handleResponse(response, method);
356
- }
357
- async function requestWithFormData(endpoint, formData, options = {}) {
358
- const { method = "POST", headers: customHeaders, signal } = options;
359
- const url = joinUrl(endpoint);
360
- const headers = await buildHeaders(customHeaders);
361
- delete headers["Content-Type"];
362
- let response;
363
- try {
364
- const fetchOptions = { method, headers, body: formData };
365
- if (signal) fetchOptions.signal = signal;
366
- response = await fetch(url, fetchOptions);
367
- } catch (networkError) {
368
- throw new ApiError(
369
- `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
370
- 0,
371
- null
372
- );
373
- }
374
- return handleResponse(response, method);
375
- }
376
- return {
377
- request,
378
- requestWithFormData,
379
- // Convenience methods for common HTTP verbs
380
- get: (endpoint, params, options) => request(endpoint, {
381
- ...options,
382
- method: "GET",
383
- ...params && { params }
384
- }),
385
- post: (endpoint, body, options) => request(endpoint, {
386
- ...options,
387
- method: "POST",
388
- body
389
- }),
390
- put: (endpoint, body, options) => request(endpoint, {
391
- ...options,
392
- method: "PUT",
393
- body
394
- }),
395
- patch: (endpoint, body, options) => request(endpoint, {
396
- ...options,
397
- method: "PATCH",
398
- body
399
- }),
400
- delete: (endpoint, options) => request(endpoint, {
401
- ...options,
402
- method: "DELETE"
403
- })
404
- };
405
- }
406
-
407
- // ../../fluidos/api-client/src/namespaces/fluid_os.ts
408
- var fluid_os_exports = {};
409
- __export(fluid_os_exports, {
410
- createFluidOSDefinition: () => createFluidOSDefinition,
411
- createFluidOSNavigation: () => createFluidOSNavigation,
412
- createFluidOSNavigationItem: () => createFluidOSNavigationItem,
413
- createFluidOSProfile: () => createFluidOSProfile,
414
- createFluidOSScreen: () => createFluidOSScreen,
415
- createFluidOSTheme: () => createFluidOSTheme,
416
- createFluidOSVersion: () => createFluidOSVersion,
417
- deleteFluidOSDefinition: () => deleteFluidOSDefinition,
418
- deleteFluidOSNavigation: () => deleteFluidOSNavigation,
419
- deleteFluidOSNavigationItem: () => deleteFluidOSNavigationItem,
420
- deleteFluidOSProfile: () => deleteFluidOSProfile,
421
- deleteFluidOSScreen: () => deleteFluidOSScreen,
422
- deleteFluidOSTheme: () => deleteFluidOSTheme,
423
- getDefaultFluidOSProfile: () => getDefaultFluidOSProfile,
424
- getFluidOSDefinition: () => getFluidOSDefinition,
425
- getFluidOSManifest: () => getFluidOSManifest,
426
- getFluidOSNavigation: () => getFluidOSNavigation,
427
- getFluidOSNavigationItem: () => getFluidOSNavigationItem,
428
- getFluidOSProfile: () => getFluidOSProfile,
429
- getFluidOSScreen: () => getFluidOSScreen,
430
- getFluidOSTheme: () => getFluidOSTheme,
431
- getFluidOSVersion: () => getFluidOSVersion,
432
- listFluidOSDefinitions: () => listFluidOSDefinitions,
433
- listFluidOSNavigationItems: () => listFluidOSNavigationItems,
434
- listFluidOSNavigations: () => listFluidOSNavigations,
435
- listFluidOSProfiles: () => listFluidOSProfiles,
436
- listFluidOSScreens: () => listFluidOSScreens,
437
- listFluidOSThemes: () => listFluidOSThemes,
438
- listFluidOSVersions: () => listFluidOSVersions,
439
- updateFluidOSDefinition: () => updateFluidOSDefinition,
440
- updateFluidOSNavigation: () => updateFluidOSNavigation,
441
- updateFluidOSNavigationItem: () => updateFluidOSNavigationItem,
442
- updateFluidOSProfile: () => updateFluidOSProfile,
443
- updateFluidOSScreen: () => updateFluidOSScreen,
444
- updateFluidOSTheme: () => updateFluidOSTheme,
445
- updateFluidOSVersion: () => updateFluidOSVersion
446
- });
447
- async function listFluidOSDefinitions(client, params) {
448
- return client.get(`/api/company/fluid_os/definitions`, params);
449
- }
450
- async function createFluidOSDefinition(client, body) {
451
- return client.post(`/api/company/fluid_os/definitions`, body);
452
- }
453
- async function getFluidOSDefinition(client, id) {
454
- return client.get(`/api/company/fluid_os/definitions/${id}`);
455
- }
456
- async function updateFluidOSDefinition(client, id, body) {
457
- return client.put(`/api/company/fluid_os/definitions/${id}`, body);
458
- }
459
- async function deleteFluidOSDefinition(client, id) {
460
- return client.delete(`/api/company/fluid_os/definitions/${id}`);
461
- }
462
- async function listFluidOSNavigationItems(client, definition_id, navigation_id) {
463
- return client.get(
464
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items`
465
- );
466
- }
467
- async function createFluidOSNavigationItem(client, definition_id, navigation_id, body) {
468
- return client.post(
469
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items`,
470
- body
471
- );
472
- }
473
- async function getFluidOSNavigationItem(client, definition_id, navigation_id, id) {
474
- return client.get(
475
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items/${id}`
476
- );
477
- }
478
- async function updateFluidOSNavigationItem(client, definition_id, navigation_id, id, body) {
479
- return client.put(
480
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items/${id}`,
481
- body
482
- );
483
- }
484
- async function deleteFluidOSNavigationItem(client, definition_id, navigation_id, id) {
485
- return client.delete(
486
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${navigation_id}/navigation_items/${id}`
487
- );
488
- }
489
- async function listFluidOSNavigations(client, definition_id, params) {
490
- return client.get(
491
- `/api/company/fluid_os/definitions/${definition_id}/navigations`,
492
- params
493
- );
494
- }
495
- async function createFluidOSNavigation(client, definition_id, body) {
496
- return client.post(
497
- `/api/company/fluid_os/definitions/${definition_id}/navigations`,
498
- body
499
- );
500
- }
501
- async function getFluidOSNavigation(client, definition_id, id) {
502
- return client.get(
503
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${id}`
504
- );
505
- }
506
- async function updateFluidOSNavigation(client, definition_id, id, body) {
507
- return client.put(
508
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${id}`,
509
- body
510
- );
511
- }
512
- async function deleteFluidOSNavigation(client, definition_id, id) {
513
- return client.delete(
514
- `/api/company/fluid_os/definitions/${definition_id}/navigations/${id}`
515
- );
516
- }
517
- async function listFluidOSProfiles(client, definition_id, params) {
518
- return client.get(
519
- `/api/company/fluid_os/definitions/${definition_id}/profiles`,
520
- params
521
- );
522
- }
523
- async function createFluidOSProfile(client, definition_id, body) {
524
- return client.post(
525
- `/api/company/fluid_os/definitions/${definition_id}/profiles`,
526
- body
527
- );
528
- }
529
- async function getDefaultFluidOSProfile(client, definition_id) {
530
- return client.get(
531
- `/api/company/fluid_os/definitions/${definition_id}/profiles/default`
532
- );
533
- }
534
- async function getFluidOSProfile(client, definition_id, id) {
535
- return client.get(
536
- `/api/company/fluid_os/definitions/${definition_id}/profiles/${id}`
537
- );
538
- }
539
- async function updateFluidOSProfile(client, definition_id, id, body) {
540
- return client.put(
541
- `/api/company/fluid_os/definitions/${definition_id}/profiles/${id}`,
542
- body
543
- );
544
- }
545
- async function deleteFluidOSProfile(client, definition_id, id) {
546
- return client.delete(
547
- `/api/company/fluid_os/definitions/${definition_id}/profiles/${id}`
548
- );
549
- }
550
- async function getFluidOSManifest(client, params) {
551
- return client.get(`/api/fluid_os/definitions/active`, params);
552
- }
553
- async function listFluidOSScreens(client, definition_id, params) {
554
- return client.get(
555
- `/api/company/fluid_os/definitions/${definition_id}/screens`,
556
- params
557
- );
558
- }
559
- async function createFluidOSScreen(client, definition_id, body) {
560
- return client.post(
561
- `/api/company/fluid_os/definitions/${definition_id}/screens`,
562
- body
563
- );
564
- }
565
- async function getFluidOSScreen(client, definition_id, id) {
566
- return client.get(
567
- `/api/company/fluid_os/definitions/${definition_id}/screens/${id}`
568
- );
569
- }
570
- async function updateFluidOSScreen(client, definition_id, id, body) {
571
- return client.put(
572
- `/api/company/fluid_os/definitions/${definition_id}/screens/${id}`,
573
- body
574
- );
575
- }
576
- async function deleteFluidOSScreen(client, definition_id, id) {
577
- return client.delete(
578
- `/api/company/fluid_os/definitions/${definition_id}/screens/${id}`
579
- );
580
- }
581
- async function listFluidOSThemes(client, definition_id, params) {
582
- return client.get(
583
- `/api/company/fluid_os/definitions/${definition_id}/themes`,
584
- params
585
- );
586
- }
587
- async function createFluidOSTheme(client, definition_id, body) {
588
- return client.post(
589
- `/api/company/fluid_os/definitions/${definition_id}/themes`,
590
- body
591
- );
592
- }
593
- async function getFluidOSTheme(client, definition_id, id) {
594
- return client.get(
595
- `/api/company/fluid_os/definitions/${definition_id}/themes/${id}`
596
- );
597
- }
598
- async function updateFluidOSTheme(client, definition_id, id, body) {
599
- return client.put(
600
- `/api/company/fluid_os/definitions/${definition_id}/themes/${id}`,
601
- body
602
- );
603
- }
604
- async function deleteFluidOSTheme(client, definition_id, id) {
605
- return client.delete(
606
- `/api/company/fluid_os/definitions/${definition_id}/themes/${id}`
607
- );
608
- }
609
- async function listFluidOSVersions(client, definition_id, params) {
610
- return client.get(
611
- `/api/company/fluid_os/definitions/${definition_id}/versions`,
612
- params
613
- );
614
- }
615
- async function createFluidOSVersion(client, definition_id) {
616
- return client.post(
617
- `/api/company/fluid_os/definitions/${definition_id}/versions`
618
- );
619
- }
620
- async function getFluidOSVersion(client, definition_id, id) {
621
- return client.get(
622
- `/api/company/fluid_os/definitions/${definition_id}/versions/${id}`
623
- );
624
- }
625
- async function updateFluidOSVersion(client, definition_id, id, body) {
626
- return client.put(
627
- `/api/company/fluid_os/definitions/${definition_id}/versions/${id}`,
628
- body
629
- );
630
- }
631
-
632
- // src/client/types.ts
633
- var HTTP_METHODS = {
634
- GET: "GET",
635
- POST: "POST",
636
- PUT: "PUT",
637
- PATCH: "PATCH",
638
- DELETE: "DELETE"
639
- };
640
-
641
- // src/transforms/screen-transforms.ts
642
- function normalizeComponentTree(componentTree) {
643
- if (!componentTree) return [];
644
- if (Array.isArray(componentTree)) return componentTree;
645
- if (typeof componentTree === "object") {
646
- return [componentTree];
647
- }
648
- return [];
649
- }
650
- function toScreenDefinition(screen) {
651
- return {
652
- id: Number(screen.id),
653
- slug: screen.slug ?? "",
654
- name: screen.name ?? "",
655
- component_tree: normalizeComponentTree(screen.component_tree)
656
- };
657
- }
658
-
659
- // src/transforms/navigation-transforms.ts
660
- function toNavigationItem(item) {
661
- const children = (item.children ?? []).map(toNavigationItem).sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
662
- return {
663
- id: Number(item.id),
664
- label: item.label ?? "Untitled",
665
- // Use conditional spread for optional properties (exactOptionalPropertyTypes)
666
- ...item.slug != null ? { slug: String(item.slug) } : {},
667
- ...item.icon != null ? { icon: String(item.icon) } : {},
668
- ...item.screen_id != null ? { screen_id: Number(item.screen_id) } : {},
669
- ...item.parent_id != null ? { parent_id: Number(item.parent_id) } : {},
670
- ...item.source != null ? { source: item.source } : {},
671
- position: item.position ?? 0,
672
- children
673
- };
674
- }
675
- function transformManifestToRepAppData(response) {
676
- const manifest = response.manifest;
677
- const rawProfile = manifest.profile;
678
- const rawThemes = Array.isArray(rawProfile?.themes) ? rawProfile.themes : [];
679
- const screens = (manifest.screens ?? []).map(
680
- (screen) => toScreenDefinition(screen)
681
- );
682
- const navigationItems = (rawProfile?.navigation?.navigation_items ?? []).map(
683
- toNavigationItem
684
- );
685
- const nav = rawProfile?.navigation;
686
- const mobileNav = rawProfile?.mobile_navigation;
687
- const mobileNavigationItems = (mobileNav?.navigation_items ?? []).map(
688
- toNavigationItem
689
- );
690
- const activeThemeId = getActiveThemeId(rawThemes);
691
- return {
692
- definition_id: manifest.definition_id,
693
- published_version: manifest.published_version ?? 0,
694
- screens,
695
- profile: {
696
- name: rawProfile?.name ?? "Default",
697
- definition_id: rawProfile?.definition_id ?? manifest.definition_id,
698
- themes: transformThemes(rawThemes),
699
- // Conditional spread for exactOptionalPropertyTypes compliance
700
- ...activeThemeId !== void 0 ? { activeThemeId } : {},
701
- navigation: {
702
- definition_id: nav?.definition_id ?? manifest.definition_id,
703
- id: nav?.id ?? 0,
704
- name: nav?.name ?? "Main Navigation",
705
- navigation_items: navigationItems,
706
- screens
707
- },
708
- ...mobileNav ? {
709
- mobile_navigation: {
710
- definition_id: mobileNav.definition_id ?? manifest.definition_id,
711
- id: mobileNav.id ?? 0,
712
- name: mobileNav.name ?? "Mobile Navigation",
713
- navigation_items: mobileNavigationItems,
714
- screens
715
- }
716
- } : {}
717
- }
718
- };
719
- }
720
-
721
- // src/client/fluid-client.ts
722
- var ApiError2 = class _ApiError extends Error {
723
- status;
724
- data;
725
- constructor(message, status, data) {
726
- super(message);
727
- this.name = "ApiError";
728
- this.status = status;
729
- this.data = data;
730
- const errorWithCapture = Error;
731
- if (errorWithCapture.captureStackTrace) {
732
- errorWithCapture.captureStackTrace(this, _ApiError);
733
- }
734
- }
735
- toJSON() {
736
- return {
737
- name: this.name,
738
- message: this.message,
739
- status: this.status,
740
- data: this.data
741
- };
742
- }
743
- };
744
- function isApiError2(error) {
745
- return error instanceof ApiError2;
746
- }
747
- function isString(value) {
748
- return typeof value === "string";
749
- }
750
- function extractErrorMessage(data, fallback) {
751
- if ("message" in data && isString(data.message)) {
752
- return data.message;
753
- }
754
- if ("error_message" in data && isString(data.error_message)) {
755
- return data.error_message;
756
- }
757
- if ("error" in data && isString(data.error)) {
758
- return data.error;
759
- }
760
- return fallback;
761
- }
762
- function createFluidClient(config) {
763
- const { baseUrl, getAuthToken, onAuthError, defaultHeaders = {} } = config;
764
- const effectiveOnAuthError = onAuthError ?? createDefaultAuthRedirect();
765
- const fetchClient = createFetchClient({
766
- baseUrl,
767
- ...getAuthToken ? { getAuthToken } : {},
768
- onAuthError: effectiveOnAuthError,
769
- defaultHeaders
770
- });
771
- async function buildHeaders(customHeaders) {
772
- const headers = {
773
- "Content-Type": "application/json",
774
- ...defaultHeaders,
775
- ...customHeaders
776
- };
777
- if (getAuthToken) {
778
- const token = await getAuthToken();
779
- if (token) {
780
- headers.Authorization = `Bearer ${token}`;
781
- }
782
- }
783
- return headers;
784
- }
785
- function buildUrl(endpoint, params) {
786
- const normalizedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
787
- const normalizedEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
788
- const url = new URL(normalizedBase + normalizedEndpoint);
789
- if (params) {
790
- for (const [key, value] of Object.entries(params)) {
791
- if (value === void 0 || value === null) {
792
- continue;
793
- }
794
- if (Array.isArray(value)) {
795
- for (const item of value) {
796
- url.searchParams.append(`${key}[]`, String(item));
797
- }
798
- } else if (typeof value === "object") {
799
- for (const [subKey, subValue] of Object.entries(
800
- value
801
- )) {
802
- if (subValue === void 0 || subValue === null) {
803
- continue;
804
- }
805
- if (Array.isArray(subValue)) {
806
- for (const item of subValue) {
807
- url.searchParams.append(`${key}[${subKey}][]`, String(item));
808
- }
809
- } else {
810
- url.searchParams.append(`${key}[${subKey}]`, String(subValue));
811
- }
812
- }
813
- } else {
814
- url.searchParams.append(key, String(value));
815
- }
816
- }
817
- }
818
- return url.toString();
819
- }
820
- const defaultRequestOptions = {
821
- method: HTTP_METHODS.GET
822
- };
823
- async function request(endpoint, options = {}) {
824
- const {
825
- method = defaultRequestOptions.method,
826
- headers: customHeaders,
827
- params,
828
- body,
829
- signal
830
- } = options;
831
- const url = buildUrl(
832
- endpoint,
833
- method === HTTP_METHODS.GET ? params : void 0
834
- );
835
- const headers = await buildHeaders(customHeaders);
836
- let response;
837
- try {
838
- const fetchOptions = {
839
- method,
840
- headers
841
- };
842
- if (signal !== void 0) {
843
- fetchOptions.signal = signal;
844
- }
845
- if (body && method !== HTTP_METHODS.GET) {
846
- fetchOptions.body = JSON.stringify(body);
847
- }
848
- response = await fetch(url, fetchOptions);
849
- } catch (networkError) {
850
- throw new ApiError2(
851
- `Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`,
852
- 0,
853
- null
854
- );
855
- }
856
- if (response.status === 401) {
857
- effectiveOnAuthError();
858
- throw new ApiError2("Authentication required", 401, null);
859
- }
860
- if (!response.ok) {
861
- try {
862
- const contentType = response.headers.get("content-type");
863
- if (contentType?.includes("application/json")) {
864
- const data = await response.json();
865
- const errorMessage = extractErrorMessage(
866
- data,
867
- `${method} request failed`
868
- );
869
- throw new ApiError2(
870
- errorMessage,
871
- response.status,
872
- "errors" in data ? data.errors : data
873
- );
874
- } else {
875
- throw new ApiError2(
876
- `${method} request failed with status ${response.status}`,
877
- response.status,
878
- null
879
- );
880
- }
881
- } catch (error) {
882
- if (isApiError2(error)) {
883
- throw error;
884
- }
885
- throw new ApiError2(
886
- `${method} request failed with status ${response.status}`,
887
- response.status,
888
- null
889
- );
890
- }
891
- }
892
- if (response.status === 204 || response.headers.get("content-length") === "0") {
893
- return null;
894
- }
895
- try {
896
- const data = await response.json();
897
- if (data === null || data === void 0) {
898
- throw new ApiError2(
899
- "Unexpected null/undefined in JSON response",
900
- response.status,
901
- null
902
- );
903
- }
904
- return data;
905
- } catch (parseError) {
906
- if (isApiError2(parseError)) {
907
- throw parseError;
908
- }
909
- throw new ApiError2(
910
- "Failed to parse response as JSON",
911
- response.status,
912
- null
913
- );
914
- }
915
- }
916
- async function requestNullable(endpoint, options = {}) {
917
- return request(endpoint, options);
918
- }
919
- async function safeRequest(endpoint, options = {}) {
920
- try {
921
- const data = await request(endpoint, options);
922
- return { success: true, data };
923
- } catch (error) {
924
- if (isApiError2(error)) {
925
- return { success: false, error };
926
- }
927
- return {
928
- success: false,
929
- error: new ApiError2(
930
- error instanceof Error ? error.message : "Unknown error",
931
- 0,
932
- null
933
- )
934
- };
935
- }
936
- }
937
- function toParams(params) {
938
- return params;
939
- }
940
- const get = (endpoint, params, options) => {
941
- const baseOptions = {
942
- ...options,
943
- method: HTTP_METHODS.GET
944
- };
945
- const convertedParams = toParams(params);
946
- const requestOptions = convertedParams !== void 0 ? { ...baseOptions, params: convertedParams } : baseOptions;
947
- return request(endpoint, requestOptions);
948
- };
949
- const post = (endpoint, body, options) => request(endpoint, {
950
- ...options,
951
- method: HTTP_METHODS.POST,
952
- body
953
- });
954
- const put = (endpoint, body, options) => request(endpoint, {
955
- ...options,
956
- method: HTTP_METHODS.PUT,
957
- body
958
- });
959
- const patch = (endpoint, body, options) => request(endpoint, {
960
- ...options,
961
- method: HTTP_METHODS.PATCH,
962
- body
963
- });
964
- const del = (endpoint, options) => request(endpoint, {
965
- ...options,
966
- method: HTTP_METHODS.DELETE
967
- });
968
- return {
969
- // Fluidos FetchClient for structured API calls
970
- fetchClient,
971
- // Low-level methods for custom endpoints
972
- request,
973
- requestNullable,
974
- safeRequest,
975
- get,
976
- post,
977
- put,
978
- patch,
979
- delete: del,
980
- // Products API - matches fluid-admin's /company/v1/products
981
- products: {
982
- list: (params) => get(
983
- "/company/v1/products",
984
- params
985
- ),
986
- get: (id) => get(`/company/v1/products/${id}`),
987
- search: (query, params) => get("/company/v1/products", {
988
- search_query: query,
989
- ...params
990
- })
991
- },
992
- // Orders API
993
- orders: {
994
- list: (params) => get("/orders", params),
995
- get: (id) => get(`/orders/${id}`),
996
- create: (data) => post("/orders", data)
997
- },
998
- // Users API
999
- users: {
1000
- me: () => get("/api/me")
1001
- },
1002
- // Reps API
1003
- reps: {
1004
- current: () => get("/reps/me"),
1005
- updateProfile: (data) => patch("/reps/me", data)
1006
- },
1007
- // Profile API (themes, navigation, screens) — legacy endpoint
1008
- profile: {
1009
- get: () => get("/rep_app/manifest")
1010
- },
1011
- // App API — fluidos endpoint (full manifest with transforms)
1012
- app: {
1013
- /** Fetch the raw manifest (plain JSON, no Color objects). Cache-safe. */
1014
- getRaw: async () => {
1015
- const raw = await fluid_os_exports.getFluidOSManifest(fetchClient, {
1016
- platform: "browser"
1017
- });
1018
- return raw;
1019
- },
1020
- /** Fetch the active app definition with full theme/screen/navigation transforms */
1021
- get: async () => {
1022
- const raw = await fluid_os_exports.getFluidOSManifest(fetchClient, {
1023
- platform: "browser"
1024
- });
1025
- return transformManifestToRepAppData(
1026
- raw
1027
- );
1028
- }
1029
- },
1030
- // Permissions API
1031
- permissions: {
1032
- get: () => get("/company/roles/my_permissions")
1033
- },
1034
- // Analytics API
1035
- analytics: {
1036
- dashboard: () => get("/analytics/dashboard"),
1037
- sales: (params) => get("/analytics/sales", params)
1038
- }
1039
- };
1040
- }
1041
-
1042
- // src/themes/index.ts
1043
- var themes_exports = {};
1044
- __reExport(themes_exports, theme_star);
1045
- var ThemeContext = createContext(null);
1046
- function applyThemeToDOM(theme, mode, container) {
1047
- const target = container ?? document.documentElement;
1048
- const resolved = (0, themes_exports.resolveTheme)(theme);
1049
- (0, themes_exports.applyTheme)(resolved);
1050
- target.dataset.theme = theme.id;
1051
- if (mode) {
1052
- target.dataset.themeMode = mode;
1053
- } else {
1054
- delete target.dataset.themeMode;
1055
- }
1056
- }
1057
- function FluidThemeProvider({
1058
- children,
1059
- initialTheme,
1060
- container
1061
- }) {
1062
- const [currentTheme, setCurrentTheme] = useState(
1063
- initialTheme ?? null
1064
- );
1065
- const [mode, setMode] = useState(void 0);
1066
- useEffect(() => {
1067
- if (currentTheme) {
1068
- applyThemeToDOM(currentTheme, mode, container ?? null);
1069
- }
1070
- return () => {
1071
- (0, themes_exports.removeAllThemes)();
1072
- };
1073
- }, [currentTheme, mode, container]);
1074
- const setTheme = useCallback((theme) => {
1075
- setCurrentTheme(theme);
1076
- }, []);
1077
- const setThemeMode = useCallback((newMode) => {
1078
- setMode(newMode);
1079
- }, []);
1080
- const value = useMemo(
1081
- () => ({
1082
- currentTheme,
1083
- setTheme,
1084
- setThemeMode,
1085
- mode
1086
- }),
1087
- [currentTheme, setTheme, setThemeMode, mode]
1088
- );
1089
- return /* @__PURE__ */ jsx(ThemeContext.Provider, { value, children });
1090
- }
1091
- function useThemeContext() {
1092
- const context = useContext(ThemeContext);
1093
- if (!context) {
1094
- throw new Error("useThemeContext must be used within a FluidThemeProvider");
1095
- }
1096
- return context;
1097
- }
1098
- var DEFAULT_SDK_WIDGET_REGISTRY = createWidgetRegistry({
1099
- AlertWidget,
1100
- CalendarWidget,
1101
- CarouselWidget,
1102
- CatchUpWidget,
1103
- ChartWidget,
1104
- ContainerWidget,
1105
- EmbedWidget,
1106
- ImageWidget,
1107
- LayoutWidget,
1108
- ListWidget,
1109
- MySiteWidget,
1110
- NestedWidget,
1111
- QuickShareWidget,
1112
- RecentActivityWidget,
1113
- SpacerWidget,
1114
- TableWidget,
1115
- TextWidget,
1116
- ToDoWidget,
1117
- VideoWidget
1118
- });
1119
- var FluidContext = createContext(null);
1120
- function FluidProvider({
1121
- config,
1122
- children,
1123
- queryClient,
1124
- initialTheme,
1125
- themeContainer,
1126
- widgetRegistry,
1127
- variables
1128
- }) {
1129
- const defaultQueryClient = useMemo(
1130
- () => new QueryClient({
1131
- defaultOptions: {
1132
- queries: {
1133
- staleTime: 1e3 * 60,
1134
- // 1 minute
1135
- retry: 1
1136
- }
1137
- }
1138
- }),
1139
- []
1140
- );
1141
- const configRef = useRef(config);
1142
- configRef.current = config;
1143
- const client = useMemo(
1144
- () => createFluidClient({
1145
- ...configRef.current,
1146
- getAuthToken: () => configRef.current.getAuthToken?.() ?? null,
1147
- onAuthError: () => configRef.current.onAuthError?.()
1148
- }),
1149
- // eslint-disable-next-line react-hooks/exhaustive-deps
1150
- [config.baseUrl]
1151
- );
1152
- const contextValue = useMemo(
1153
- () => ({ client, config: configRef.current }),
1154
- [client]
1155
- );
1156
- const getApiHeaders = useCallback(() => {
1157
- const headers = {
1158
- "Content-Type": "application/json"
1159
- };
1160
- const getAuthToken = configRef.current.getAuthToken;
1161
- if (typeof getAuthToken === "function") {
1162
- const tokenOrPromise = getAuthToken();
1163
- if (typeof tokenOrPromise === "string") {
1164
- headers.Authorization = `Bearer ${tokenOrPromise}`;
1165
- }
1166
- }
1167
- return headers;
1168
- }, []);
1169
- const dataSourceBaseUrl = useMemo(() => {
1170
- const base = config.baseUrl.replace(/\/+$/, "");
1171
- return base.endsWith("/api") ? base : `${base}/api`;
1172
- }, [config.baseUrl]);
1173
- const authContext = useFluidAuthOptional();
1174
- const autoVariables = useMemo(() => {
1175
- if (authContext?.user?.id != null) {
1176
- return { rep_id: String(authContext.user.id) };
1177
- }
1178
- return void 0;
1179
- }, [authContext?.user?.id]);
1180
- const effectiveVariables = variables ?? autoVariables;
1181
- const themeProviderProps = {
1182
- ...initialTheme !== void 0 && { initialTheme },
1183
- ...themeContainer !== void 0 && { container: themeContainer }
1184
- };
1185
- const registry = widgetRegistry ?? DEFAULT_SDK_WIDGET_REGISTRY;
1186
- return /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient ?? defaultQueryClient, children: /* @__PURE__ */ jsx(FluidContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(
1187
- DataSourceRegistryProvider,
1188
- {
1189
- baseUrl: dataSourceBaseUrl,
1190
- getApiHeaders,
1191
- variables: effectiveVariables,
1192
- children: /* @__PURE__ */ jsx(RegistryProvider, { registry, children: /* @__PURE__ */ jsx(FluidThemeProvider, { ...themeProviderProps, children }) })
1193
- }
1194
- ) }) });
1195
- }
1196
- function useFluidContext() {
1197
- const context = useContext(FluidContext);
1198
- if (!context) {
1199
- throw new Error("useFluidContext must be used within a FluidProvider");
1200
- }
1201
- return context;
1202
- }
1203
-
1204
- // src/hooks/use-fluid-api.ts
1205
- function useFluidApi() {
1206
- const { client } = useFluidContext();
1207
- return client;
1208
- }
1209
-
1210
- // src/messaging/use-messaging-auth.ts
1211
- var USERS_ME_QUERY_KEY = ["fluid", "users", "me"];
1212
- function useMessagingAuth() {
1213
- const auth = useFluidAuthContext();
1214
- const api = useFluidApi();
1215
- const {
1216
- data: userMe,
1217
- isLoading: isUserMeLoading,
1218
- isError
1219
- } = useQuery({
1220
- queryKey: USERS_ME_QUERY_KEY,
1221
- queryFn: () => api.users.me(),
1222
- enabled: auth.isAuthenticated,
1223
- staleTime: Infinity,
1224
- retry: 1
1225
- });
1226
- if (auth.isLoading || auth.isAuthenticated && isUserMeLoading) {
1227
- return {
1228
- recipientId: null,
1229
- companyId: null,
1230
- currentUser: null,
1231
- isLoading: true
1232
- };
1233
- }
1234
- if (!auth.isAuthenticated || isError || !userMe) {
1235
- return {
1236
- recipientId: null,
1237
- companyId: null,
1238
- currentUser: null,
1239
- isLoading: false
1240
- };
1241
- }
1242
- const currentUser = userMe.recipient_id ? {
1243
- id: userMe.id,
1244
- recipientId: userMe.recipient_id,
1245
- firstName: userMe.first_name ?? "",
1246
- lastName: userMe.last_name ?? "",
1247
- email: userMe.email,
1248
- ...userMe.image_url != null && { imageUrl: userMe.image_url },
1249
- ...userMe.affiliate_id != null && {
1250
- affiliateId: userMe.affiliate_id
1251
- }
1252
- } : null;
1253
- return {
1254
- recipientId: userMe.recipient_id,
1255
- companyId: userMe.company_id ?? null,
1256
- currentUser,
1257
- isLoading: false
1258
- };
1259
- }
1260
- function deriveWebsocketUrl(baseUrl) {
1261
- const base = baseUrl.replace(/\/+$/, "").replace(/\/api$/, "");
1262
- return `${base}/cable`;
1263
- }
1264
- function useMessagingConfig() {
1265
- const { config } = useFluidContext();
1266
- const auth = useFluidAuthContext();
1267
- const getHeaders = useCallback(async () => {
1268
- const headers = {
1269
- "Content-Type": "application/json",
1270
- ...config.defaultHeaders
1271
- };
1272
- if (config.getAuthToken) {
1273
- const token = await config.getAuthToken();
1274
- if (token) {
1275
- headers.Authorization = `Bearer ${token}`;
1276
- }
1277
- }
1278
- return headers;
1279
- }, [config]);
1280
- const apiBaseUrl = useMemo(() => {
1281
- const base = config.baseUrl.replace(/\/+$/, "");
1282
- return base.endsWith("/api") ? base : `${base}/api`;
1283
- }, [config.baseUrl]);
1284
- const apiConfig = useMemo(
1285
- () => ({
1286
- baseUrl: apiBaseUrl,
1287
- getHeaders,
1288
- ...config.onAuthError != null && { onAuthError: config.onAuthError }
1289
- }),
1290
- [apiBaseUrl, config.onAuthError, getHeaders]
1291
- );
1292
- const websocketUrl = useMemo(
1293
- () => config.websocketUrl ?? deriveWebsocketUrl(config.baseUrl),
1294
- [config.websocketUrl, config.baseUrl]
1295
- );
1296
- return {
1297
- apiConfig,
1298
- websocketUrl,
1299
- token: auth.token
1300
- };
1301
- }
1302
- var FILESTACK_UPLOAD_URL = "https://www.filestackapi.com/api/store/S3";
1303
- function getImageDimensions(file) {
1304
- if (!file.type.startsWith("image/")) return Promise.resolve(null);
1305
- return new Promise((resolve) => {
1306
- const img = new Image();
1307
- const url = URL.createObjectURL(file);
1308
- img.onload = () => {
1309
- URL.revokeObjectURL(url);
1310
- resolve({ width: img.naturalWidth, height: img.naturalHeight });
1311
- };
1312
- img.onerror = () => {
1313
- URL.revokeObjectURL(url);
1314
- resolve(null);
1315
- };
1316
- img.src = url;
1317
- });
1318
- }
1319
- function uploadToFilestack(file, apiKey, callbacks) {
1320
- const xhr = new XMLHttpRequest();
1321
- let aborted = false;
1322
- getImageDimensions(file).then((metadata) => {
1323
- if (aborted) return;
1324
- const url = `${FILESTACK_UPLOAD_URL}?key=${encodeURIComponent(apiKey)}`;
1325
- xhr.open("POST", url);
1326
- xhr.setRequestHeader("Content-Type", file.type);
1327
- xhr.upload.onprogress = (event) => {
1328
- if (event.lengthComputable) {
1329
- const progress = Math.round(event.loaded / event.total * 100);
1330
- callbacks.onProgress(progress);
1331
- }
1332
- };
1333
- xhr.onload = () => {
1334
- if (xhr.status >= 200 && xhr.status < 300) {
1335
- try {
1336
- const response = JSON.parse(xhr.responseText);
1337
- const result = {
1338
- url: response.url,
1339
- size: file.size,
1340
- mimetype: file.type,
1341
- kind: getFileTypeFromMimetype(file.type),
1342
- metadata
1343
- };
1344
- callbacks.onSuccess(result);
1345
- } catch {
1346
- callbacks.onError(new Error("Failed to parse upload response"));
1347
- }
1348
- } else {
1349
- callbacks.onError(
1350
- new Error(`Upload failed with status ${xhr.status}`)
1351
- );
1352
- }
1353
- };
1354
- xhr.onerror = () => {
1355
- if (!aborted) {
1356
- callbacks.onError(new Error("Upload failed due to a network error"));
1357
- }
1358
- };
1359
- xhr.onabort = () => {
1360
- };
1361
- xhr.send(file);
1362
- }).catch((error) => {
1363
- if (!aborted) {
1364
- callbacks.onError(
1365
- error instanceof Error ? error : new Error("Upload preparation failed")
1366
- );
1367
- }
1368
- });
1369
- return {
1370
- abort: () => {
1371
- aborted = true;
1372
- xhr.abort();
1373
- }
1374
- };
1375
- }
1376
- function createFluidFileUploader(apiKey) {
1377
- if (!apiKey) {
1378
- return {
1379
- uploadFile: (_file, callbacks) => {
1380
- callbacks.onError(
1381
- new Error(
1382
- "File uploads are not configured. Set filestackApiKey in your SDK config to enable attachments."
1383
- )
1384
- );
1385
- return { abort: () => {
1386
- } };
1387
- }
1388
- };
1389
- }
1390
- return {
1391
- uploadFile: (file, callbacks) => uploadToFilestack(file, apiKey, callbacks)
1392
- };
1393
- }
1394
- function renderImage(props) {
1395
- return /* @__PURE__ */ jsx(
1396
- "img",
1397
- {
1398
- src: props.src,
1399
- alt: props.alt,
1400
- width: props.width,
1401
- height: props.height,
1402
- className: props.className
1403
- }
1404
- );
1405
- }
1406
- function defaultToast(message, type) {
1407
- if (type === "error") {
1408
- console.warn("[Messaging]", message);
1409
- }
1410
- }
1411
- function MessagingScreen({
1412
- onToast,
1413
- filestackApiKey,
1414
- websocketUrl: websocketUrlOverride,
1415
- /* eslint-disable @typescript-eslint/no-unused-vars -- destructured to exclude from divProps spread */
1416
- background,
1417
- textColor,
1418
- accentColor,
1419
- padding,
1420
- borderRadius,
1421
- /* eslint-enable @typescript-eslint/no-unused-vars */
1422
- ...divProps
1423
- }) {
1424
- const { config } = useFluidContext();
1425
- const { apiConfig, websocketUrl, token } = useMessagingConfig();
1426
- const messagingAuth = useMessagingAuth();
1427
- const effectiveApiKey = filestackApiKey ?? config.filestackApiKey;
1428
- const uploader = useMemo(
1429
- () => createFluidFileUploader(effectiveApiKey),
1430
- [effectiveApiKey]
1431
- );
1432
- const effectiveWsUrl = websocketUrlOverride ?? websocketUrl;
1433
- const effectiveToast = onToast ?? defaultToast;
1434
- const searchUsers = useCallback(
1435
- async (query) => {
1436
- const result = await listConnectedRecipients(apiConfig, {
1437
- filterrific: { search_query: query },
1438
- per_page: 10,
1439
- page: 1
1440
- });
1441
- const recipients = result?.[1]?.items ?? [];
1442
- return recipients.map((user) => {
1443
- const hasName = [user.first_name, user.last_name].filter(Boolean).length > 0;
1444
- const name = hasName ? [user.first_name, user.last_name].filter(Boolean).join(" ") : `User ${user.id}`;
1445
- return {
1446
- id: String(user.id),
1447
- label: name,
1448
- imageType: "user",
1449
- userData: {
1450
- first_name: user.first_name,
1451
- last_name: user.last_name,
1452
- image_url: user.avatar_url,
1453
- phone: user.phone || void 0,
1454
- email: user.email || void 0
1455
- },
1456
- conversationName: name
1457
- };
1458
- });
1459
- },
1460
- [apiConfig]
1461
- );
1462
- const searchChannels = useCallback(
1463
- async (query) => {
1464
- const channels = await searchConversations(apiConfig, {
1465
- filterrific: { search_query: query }
1466
- }) ?? [];
1467
- return channels.map((channel) => {
1468
- const { text: nameWithoutEmoji } = extractEmoji(channel.name);
1469
- return {
1470
- id: `channel-${channel.id}`,
1471
- label: formatMessageChannelName(nameWithoutEmoji),
1472
- imageType: "channel",
1473
- userData: {
1474
- first_name: channel.name,
1475
- last_name: null,
1476
- image_url: channel.avatar_url
1477
- },
1478
- conversationName: channel.name
1479
- };
1480
- });
1481
- },
1482
- [apiConfig]
1483
- );
1484
- if (messagingAuth.isLoading) {
1485
- return /* @__PURE__ */ jsx(
1486
- "div",
1487
- {
1488
- ...divProps,
1489
- className: `flex h-full items-center justify-center ${divProps.className ?? ""}`,
1490
- children: /* @__PURE__ */ jsx("div", { className: "text-muted-foreground", children: "Loading messaging..." })
1491
- }
1492
- );
1493
- }
1494
- if (!messagingAuth.recipientId) {
1495
- return /* @__PURE__ */ jsx(
1496
- "div",
1497
- {
1498
- ...divProps,
1499
- className: `flex h-full items-center justify-center ${divProps.className ?? ""}`,
1500
- children: /* @__PURE__ */ jsxs("div", { className: "border-border max-w-sm rounded-lg border border-dashed p-8 text-center", children: [
1501
- /* @__PURE__ */ jsx("h2", { className: "text-foreground text-xl font-semibold", children: "Messaging" }),
1502
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground mt-2", children: "Messaging is not available for your account" })
1503
- ] })
1504
- }
1505
- );
1506
- }
1507
- return /* @__PURE__ */ jsx("div", { ...divProps, className: `h-full ${divProps.className ?? ""}`, children: /* @__PURE__ */ jsx(
1508
- MessagingApp,
1509
- {
1510
- config: apiConfig,
1511
- auth: messagingAuth,
1512
- websocketUrl: effectiveWsUrl,
1513
- token,
1514
- renderImage,
1515
- showAdminFeatures: false,
1516
- onToast: effectiveToast,
1517
- messagesViewProps: {
1518
- uploader,
1519
- saveDrafts: true,
1520
- onToast: effectiveToast
1521
- },
1522
- newMessageViewProps: {
1523
- searchUsers,
1524
- searchChannels
1525
- }
1526
- }
1527
- ) });
1528
- }
1529
- var messagingScreenPropertySchema = {
1530
- widgetType: "MessagingScreen",
1531
- displayName: "Messaging Screen",
1532
- tabsConfig: [{ id: "styling", label: "Styling" }],
1533
- fields: []
1534
- };
1535
-
1536
- export { ApiError2 as ApiError, DEFAULT_SDK_WIDGET_REGISTRY, FluidAuthProvider, FluidProvider, FluidThemeProvider, MessagingScreen, createFluidClient, createFluidFileUploader, isApiError2 as isApiError, messagingScreenPropertySchema, normalizeComponentTree, themes_exports, toNavigationItem, toScreenDefinition, transformManifestToRepAppData, useFluidApi, useFluidAuthContext, useFluidContext, useMessagingAuth, useMessagingConfig, useThemeContext };
1537
- //# sourceMappingURL=chunk-SYZUEL6B.js.map
1538
- //# sourceMappingURL=chunk-SYZUEL6B.js.map