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