@1interface/shared-core 0.1.0

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.
@@ -0,0 +1,874 @@
1
+ import { ActionCreatorWithNonInferrablePayload } from '@reduxjs/toolkit';
2
+ import { ActionCreatorWithOptionalPayload } from '@reduxjs/toolkit';
3
+ import { ActionCreatorWithoutPayload } from '@reduxjs/toolkit';
4
+ import { Context } from 'react';
5
+ import { Dispatch } from '@reduxjs/toolkit';
6
+ import { ListenerMiddlewareInstance } from '@reduxjs/toolkit';
7
+ import { Reducer } from '@reduxjs/toolkit';
8
+ import { ThunkAction } from '@reduxjs/toolkit';
9
+ import { ThunkDispatch } from '@reduxjs/toolkit';
10
+ import { UnknownAction } from '@reduxjs/toolkit';
11
+
12
+ export declare const API_ENDPOINTS: {
13
+ CONVERSATIONS: () => string;
14
+ CONVERSATION_STREAM: (conversationId: string) => string;
15
+ CONVERSATION_START: (conversationId: string) => string;
16
+ readonly TRANSCRIBE: string;
17
+ readonly BRANDING: string;
18
+ readonly CONFIG: string;
19
+ readonly PROFILE: string;
20
+ readonly AUTH_ME: string;
21
+ readonly ORGANIZATIONS_EXISTS: string;
22
+ readonly DEBUG: string;
23
+ readonly TOOL_SERVERS: string;
24
+ TOOL_SERVER_AUTH_START: (id: string) => string;
25
+ TOOL_SERVER_AUTH_CONNECTION: (id: string) => string;
26
+ readonly TOOL_SERVERS_SIGN_IN_EXCHANGE: string;
27
+ readonly LOG: string;
28
+ };
29
+
30
+ export declare interface AppBrandingResponse {
31
+ success: boolean;
32
+ data: BrandingResponseData | null;
33
+ }
34
+
35
+ export declare const APPEARANCE_MODE_VALUES: AppearanceMode[];
36
+
37
+ export declare const APPEARANCE_MODES: {
38
+ readonly LIGHT: "light";
39
+ readonly DARK: "dark";
40
+ readonly SYSTEM: "system";
41
+ };
42
+
43
+ export declare type AppearanceMode = (typeof APPEARANCE_MODES)[keyof typeof APPEARANCE_MODES];
44
+
45
+ export declare interface AppResponse<T> {
46
+ success: boolean;
47
+ data: T;
48
+ message?: string;
49
+ }
50
+
51
+ export declare const AUTH_HEADERS: {
52
+ readonly ACCESS_TOKEN: "x-access-token";
53
+ readonly REFRESH_TOKEN: "x-refresh-token";
54
+ };
55
+
56
+ export declare const AUTH_PATHS: {
57
+ readonly LOGIN: "/auth/login";
58
+ readonly SIGNUP: "/auth/signup";
59
+ readonly LOGOUT: "/auth/logout";
60
+ readonly REFRESH: "/auth/refresh";
61
+ readonly FORGOT_PASSWORD: "/auth/forgot-password";
62
+ readonly RESET_PASSWORD: "/auth/reset-password";
63
+ readonly SSO_START: "/auth/sso/start";
64
+ readonly SSO_EXCHANGE: "/auth/sso/exchange";
65
+ readonly ORGANIZATIONS: "/organizations";
66
+ };
67
+
68
+ export declare interface AuthApiResult {
69
+ body: AppResponse<SessionResponse>;
70
+ tokens: AuthHeaderTokens;
71
+ }
72
+
73
+ export declare interface AuthHeaderTokens {
74
+ accessToken: string;
75
+ refreshToken: string;
76
+ }
77
+
78
+ export declare interface AuthState {
79
+ user: UserResponse | null;
80
+ accessToken: string | null;
81
+ refreshToken: string | null;
82
+ tokenExpiresAt: number | null;
83
+ selectedOrgId: string | null;
84
+ isAuthenticated: boolean;
85
+ isLoading: boolean;
86
+ }
87
+
88
+ export declare interface BrandingConfig {
89
+ startScreen?: StartScreenConfig;
90
+ typography?: TypographyConfig;
91
+ cornerRadius?: string;
92
+ themes?: BrandingThemes;
93
+ orbPosition?: OrbPosition;
94
+ }
95
+
96
+ export declare const BrandingContext: Context<BrandingContextValue>;
97
+
98
+ export declare interface BrandingContextValue {
99
+ theme: ResolvedTheme;
100
+ setTheme: (theme: AppearanceMode) => void;
101
+ appearanceMode: AppearanceMode;
102
+ isLoading: boolean;
103
+ error: Error | null;
104
+ currentThemeColors: BrandingTheme | null;
105
+ themeStyles: ChatThemeStyles;
106
+ orbPosition?: OrbPosition;
107
+ }
108
+
109
+ export declare type BrandingResponseData = BrandingConfig;
110
+
111
+ export declare interface BrandingTheme {
112
+ surface?: SurfaceColors;
113
+ text?: TextColors;
114
+ status?: StatusColors;
115
+ }
116
+
117
+ export declare interface BrandingThemes {
118
+ light?: BrandingTheme;
119
+ dark?: BrandingTheme;
120
+ }
121
+
122
+ export declare function brandingToThemeStyles(branding: BrandingConfig | null, theme: BrandingTheme | null, resolvedTheme?: ResolvedTheme): ChatThemeStyles;
123
+
124
+ export declare const BRIDGE_TOAST_EVENT_NAME = "bridge-toast";
125
+
126
+ export declare type BridgeToastDetail = ToastOptions;
127
+
128
+ declare type CallbackFn = (payload?: unknown) => void;
129
+
130
+ export declare const capitalizeFirst: (text: string) => string;
131
+
132
+ export declare interface ChargebeePaymentInit {
133
+ provider: "chargebee";
134
+ payment_id: string;
135
+ status: string;
136
+ config: {
137
+ site: string;
138
+ hosted_page_url: string;
139
+ amount?: number;
140
+ currency?: string;
141
+ expires_at?: number;
142
+ };
143
+ }
144
+
145
+ export declare interface ChatInputColors {
146
+ background?: string;
147
+ placeholderColor?: string;
148
+ border?: {
149
+ style?: string;
150
+ color?: string;
151
+ width?: string;
152
+ opacity?: number;
153
+ };
154
+ }
155
+
156
+ export declare interface ChatSurfaceColors {
157
+ background?: string;
158
+ input?: string;
159
+ inputField?: InputFieldColors;
160
+ }
161
+
162
+ export declare interface ChatThemeStyles {
163
+ bgColor: string;
164
+ inputBgColor: string;
165
+ sidebarBg: string;
166
+ sidebarBorderColor: string;
167
+ widgetBg: string;
168
+ settingsGroupBg: string;
169
+ inputBorderStyle: "none" | "solid" | "dashed" | "dotted";
170
+ inputBorderColor: string;
171
+ inputBorderWidth: string;
172
+ inputBorderOpacity: number;
173
+ widgetBorderStyle: "none" | "solid" | "dashed" | "dotted";
174
+ widgetBorderColor: string;
175
+ widgetBorderWidth: string;
176
+ widgetBorderOpacity: number;
177
+ placeholderColor: string;
178
+ primaryText: string;
179
+ secondaryText: string;
180
+ tertiaryText: string;
181
+ userMsgBg: string;
182
+ userMsgText: string;
183
+ userMsgBorderStyle: "none" | "solid" | "dashed" | "dotted";
184
+ userMsgBorderColor: string;
185
+ userMsgBorderWidth: string;
186
+ userMsgBorderOpacity: number;
187
+ sideMenuHeadings: string;
188
+ sideMenuText: string;
189
+ sideMenuIcon: string;
190
+ sideMenuProfile: string;
191
+ statusPrimary: StatusThemeVariant;
192
+ statusSecondary: StatusThemeVariant;
193
+ statusSuccess: StatusThemeVariant;
194
+ statusDanger: StatusThemeVariant;
195
+ statusWarning: StatusThemeVariant;
196
+ statusInfo: StatusThemeVariant;
197
+ statusDiscovery: StatusThemeVariant;
198
+ switchCheckedColor: string;
199
+ switchUncheckedColor: string;
200
+ fontFamily: string;
201
+ fontFamilyMono: string;
202
+ fontSize: number;
203
+ borderRadius: number;
204
+ cornerRadiusMode: CornerRadiusMode;
205
+ chatInputPlaceholder: string;
206
+ }
207
+
208
+ export declare function clearAuthTokens(storage: SyncKeyValueStorage): void;
209
+
210
+ export declare const clearLastResponseTime: ActionCreatorWithoutPayload<"indicator/clearLastResponseTime">;
211
+
212
+ export declare const clearSession: ActionCreatorWithoutPayload<"auth/clearSession">;
213
+
214
+ export declare const CORNER_RADIUS_MODES: {
215
+ readonly PILL: "pill";
216
+ readonly ROUNDED: "rounded";
217
+ readonly SHARP: "sharp";
218
+ };
219
+
220
+ export declare type CornerRadiusMode = (typeof CORNER_RADIUS_MODES)[keyof typeof CORNER_RADIUS_MODES];
221
+
222
+ export declare function createTokenRefresher(opts: TokenRefresherOptions): () => Promise<TokenRefreshResult | null>;
223
+
224
+ export declare const defaultChatThemeStyles: ChatThemeStyles;
225
+
226
+ export declare const defaultDarkThemeStyles: ChatThemeStyles;
227
+
228
+ export declare const defaultIsTransient: TransientClassifier;
229
+
230
+ export declare const defaultLightThemeStyles: ChatThemeStyles;
231
+
232
+ export declare function detectOrgSwitch(activeOrgId: string, storage: SyncKeyValueStorage): OrgSwitchReason;
233
+
234
+ export declare const ensureFreshToken: () => Promise<TokenRefreshResult | null>;
235
+
236
+ export declare class EventEmitter {
237
+ private static instance;
238
+ private events;
239
+ private constructor();
240
+ static getInstance(): EventEmitter;
241
+ on(event: string, listenerIdOrCallback: string | CallbackFn, callback?: CallbackFn): () => void;
242
+ off(event: string, callback: CallbackFn): void;
243
+ emit(event: string, payload?: unknown): void;
244
+ clear(event?: string): void;
245
+ }
246
+
247
+ export declare const eventEmitter: EventEmitter;
248
+
249
+ export declare function extractTokens(response: Response): AuthHeaderTokens;
250
+
251
+ export declare type ExtraHydration = (storage: Storage_2, dispatch: Dispatch<any>) => Promise<unknown>;
252
+
253
+ export declare const FEATURE_FLAGS: {
254
+ readonly SSO: "sso";
255
+ };
256
+
257
+ export declare type FeatureFlag = (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS];
258
+
259
+ export declare interface ForgotPasswordRequest {
260
+ email: string;
261
+ }
262
+
263
+ export declare const formatCamelCaseToTitle: (text: string) => string;
264
+
265
+ export declare const formatCardNumber: (value: string) => string;
266
+
267
+ export declare const formatCVC: (value: string) => string;
268
+
269
+ export declare const formatExpiryDate: (value: string) => string;
270
+
271
+ export declare const formatTimeRemaining: (timeMs: number) => string;
272
+
273
+ export declare const formatTimestamp: (timestamp: string, now?: Date) => string;
274
+
275
+ export declare const generateUniqueId: () => string;
276
+
277
+ export declare const getApiUrl: (path: string) => string;
278
+
279
+ export declare const getAppearanceModeStorageKey: (userId?: string | null) => string;
280
+
281
+ export declare function getArrayOfObjects<T>(data: T[] | T[][]): T[];
282
+
283
+ export declare const getBaseUrl: () => string;
284
+
285
+ export declare const getCustomHeaders: () => Record<string, string>;
286
+
287
+ export declare function getDefaultThemeStyles(theme: ResolvedTheme): ChatThemeStyles;
288
+
289
+ export declare function getErrorMessage(err: unknown, fallback?: string): string;
290
+
291
+ export declare const getInitials: (name?: string, email?: string) => string;
292
+
293
+ export declare function getPaymentId(payload?: PaymentInitPayload | null): string | undefined;
294
+
295
+ export declare const getPaymentProviderHint: () => PaymentProviderType | undefined;
296
+
297
+ export declare const getSendDiagnostics: () => boolean;
298
+
299
+ export declare const getStorageRef: () => Storage_2 | null;
300
+
301
+ export declare const getTimeUntilExpiry: (expiresAt: number | null) => number;
302
+
303
+ export declare const getTimeUntilRefresh: (expiresAt: number | null) => number;
304
+
305
+ export declare const getTokenRefreshHandler: () => typeof _tokenRefreshHandler;
306
+
307
+ export declare function handleSharedEvent(event: SharedEvent, deps: SharedHandlerDeps): void;
308
+
309
+ export declare const hasWidgets: (msg: Message) => msg is Message & {
310
+ widget: NonNullable<Message["widget"]>;
311
+ };
312
+
313
+ export declare function hexToRgba(hex: string, alpha: number): string;
314
+
315
+ export declare const hydrateAppBoot: (storage: Storage_2) => Promise<void>;
316
+
317
+ export declare const hydrateSession: (storage: Storage_2) => ThunkAction<Promise<void>, unknown, unknown, UnknownAction>;
318
+
319
+ export declare const IDP_HINTS: {
320
+ readonly GOOGLE: "google";
321
+ readonly APPLE: "apple";
322
+ readonly MICROSOFT: "microsoft";
323
+ };
324
+
325
+ export declare type IdpHint = (typeof IDP_HINTS)[keyof typeof IDP_HINTS];
326
+
327
+ export declare const INDICATOR_TIMER_ACTIONS: {
328
+ readonly KEEP: "keep";
329
+ readonly FINALIZE: "finalize";
330
+ readonly CANCEL: "cancel";
331
+ };
332
+
333
+ export declare const indicatorReducer: Reducer< {
334
+ lastResponseTime: number | null;
335
+ }>;
336
+
337
+ export declare interface IndicatorState {
338
+ lastResponseTime: number | null;
339
+ }
340
+
341
+ export declare type IndicatorTimerAction = (typeof INDICATOR_TIMER_ACTIONS)[keyof typeof INDICATOR_TIMER_ACTIONS];
342
+
343
+ export declare const initializeChatConfig: (params: {
344
+ baseUrl: string;
345
+ customHeaders?: Record<string, string>;
346
+ paymentProvider?: PaymentProviderType;
347
+ }) => void;
348
+
349
+ export declare function initLogger(opts: InitLoggerOptions): void;
350
+
351
+ export declare interface InitLoggerOptions {
352
+ appName: string;
353
+ appVersion: string;
354
+ environment: string;
355
+ isDev: boolean;
356
+ otlpEndpoint?: string;
357
+ logTransport?: LogTransport;
358
+ consoleMinLevel?: LogLevel;
359
+ getContext: () => LogAttrs;
360
+ extraSinks?: LogSink[];
361
+ flushOnAppHide?: boolean;
362
+ }
363
+
364
+ export declare interface InputFieldColors {
365
+ background?: string;
366
+ borderColor?: string;
367
+ placeholderColor?: string;
368
+ }
369
+
370
+ export declare const isDevMode: () => boolean;
371
+
372
+ export declare const isTokenAboutToExpire: (expiresAt: number | null) => boolean;
373
+
374
+ export declare const isTokenExpired: (expiresAt: number | null) => boolean;
375
+
376
+ export declare const joinOrgMountBase: (host: string, orgId?: string | null) => string;
377
+
378
+ export declare const LOG_LEVELS: {
379
+ readonly DEBUG: "DEBUG";
380
+ readonly INFO: "INFO";
381
+ readonly WARN: "WARN";
382
+ readonly ERROR: "ERROR";
383
+ };
384
+
385
+ export declare interface LogAttrs {
386
+ app_name?: string;
387
+ app_version?: string;
388
+ environment?: string;
389
+ org_id?: string;
390
+ user_id?: string;
391
+ conversation_id?: string;
392
+ api_name?: string;
393
+ request_id?: string;
394
+ [key: string]: unknown;
395
+ }
396
+
397
+ export declare const logger: {
398
+ debug(input: LogInput): void;
399
+ info(input: LogInput): void;
400
+ warn(input: LogInput): void;
401
+ error(input: LogInput): void;
402
+ flush(): Promise<void> | void;
403
+ };
404
+
405
+ export declare type LoggerContextProvider = () => LogAttrs;
406
+
407
+ export declare type LogInput = LogAttrs & {
408
+ message: string;
409
+ };
410
+
411
+ export declare type LogLevel = (typeof LOG_LEVELS)[keyof typeof LOG_LEVELS];
412
+
413
+ export declare const logout: ActionCreatorWithoutPayload<"auth/clearSession">;
414
+
415
+ export declare interface LogoutRequest {
416
+ refresh_token: string;
417
+ user_id: string;
418
+ }
419
+
420
+ export declare type LogRecord = LogAttrs & {
421
+ level: LogLevel;
422
+ message: string;
423
+ timestamp: string;
424
+ };
425
+
426
+ export declare interface LogSink {
427
+ emit(record: LogRecord): void;
428
+ flush?(): Promise<void> | void;
429
+ }
430
+
431
+ export declare type LogTransport = "otel" | "http-json";
432
+
433
+ export declare interface Message {
434
+ id: number | string;
435
+ msg_id?: string;
436
+ sender: "user" | "agent" | "system";
437
+ message: string | unknown;
438
+ timestamp: string;
439
+ tookMs?: number;
440
+ error?: string;
441
+ message_type?: string[];
442
+ widget?: unknown[];
443
+ request_id?: string;
444
+ }
445
+
446
+ export declare interface MessageResult {
447
+ message: string;
448
+ }
449
+
450
+ export declare interface MoyasarApplePayConfig {
451
+ country: string;
452
+ label: string;
453
+ validate_merchant_url: string;
454
+ }
455
+
456
+ export declare interface MoyasarCustomerInfo {
457
+ name?: string;
458
+ email?: string;
459
+ phone?: string;
460
+ reference_id?: string;
461
+ }
462
+
463
+ export declare interface MoyasarPaymentInit {
464
+ provider: "moyasar";
465
+ status: string;
466
+ config: {
467
+ given_id: string;
468
+ publishable_key: string;
469
+ amount: number;
470
+ currency: string;
471
+ description: string;
472
+ language?: "en" | "ar";
473
+ methods?: ("creditcard" | "applepay" | "stcpay")[];
474
+ metadata?: {
475
+ reference_id?: string;
476
+ [key: string]: string | undefined;
477
+ };
478
+ customer?: MoyasarCustomerInfo;
479
+ apple_pay?: MoyasarApplePayConfig;
480
+ };
481
+ }
482
+
483
+ export declare const NetworkContext: Context<NetworkMonitor>;
484
+
485
+ export declare interface NetworkMonitor {
486
+ getState(): NetworkState;
487
+ subscribe(listener: () => void): () => void;
488
+ }
489
+
490
+ export declare interface NetworkState {
491
+ isConnected: boolean;
492
+ isInternetReachable: boolean | null;
493
+ }
494
+
495
+ export declare const ORB_POSITIONS: {
496
+ readonly FOREGROUND: "foreground";
497
+ readonly BACKGROUND: "background";
498
+ };
499
+
500
+ export declare const ORB_URL = "https://one-interface-assets.nyc3.cdn.digitaloceanspaces.com/Orb.mp4";
501
+
502
+ export declare type OrbPosition = (typeof ORB_POSITIONS)[keyof typeof ORB_POSITIONS];
503
+
504
+ export declare const ORG_MOUNT_SUFFIX = "chat";
505
+
506
+ export declare interface Organization {
507
+ id: string;
508
+ name: string;
509
+ }
510
+
511
+ export declare type OrgSwitchReason = "storage" | "jwt" | null;
512
+
513
+ export declare function parseJwtPayload(token: string | null | undefined): Record<string, unknown> | null;
514
+
515
+ export declare function parseOrgFromJwt(token: string | null | undefined): string | null;
516
+
517
+ export declare const PATTERNS: {
518
+ readonly EMAIL: RegExp;
519
+ readonly NON_DIGIT: RegExp;
520
+ readonly PHONE_E164: RegExp;
521
+ };
522
+
523
+ export declare type PaymentInitPayload = StripePaymentInit | MoyasarPaymentInit | ChargebeePaymentInit;
524
+
525
+ export declare type PaymentProviderType = "stripe" | "moyasar" | "chargebee";
526
+
527
+ export declare const PROFILE_LIMITS: {
528
+ readonly NAME_MAX_LENGTH: 64;
529
+ readonly PHONE_MIN_LENGTH: 8;
530
+ readonly PHONE_MAX_LENGTH: 16;
531
+ };
532
+
533
+ export declare const readAccessToken: () => string | null;
534
+
535
+ export declare const readTokenExpiresAt: () => number | null;
536
+
537
+ export declare interface RefreshApiResult {
538
+ body: SessionRefreshResponse;
539
+ tokens: AuthHeaderTokens;
540
+ }
541
+
542
+ export declare interface RefreshRequest {
543
+ refresh_token: string;
544
+ user_id: string;
545
+ }
546
+
547
+ export declare function registerEventListener(eventName: string, handler: CallbackFn): () => void;
548
+
549
+ export declare function registerLoggerContextProvider(provider: LoggerContextProvider): void;
550
+
551
+ export declare function registerLoggerSink(sink: LogSink): void;
552
+
553
+ export declare const removeSpecialCharsAndSpaces: (type: string) => string;
554
+
555
+ export declare function resetLoggerForTests(): Promise<void>;
556
+
557
+ export declare interface ResetPasswordRequest {
558
+ email: string;
559
+ code: string;
560
+ new_password: string;
561
+ }
562
+
563
+ export declare type ResolvedTheme = Exclude<AppearanceMode, typeof APPEARANCE_MODES.SYSTEM>;
564
+
565
+ export declare const sanitizeExpiryDate: (value: string) => string;
566
+
567
+ export declare interface SessionCreateRequest {
568
+ email: string;
569
+ password: string;
570
+ }
571
+
572
+ export declare const sessionExpired: ActionCreatorWithoutPayload<"auth/sessionExpired">;
573
+
574
+ export declare const sessionListenerMiddleware: ListenerMiddlewareInstance<unknown, ThunkDispatch<unknown, unknown, UnknownAction>, unknown>;
575
+
576
+ export declare const sessionReducer: Reducer<AuthState>;
577
+
578
+ export declare interface SessionRefreshResponse {
579
+ success: boolean;
580
+ data?: {
581
+ expiry_time: number;
582
+ };
583
+ message?: string;
584
+ }
585
+
586
+ export declare interface SessionResponse {
587
+ expiry_time: number;
588
+ user: {
589
+ id: string;
590
+ email: string;
591
+ name: string;
592
+ role: string;
593
+ scopes: string[];
594
+ };
595
+ }
596
+
597
+ export declare const setAccessTokenReader: (fn: () => string | null) => void;
598
+
599
+ export declare const setCredentials: ActionCreatorWithNonInferrablePayload<"auth/setSession">;
600
+
601
+ export declare const setIsDev: (value: boolean) => void;
602
+
603
+ export declare const setLastResponseTime: ActionCreatorWithOptionalPayload<number, "indicator/setLastResponseTime">;
604
+
605
+ export declare function setModuleStorage(s: Storage_2): void;
606
+
607
+ export declare function setNetworkLoggingEnabled(enabled: boolean): void;
608
+
609
+ export declare const setSelectedOrgId: ActionCreatorWithOptionalPayload<string, "auth/setSelectedOrgId">;
610
+
611
+ export declare const setSession: ActionCreatorWithNonInferrablePayload<"auth/setSession">;
612
+
613
+ export declare interface SettingsColors {
614
+ groupBackground?: string;
615
+ }
616
+
617
+ export declare const setTokenExpiresAtReader: (fn: () => number | null) => void;
618
+
619
+ export declare const setTokenRefreshHandler: (handler: (() => Promise<TokenRefreshResult | null>) | null) => void;
620
+
621
+ export declare type SharedEvent = {
622
+ kind: 'status_update';
623
+ statusText: string;
624
+ } | {
625
+ kind: 'widget';
626
+ widget: unknown;
627
+ messageId?: number | string;
628
+ } | {
629
+ kind: 'payment';
630
+ payment: PaymentInitPayload;
631
+ } | {
632
+ kind: 'sign_in';
633
+ signIn: SignInInitPayload;
634
+ } | {
635
+ kind: 'error';
636
+ error: string;
637
+ } | {
638
+ kind: 'text';
639
+ text: string;
640
+ messageId?: number | string;
641
+ } | {
642
+ kind: 'conversation_title';
643
+ title: string;
644
+ };
645
+
646
+ export declare type SharedEventKind = SharedEvent['kind'];
647
+
648
+ export declare interface SharedHandlerDeps {
649
+ setStatusText: (text: string | null) => void;
650
+ setIsAgentWorking: (working: boolean) => void;
651
+ appendStreamText: (text: string, messageId?: number | string) => void;
652
+ pushWidget: (widget: unknown, messageId?: number | string) => void;
653
+ onPayment: (payment: PaymentInitPayload) => void;
654
+ onSignIn?: (init: SignInInitPayload) => void;
655
+ onError: (error: string) => void;
656
+ onStatusActive?: (statusText: string) => void;
657
+ onConversationTitle?: (title: string) => void;
658
+ }
659
+
660
+ export declare const showErrorToast: (message?: string) => void;
661
+
662
+ export declare const showSuccessToast: (message?: string) => void;
663
+
664
+ export declare const showToast: (options: ToastOptions) => void;
665
+
666
+ export declare interface SideMenuColors {
667
+ background?: string;
668
+ headings?: string;
669
+ headingsColor?: string;
670
+ textContent?: string;
671
+ textContentColor?: string;
672
+ icons?: string;
673
+ iconColor?: string;
674
+ textProfile?: string;
675
+ profileTextColor?: string;
676
+ }
677
+
678
+ export declare interface SignInInitPayload {
679
+ authorize_url: string;
680
+ state: string;
681
+ }
682
+
683
+ export declare interface SignupRequest {
684
+ email: string;
685
+ password: string;
686
+ first_name: string;
687
+ last_name: string;
688
+ }
689
+
690
+ export declare type SsoStartResponse = AppResponse<{
691
+ authorize_url: string;
692
+ }>;
693
+
694
+ export declare interface StartScreenConfig {
695
+ mode?: string;
696
+ greetingMessage?: string;
697
+ inputPlaceholder?: string;
698
+ }
699
+
700
+ export declare interface StatusColors {
701
+ primary?: StatusVariant;
702
+ secondary?: StatusVariant;
703
+ success?: StatusVariant;
704
+ danger?: StatusVariant;
705
+ warning?: StatusVariant;
706
+ info?: StatusVariant;
707
+ discovery?: StatusVariant;
708
+ }
709
+
710
+ export declare interface StatusThemeVariant {
711
+ solid: string;
712
+ background: string;
713
+ text: string;
714
+ }
715
+
716
+ export declare interface StatusVariant {
717
+ solid?: string;
718
+ background?: string;
719
+ text?: string;
720
+ }
721
+
722
+ declare interface Storage_2 {
723
+ getItem(key: string): Promise<string | null>;
724
+ setItem(key: string, value: string): Promise<void>;
725
+ removeItem(key: string): Promise<void>;
726
+ }
727
+ export { Storage_2 as Storage }
728
+
729
+ export declare const STORAGE_KEYS: {
730
+ readonly ACCESS_TOKEN: "accessToken";
731
+ readonly REFRESH_TOKEN: "refreshToken";
732
+ readonly TOKEN_EXPIRES_AT: "tokenExpiresAt";
733
+ readonly USER: "user";
734
+ readonly SELECTED_ORG_ID: "selectedOrgId";
735
+ readonly SELECTED_ORG_NAME: "selectedOrgName";
736
+ readonly APPEARANCE_MODE_KEY: "1interface_appearance_mode";
737
+ readonly LOCATION_ENABLED: "1interface_location_enabled";
738
+ readonly LOCATION_CACHE: "1interface_cached_location";
739
+ readonly DEBUG_MODE: "1interface_debug_mode";
740
+ readonly STT_AUTO_SEND: "1interface_stt_auto_send";
741
+ readonly STT_IMPLEMENTATION: "1interface_stt_implementation";
742
+ readonly SEND_DIAGNOSTICS: "1interface_send_diagnostics";
743
+ readonly ACTIVE_CONVERSATION_ID: "1interface_active_conversation_id";
744
+ };
745
+
746
+ export declare const StorageContext: Context<Storage_2>;
747
+
748
+ export declare interface StripePaymentInit {
749
+ provider: "stripe";
750
+ payment_id: string;
751
+ status: string;
752
+ config: {
753
+ client_secret: string;
754
+ publishable_key: string;
755
+ };
756
+ }
757
+
758
+ export declare const STT_IMPLEMENTATIONS: {
759
+ readonly ONLINE: "online";
760
+ readonly DEVICE: "device";
761
+ };
762
+
763
+ export declare type SttImplementation = (typeof STT_IMPLEMENTATIONS)[keyof typeof STT_IMPLEMENTATIONS];
764
+
765
+ export declare interface SurfaceColors {
766
+ chat?: ChatSurfaceColors;
767
+ chatInput?: ChatInputColors;
768
+ input?: ChatInputColors;
769
+ widget?: WidgetSurfaceColors;
770
+ userMessage?: UserMessageColors;
771
+ sideMenu?: SideMenuColors;
772
+ settings?: SettingsColors;
773
+ }
774
+
775
+ export declare interface SyncKeyValueStorage {
776
+ getItem(key: string): string | null;
777
+ setItem(key: string, value: string): void;
778
+ removeItem(key: string): void;
779
+ }
780
+
781
+ export declare interface TextColors {
782
+ primary?: string;
783
+ secondary?: string;
784
+ tertiary?: string;
785
+ }
786
+
787
+ export declare const TIMING: {
788
+ readonly TOKEN_REFRESH_THRESHOLD_MS: number;
789
+ readonly TOKEN_CLOCK_SKEW_MS: number;
790
+ readonly TOKEN_DEFAULT_EXPIRY_MS: number;
791
+ readonly THINKING_STATE_TIMEOUT_MS: 600;
792
+ readonly MESSAGE_WARNING_TIMEOUT_MS: 10000;
793
+ readonly TOAST_DURATION_MS: 5000;
794
+ readonly TOAST_ERROR_DURATION_MS: 7000;
795
+ readonly INPUT_DEBOUNCE_MS: 300;
796
+ readonly SEARCH_DEBOUNCE_MS: 500;
797
+ readonly CONFIG_TIMEOUT_MS: 5000;
798
+ };
799
+
800
+ declare interface ToastOptions {
801
+ title: string;
802
+ description?: string;
803
+ variant?: ToastVariant;
804
+ duration?: number;
805
+ }
806
+
807
+ declare type ToastVariant = "default" | "destructive";
808
+
809
+ export declare interface TokenRefresherOptions {
810
+ performRefresh: () => Promise<TokenRefreshResult | null>;
811
+ isTransient?: TransientClassifier;
812
+ maxAttempts?: number;
813
+ backoffBaseMs?: number;
814
+ }
815
+
816
+ declare let _tokenRefreshHandler: (() => Promise<TokenRefreshResult | null>) | null;
817
+
818
+ export declare interface TokenRefreshResult {
819
+ accessToken: string;
820
+ refreshToken?: string;
821
+ expiresIn?: number;
822
+ }
823
+
824
+ export declare type TransientClassifier = (err: unknown) => boolean;
825
+
826
+ export declare const truncateWordLimit: (text: string, wordLimit: number) => string;
827
+
828
+ export declare interface TypographyConfig {
829
+ fontFamily?: string;
830
+ fontFamilyMono?: string;
831
+ }
832
+
833
+ export declare const updateUser: ActionCreatorWithNonInferrablePayload<"auth/updateUser">;
834
+
835
+ export declare function useBranding(): BrandingContextValue;
836
+
837
+ export declare const useNetworkState: () => NetworkState;
838
+
839
+ export declare interface UserMessageColors {
840
+ background?: string;
841
+ textColor?: string;
842
+ border?: {
843
+ style?: string;
844
+ color?: string;
845
+ width?: string;
846
+ opacity?: number;
847
+ };
848
+ }
849
+
850
+ export declare interface UserResponse {
851
+ id: string;
852
+ email: string;
853
+ name: string;
854
+ role: string;
855
+ scopes: string[];
856
+ }
857
+
858
+ export declare const useStorage: () => Storage_2;
859
+
860
+ export declare const validateExpiryDate: (value: string) => boolean;
861
+
862
+ export declare interface WidgetSurfaceColors {
863
+ background?: string;
864
+ border?: {
865
+ style?: string;
866
+ color?: string;
867
+ opacity?: number;
868
+ width?: string;
869
+ };
870
+ }
871
+
872
+ export declare function writeOrgToStorage(orgId: string, storage: SyncKeyValueStorage): void;
873
+
874
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@reduxjs/toolkit"),t=require("react"),r=e=>{const t=e.match(/^(\d{2})\/(\d{2})$/);if(!t)return!1;const r=Number(t[1]),s=Number(t[2]);if(r<1||r>12)return!1;const o=new Date,n=o.getFullYear()%100,a=o.getMonth()+1;return!(s<n||s===n&&r<a||r>12)},s=e=>{if(!e)return"";if(!r(e)){const t=e.match(/^(\d{2})\/(\d{2})$/);if(t){const e=Number(t[1]),r=Number(t[2]),s=new Date,o=s.getFullYear()%100,n=s.getMonth()+1;if(r<o||r===o&&e<n||e>12)return""}}return e},o={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"};let n=null,a=null;const i=[];function u(e){if(n=e,i.length>0){const t=i.splice(0,i.length);for(const r of t)e.emit(r)}}function c(e){a=e}function l(e,t){const r=a?function(e){try{return e()??{}}catch{return{}}}(a):{},{message:s,...o}=t,u={...r,...o,level:e,message:s,timestamp:(new Date).toISOString()};n?n.emit(u):(i.length>=200&&i.shift(),i.push(u))}const d={debug(e){l(o.DEBUG,e)},info(e){l(o.INFO,e)},warn(e){l(o.WARN,e)},error(e){l(o.ERROR,e)},flush:()=>n?.flush?.()},p={[o.DEBUG]:0,[o.INFO]:1,[o.WARN]:2,[o.ERROR]:3};function g(e={}){const t=p[e.minLevel??o.DEBUG];return{emit(e){p[e.level]<t||(e.level===o.ERROR?console.error:e.level===o.WARN?console.warn:e.level===o.DEBUG?console.debug:console.info)(e)}}}const E={[o.DEBUG]:5,[o.INFO]:9,[o.WARN]:13,[o.ERROR]:17};function m(e){if(null===e)return"null";const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Error)return JSON.stringify({name:e.name,message:e.message,stack:e.stack});try{return JSON.stringify(e)}catch{return String(e)}}function F(e){const t={};for(const[r,s]of Object.entries(e))void 0!==s&&(t[r]=m(s));return t}let f=!1,x=null,S=!0;function h(e){S=e}function T(e){f||(f=!0,c(function(e){const t={app_name:e.appName,app_version:e.appVersion,environment:e.environment};return()=>({...t,...e.getContext()})}(e)),u(function(e){const t=[g({minLevel:e.consoleMinLevel??(e.isDev?o.DEBUG:o.WARN)})];if(e.otlpEndpoint&&!e.isDev){const r="otel"===(e.logTransport??"otel")?function(e){let t=!1,r=null,s=null;const o=[];function n(){s||(s=async function(){const[t,s,n,a]=await Promise.all([import("@opentelemetry/api-logs"),import("@opentelemetry/sdk-logs"),import("@opentelemetry/exporter-logs-otlp-http"),import("@opentelemetry/resources")]),i=a.resourceFromAttributes(e.resourceAttrs),u=new n.OTLPLogExporter({url:e.endpoint}),c=new s.LoggerProvider({resource:i,processors:[new s.BatchLogRecordProcessor(u)]});t.logs.setGlobalLoggerProvider(c);const l=t.logs.getLogger(e.resourceAttrs["service.name"]??"app");if(r={emit(e){const{level:t,message:r,timestamp:s,...o}=e;l.emit({severityNumber:E[t],severityText:t,body:JSON.stringify(e),attributes:F(o),timestamp:new Date(s)})},async flush(){await c.forceFlush()}},o.length>0){const e=o.splice(0,o.length);for(const t of e)r.emit(t)}}().catch(()=>{o.length=0,r=null,t=!0}))}return{emit(e){t||(r?r.emit(e):(n(),o.length>=200&&o.shift(),o.push(e)))},async flush(){(s||r)&&(n(),await s,r&&await r.flush())}}}({endpoint:e.otlpEndpoint,resourceAttrs:{"service.name":e.appName,"service.version":e.appVersion,"deployment.environment":e.environment}}):function(e){const t=e.maxBatchSize??50,r=e.scheduledDelayMs??5e3,s=e.maxQueueSize??2048,o=e.wrapBatch??(e=>e),n=[];let a=null;function i(){return null!==a&&(clearTimeout(a),a=null),0===n.length||0===(t=n.splice(0,n.length)).length?Promise.resolve():fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o(t)),keepalive:!0}).then(()=>{}).catch(()=>{});var t}return{emit(e){n.length>=s&&n.shift(),n.push(e),n.length>=t?i():null===a&&(a=setTimeout(()=>{a=null,i()},r))},async flush(){await i()}}}({endpoint:e.otlpEndpoint});t.push({emit(e){S&&r.emit(e)},flush:r.flush.bind(r)})}return e.extraSinks?.length&&t.push(...e.extraSinks),1===t.length?t[0]:function(e){return{emit(t){for(const r of e)try{r.emit(t)}catch{}},async flush(){await Promise.all(e.map(e=>e.flush?Promise.resolve(e.flush()).catch(()=>{}):Promise.resolve()))}}}(t)}(e)),!1!==e.flushOnAppHide&&x?.())}const y=Object.freeze(Object.defineProperty({__proto__:null,initLogger:T,registerPlatformFlushAttacher:function(e){x=e},resetInitLoggerStateForTests:function(){f=!1,x=null,S=!0},setNetworkLoggingEnabled:h},Symbol.toStringTag,{value:"Module"}));let O,A="",_={},I=null,R=()=>null,N=()=>null,C=!1;const M=()=>I,D=()=>N(),B=e=>{const t=e.startsWith("/")?e:`/${e}`;return`${A}/api${t}`},v="chat",k={CONVERSATIONS:()=>B("/conversations"),CONVERSATION_STREAM:e=>B(`/conversations/${e}`),CONVERSATION_START:e=>B(`/conversations/${e}/start`),get TRANSCRIBE(){return B("/transcribe")},get BRANDING(){return B("/branding")},get CONFIG(){return B("/config")},get PROFILE(){return B("/profile")},get AUTH_ME(){return B("/auth/me")},get ORGANIZATIONS_EXISTS(){return B("/organizations/exists")},get DEBUG(){return B("/debug")},get TOOL_SERVERS(){return B("/tool-servers")},TOOL_SERVER_AUTH_START:e=>B(`/tool-servers/${e}/auth/start`),TOOL_SERVER_AUTH_CONNECTION:e=>B(`/tool-servers/${e}/auth/connection`),get TOOL_SERVERS_SIGN_IN_EXCHANGE(){return B("/tool-servers/auth/exchange")},get LOG(){return B("/log")}},b={TOKEN_REFRESH_THRESHOLD_MS:6e5,TOKEN_CLOCK_SKEW_MS:3e4,TOKEN_DEFAULT_EXPIRY_MS:36e5,THINKING_STATE_TIMEOUT_MS:600,MESSAGE_WARNING_TIMEOUT_MS:1e4,TOAST_DURATION_MS:5e3,TOAST_ERROR_DURATION_MS:7e3,INPUT_DEBOUNCE_MS:300,SEARCH_DEBOUNCE_MS:500,CONFIG_TIMEOUT_MS:5e3},w={ACCESS_TOKEN:"accessToken",REFRESH_TOKEN:"refreshToken",TOKEN_EXPIRES_AT:"tokenExpiresAt",USER:"user",SELECTED_ORG_ID:"selectedOrgId",SELECTED_ORG_NAME:"selectedOrgName",APPEARANCE_MODE_KEY:"1interface_appearance_mode",LOCATION_ENABLED:"1interface_location_enabled",LOCATION_CACHE:"1interface_cached_location",DEBUG_MODE:"1interface_debug_mode",STT_AUTO_SEND:"1interface_stt_auto_send",STT_IMPLEMENTATION:"1interface_stt_implementation",SEND_DIAGNOSTICS:"1interface_send_diagnostics",ACTIVE_CONVERSATION_ID:"1interface_active_conversation_id"},P={ACCESS_TOKEN:"x-access-token",REFRESH_TOKEN:"x-refresh-token"};let L=!0;const U=3,G=500,H=e=>{const t=e?.status;return"FETCH_ERROR"===t||"TIMEOUT_ERROR"===t||("number"==typeof t?t>=500:(d.warn({message:"unknown error shape; treating as transient",api_name:"auth-refresh",error_message:e instanceof Error?e.message:String(e)}),!0))},K="bridge-toast";function $(e){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent(K,{detail:e}))}const W=K,V=e=>!!e&&Date.now()>=e-b.TOKEN_CLOCK_SKEW_MS,j=e=>!e||Date.now()>=e-b.TOKEN_REFRESH_THRESHOLD_MS;function z(e){if(!e)return null;const t=e.split(".");if(3!==t.length)return null;try{const e=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=e+"=".repeat((4-e.length%4)%4),s=atob(r),o=JSON.parse(s);return o&&"object"==typeof o&&!Array.isArray(o)?o:null}catch{return null}}function X(e){const t=z(e),r=t?.org_id;return"string"==typeof r&&r.length>0?r:null}class Y{static instance;events={};constructor(){}static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}on(e,t,r){const s="function"==typeof t?t:r;return this.events[e]||(this.events[e]=[]),this.events[e].push(s),()=>{this.off(e,s)}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(e=>e!==t))}emit(e,t){this.events[e]&&this.events[e].forEach(r=>{try{r(t)}catch(t){d.error({message:`Error in event handler for "${e}"`,api_name:"event-emitter",event:e,error_message:t instanceof Error?t.message:String(t)})}})}clear(e){e?delete this.events[e]:this.events={}}}const J=Y.getInstance(),q={LIGHT:"light",DARK:"dark",SYSTEM:"system"},Z=[q.LIGHT,q.DARK,q.SYSTEM],Q={PILL:"pill",ROUNDED:"rounded",SHARP:"sharp"},ee={bgColor:"linear-gradient(281.8deg, #061522 6.7%, #101F2F 59.64%, #3C3B4F 76.85%, #5D4C63 88.46%, #755770 99.24%)",inputBgColor:"#222D34",sidebarBg:"#0F1419",sidebarBorderColor:"#8F8F8F",widgetBg:"#222D34",settingsGroupBg:"#272626",inputBorderStyle:"solid",inputBorderColor:"#FFFFFF80",inputBorderWidth:"1px",inputBorderOpacity:50,widgetBorderStyle:"solid",widgetBorderColor:"#FFFFFF1A",widgetBorderWidth:"1px",widgetBorderOpacity:10,placeholderColor:"#8F8F8F",primaryText:"#FFFFFF",secondaryText:"#AFAFAF",tertiaryText:"#8F8F8F",userMsgBg:"#90629F",userMsgText:"#FFFFFF",userMsgBorderStyle:"none",userMsgBorderColor:"#FFFFFFFF",userMsgBorderWidth:"1px",userMsgBorderOpacity:100,sideMenuHeadings:"#FFFFFF",sideMenuText:"#AFAFAF",sideMenuIcon:"#8F8F8F",sideMenuProfile:"#FFFFFF",statusPrimary:{solid:"#90629F",background:"#90629F",text:"#FFFFFF"},statusSecondary:{solid:"#5D5D5D",background:"#F3F3F3",text:"#0D0D0D"},statusSuccess:{solid:"#00A240",background:"#D9F4E4",text:"#FFFFFF"},statusDanger:{solid:"#E02E2A",background:"#FFD9D9",text:"#FFFFFF"},statusWarning:{solid:"#E25507",background:"#FFE7D9",text:"#FFFFFF"},statusInfo:{solid:"#0285FF",background:"#E5F3FF",text:"#FFFFFF"},statusDiscovery:{solid:"#924FF7",background:"#EFE5FE",text:"#FFFFFF"},switchCheckedColor:"#90629F",switchUncheckedColor:"#222D34",fontFamily:"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif",fontFamilyMono:'"SF Mono", ui-monospace, monospace',fontSize:14,borderRadius:16,cornerRadiusMode:Q.PILL,chatInputPlaceholder:"Type anything..."},te={bgColor:"linear-gradient(281.8deg, #EEF2FF 6.7%, #E2E8FD 59.64%, #E8DFF4 76.85%, #F4DBE6 88.46%, #FFE1D0 99.24%)",inputBgColor:"#F4F4F5",sidebarBg:"#FFFFFF",sidebarBorderColor:"#9B9B9B",widgetBg:"#FFFFFF",settingsGroupBg:"#1A1A1A10",inputBorderStyle:"solid",inputBorderColor:"#0000001A",inputBorderWidth:"1px",inputBorderOpacity:10,widgetBorderStyle:"solid",widgetBorderColor:"#0000001A",widgetBorderWidth:"1px",widgetBorderOpacity:10,placeholderColor:"#9B9B9B",primaryText:"#1A1A1A",secondaryText:"#6B6B6B",tertiaryText:"#9B9B9B",userMsgBg:"#90629F",userMsgText:"#FFFFFF",userMsgBorderStyle:"none",userMsgBorderColor:"#000000FF",userMsgBorderWidth:"1px",userMsgBorderOpacity:100,sideMenuHeadings:"#1A1A1A",sideMenuText:"#6B6B6B",sideMenuIcon:"#9B9B9B",sideMenuProfile:"#1A1A1A",statusPrimary:{solid:"#90629F",background:"#90629F",text:"#FFFFFF"},statusSecondary:{solid:"#5D5D5D",background:"#F3F3F3",text:"#0D0D0D"},statusSuccess:{solid:"#00A240",background:"#D9F4E4",text:"#FFFFFF"},statusDanger:{solid:"#E02E2A",background:"#FFD9D9",text:"#FFFFFF"},statusWarning:{solid:"#E25507",background:"#FFE7D9",text:"#FFFFFF"},statusInfo:{solid:"#0285FF",background:"#E5F3FF",text:"#FFFFFF"},statusDiscovery:{solid:"#924FF7",background:"#EFE5FE",text:"#FFFFFF"},switchCheckedColor:"#90629F",switchUncheckedColor:"#F4F4F5",fontFamily:"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif",fontFamilyMono:'"SF Mono", ui-monospace, monospace',fontSize:14,borderRadius:16,cornerRadiusMode:Q.PILL,chatInputPlaceholder:"Type anything..."};function re(e){return e===q.LIGHT?te:ee}const se=ee;function oe(e,t){const r=e.replace("#","");let s;s=3===r.length?r.split("").map(e=>e+e).join(""):6===r.length?r:"000000";const o=Math.max(0,Math.min(100,t));return`#${s}${Math.round(o/100*255).toString(16).padStart(2,"0")}`.toUpperCase()}function ne(e,t){if(!e)return t.fontFamily;switch(e){case"Inter":return"'Inter', sans-serif";case"System":return"system-ui, -apple-system, sans-serif";default:return"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif"}}function ae(e,t){return e?`"${e}", ui-monospace, monospace`:t.fontFamilyMono}function ie(e,t){if(!e)return t.borderRadius;switch(e){case"none":return 0;case"sm":return 8;case"md":return 12;case"pill":return 16;default:const r=parseInt(e,10);return isNaN(r)?t.borderRadius:r}}function ue(e){switch(e){case"pill":return Q.PILL;case"none":return Q.SHARP;default:return 0===parseInt(e??"",10)?Q.SHARP:Q.ROUNDED}}const ce=t.createContext(void 0),le=t.createContext(null);let de=null;const pe=()=>de,ge=t.createContext(null),Ee={isConnected:!0,isInternetReachable:!0},me=e.createSlice({name:"auth",initialState:{user:null,accessToken:null,refreshToken:null,tokenExpiresAt:null,selectedOrgId:null,isAuthenticated:!1,isLoading:!1},reducers:{setSession:(e,t)=>{const{user:r,accessToken:s,refreshToken:o,expiresIn:n}=t.payload;void 0!==r&&(e.user=r),void 0!==s&&(e.accessToken=s),void 0!==o&&(e.refreshToken=o),void 0!==n?e.tokenExpiresAt=null===n?null:1e3*n:s&&(e.tokenExpiresAt=Date.now()+b.TOKEN_DEFAULT_EXPIRY_MS),e.isAuthenticated=Boolean(e.accessToken),e.isLoading=!1},updateUser:(e,t)=>{e.user={...e.user||{},...t.payload}},clearSession:e=>{e.user=null,e.accessToken=null,e.refreshToken=null,e.tokenExpiresAt=null,e.isAuthenticated=!1,e.isLoading=!1},sessionExpired:e=>{e.user=null,e.accessToken=null,e.refreshToken=null,e.tokenExpiresAt=null,e.isAuthenticated=!1,e.isLoading=!1},setSelectedOrgId:(e,t)=>{e.selectedOrgId=t.payload??null}}}),{setSession:Fe,updateUser:fe,clearSession:xe,sessionExpired:Se,setSelectedOrgId:he}=me.actions,Te=Fe,ye=xe,Oe=e.createListenerMiddleware();Oe.startListening({matcher:e.isAnyOf(Fe,fe,xe,Se),effect:async(e,t)=>{const r=pe();if(!r)return;const{auth:s}=t.getState(),o=[];o.push(s.accessToken?r.setItem(w.ACCESS_TOKEN,s.accessToken):r.removeItem(w.ACCESS_TOKEN)),o.push(s.refreshToken?r.setItem(w.REFRESH_TOKEN,s.refreshToken):r.removeItem(w.REFRESH_TOKEN)),o.push(null!=s.tokenExpiresAt?r.setItem(w.TOKEN_EXPIRES_AT,String(s.tokenExpiresAt)):r.removeItem(w.TOKEN_EXPIRES_AT)),o.push(s.user?r.setItem(w.USER,JSON.stringify(s.user)):r.removeItem(w.USER)),(xe.match(e)||Se.match(e))&&o.push(r.removeItem(w.LOCATION_CACHE),r.removeItem(w.DEBUG_MODE),r.removeItem(w.APPEARANCE_MODE_KEY),r.removeItem(w.LOCATION_ENABLED),r.removeItem(w.STT_AUTO_SEND),r.removeItem(w.STT_IMPLEMENTATION),r.removeItem(w.SEND_DIAGNOSTICS),r.removeItem(w.ACTIVE_CONVERSATION_ID)),await Promise.all(o)}});const Ae=me.reducer,_e={lastResponseTime:null},Ie=e.createSlice({name:"indicator",initialState:_e,reducers:{setLastResponseTime(e,t){e.lastResponseTime=t.payload},clearLastResponseTime(e){e.lastResponseTime=null}},extraReducers:t=>{t.addMatcher(e.isAnyOf(xe,Se),()=>_e)}}),{setLastResponseTime:Re,clearLastResponseTime:Ne}=Ie.actions,Ce=Ie.reducer;exports.API_ENDPOINTS=k,exports.APPEARANCE_MODES=q,exports.APPEARANCE_MODE_VALUES=Z,exports.AUTH_HEADERS=P,exports.AUTH_PATHS={LOGIN:"/auth/login",SIGNUP:"/auth/signup",LOGOUT:"/auth/logout",REFRESH:"/auth/refresh",FORGOT_PASSWORD:"/auth/forgot-password",RESET_PASSWORD:"/auth/reset-password",SSO_START:"/auth/sso/start",SSO_EXCHANGE:"/auth/sso/exchange",ORGANIZATIONS:"/organizations"},exports.BRIDGE_TOAST_EVENT_NAME=W,exports.BrandingContext=ce,exports.CORNER_RADIUS_MODES=Q,exports.EventEmitter=Y,exports.FEATURE_FLAGS={SSO:"sso"},exports.IDP_HINTS={GOOGLE:"google",APPLE:"apple",MICROSOFT:"microsoft"},exports.INDICATOR_TIMER_ACTIONS={KEEP:"keep",FINALIZE:"finalize",CANCEL:"cancel"},exports.LOG_LEVELS=o,exports.NetworkContext=ge,exports.ORB_POSITIONS={FOREGROUND:"foreground",BACKGROUND:"background"},exports.ORB_URL="https://one-interface-assets.nyc3.cdn.digitaloceanspaces.com/Orb.mp4",exports.ORG_MOUNT_SUFFIX=v,exports.PATTERNS={EMAIL:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,NON_DIGIT:/\D/g,PHONE_E164:/^\+[1-9]\d{1,14}$/},exports.PROFILE_LIMITS={NAME_MAX_LENGTH:64,PHONE_MIN_LENGTH:8,PHONE_MAX_LENGTH:16},exports.STORAGE_KEYS=w,exports.STT_IMPLEMENTATIONS={ONLINE:"online",DEVICE:"device"},exports.StorageContext=le,exports.TIMING=b,exports.brandingToThemeStyles=function(e,t,r=q.DARK){const s=re(r);if(!e||!t)return s;const o=t.surface?.chatInput?.border||t.surface?.input?.border,n=t.surface?.userMessage?.border,a=t.surface?.widget?.border;return{bgColor:t.surface?.chat?.background||s.bgColor,inputBgColor:t.surface?.chatInput?.background||t.surface?.input?.background||s.inputBgColor,sidebarBg:t.surface?.sideMenu?.background||s.sidebarBg,sidebarBorderColor:t.surface?.sideMenu?.iconColor||t.surface?.sideMenu?.icons||s.sidebarBorderColor,widgetBg:t.surface?.widget?.background||s.widgetBg,settingsGroupBg:t.surface?.settings?.groupBackground||s.settingsGroupBg,inputBorderStyle:o?.style||s.inputBorderStyle,inputBorderColor:o?.color?oe(o.color,o.opacity||100):s.inputBorderColor,inputBorderWidth:o?.width||s.inputBorderWidth,inputBorderOpacity:o?.opacity||100,widgetBorderStyle:a?.style||s.widgetBorderStyle,widgetBorderColor:a?.color?oe(a.color,a.opacity||100):s.widgetBorderColor,widgetBorderWidth:a?.width||s.widgetBorderWidth,widgetBorderOpacity:a?.opacity??s.widgetBorderOpacity,placeholderColor:t.surface?.chatInput?.placeholderColor||t.surface?.input?.placeholderColor||s.placeholderColor,primaryText:t.text?.primary||s.primaryText,secondaryText:t.text?.secondary||s.secondaryText,tertiaryText:t.text?.tertiary||s.tertiaryText,userMsgBg:t.surface?.userMessage?.background||s.userMsgBg,userMsgText:t.surface?.userMessage?.textColor||s.userMsgText,userMsgBorderStyle:n?.style||s.userMsgBorderStyle,userMsgBorderColor:n?.color?oe(n.color,n.opacity||100):s.userMsgBorderColor,userMsgBorderWidth:n?.width||s.userMsgBorderWidth,userMsgBorderOpacity:n?.opacity||0,sideMenuHeadings:t.surface?.sideMenu?.headingsColor||t.surface?.sideMenu?.headings||s.sideMenuHeadings,sideMenuText:t.surface?.sideMenu?.textContentColor||t.surface?.sideMenu?.textContent||s.sideMenuText,sideMenuIcon:t.surface?.sideMenu?.iconColor||t.surface?.sideMenu?.icons||s.sideMenuIcon,sideMenuProfile:t.surface?.sideMenu?.profileTextColor||t.surface?.sideMenu?.textProfile||s.sideMenuProfile,statusPrimary:{solid:t.status?.primary?.solid||s.statusPrimary.solid,background:t.status?.primary?.background||s.statusPrimary.background,text:t.status?.primary?.text||s.statusPrimary.text},statusSecondary:{solid:t.status?.secondary?.solid||s.statusSecondary.solid,background:t.status?.secondary?.background||s.statusSecondary.background,text:t.status?.secondary?.text||s.statusSecondary.text},statusSuccess:{solid:t.status?.success?.solid||s.statusSuccess.solid,background:t.status?.success?.background||s.statusSuccess.background,text:t.status?.success?.text||s.statusSuccess.text},statusDanger:{solid:t.status?.danger?.solid||s.statusDanger.solid,background:t.status?.danger?.background||s.statusDanger.background,text:t.status?.danger?.text||s.statusDanger.text},statusWarning:{solid:t.status?.warning?.solid||s.statusWarning.solid,background:t.status?.warning?.background||s.statusWarning.background,text:t.status?.warning?.text||s.statusWarning.text},statusInfo:{solid:t.status?.info?.solid||s.statusInfo.solid,background:t.status?.info?.background||s.statusInfo.background,text:t.status?.info?.text||s.statusInfo.text},statusDiscovery:{solid:t.status?.discovery?.solid||s.statusDiscovery.solid,background:t.status?.discovery?.background||s.statusDiscovery.background,text:t.status?.discovery?.text||s.statusDiscovery.text},switchCheckedColor:t.status?.primary?.solid||s.switchCheckedColor,switchUncheckedColor:t.surface?.chatInput?.background||s.switchUncheckedColor,fontFamily:ne(e.typography?.fontFamily,s),fontFamilyMono:ae(e.typography?.fontFamilyMono,s),fontSize:14,borderRadius:ie(e.cornerRadius,s),cornerRadiusMode:ue(e.cornerRadius),chatInputPlaceholder:e.startScreen.inputPlaceholder}},exports.capitalizeFirst=e=>e?e.split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"",exports.clearAuthTokens=function(e){try{e.removeItem(w.ACCESS_TOKEN),e.removeItem(w.REFRESH_TOKEN),e.removeItem(w.TOKEN_EXPIRES_AT),e.removeItem(w.USER)}catch{}},exports.clearLastResponseTime=Ne,exports.clearSession=xe,exports.createTokenRefresher=function(e){const{performRefresh:t,isTransient:r=H,maxAttempts:s=U,backoffBaseMs:o=G}=e;let n=null;return function(){return n||(n=(async()=>{for(let e=0;e<s;e++)try{return await t()}catch(t){if(!r(t))return null;if(e===s-1)break;const n=o*2**e+250*Math.random();await new Promise(e=>setTimeout(e,n))}return null})().finally(()=>{n=null}),n)}},exports.defaultChatThemeStyles=se,exports.defaultDarkThemeStyles=ee,exports.defaultIsTransient=H,exports.defaultLightThemeStyles=te,exports.detectOrgSwitch=function(e,t){try{const r=t.getItem(w.SELECTED_ORG_ID);if(r&&r!==e)return"storage";const s=X(t.getItem(w.ACCESS_TOKEN));return s&&s!==e?"jwt":null}catch{return null}},exports.ensureFreshToken=async()=>j(D())?await(M()?.())??null:null,exports.eventEmitter=J,exports.extractTokens=function(e){const t=e.headers.get(P.ACCESS_TOKEN),r=e.headers.get(P.REFRESH_TOKEN);if(!t)throw new Error(`Missing ${P.ACCESS_TOKEN} header in response`);if(!r)throw new Error(`Missing ${P.REFRESH_TOKEN} header in response`);return{accessToken:t,refreshToken:r}},exports.formatCVC=e=>e.replace(/\D/g,"").slice(0,4),exports.formatCamelCaseToTitle=e=>e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/^(.)/,e=>e.toUpperCase()).split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ").trim():"",exports.formatCardNumber=e=>e.replace(/\D/g,"").slice(0,16).replace(/(.{4})/g,"$1 ").trim(),exports.formatExpiryDate=e=>{const t=e.replace(/\D/g,"").slice(0,4);if(4===t.length){const e=t.slice(0,2)+"/"+t.slice(2);return s(e)}return t.length>=3?`${t.slice(0,2)}/${t.slice(2)}`:t.length>=1?t:""},exports.formatTimeRemaining=e=>{const t=Math.floor(e/6e4),r=Math.floor(e%6e4/1e3);return t>0?`${t}m ${r}s`:`${r}s`},exports.formatTimestamp=(e,t=new Date)=>{if(!e)return"";const r=new Date(e);if(isNaN(r.getTime()))return"";const s=t.getTime()-r.getTime(),o=Math.floor(s/6e4),n=Math.floor(s/36e5),a=Math.floor(s/864e5);return o<1?"Just now":o<60?`${o}m ago`:n<24?`${n}h ago`:a<7?`${a}d ago`:new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(r)},exports.generateUniqueId=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),exports.getApiUrl=B,exports.getAppearanceModeStorageKey=e=>e?`${w.APPEARANCE_MODE_KEY}:${e}`:w.APPEARANCE_MODE_KEY,exports.getArrayOfObjects=function(e){return Array.isArray(e)&&Array.isArray(e[0])?e.flat():e},exports.getBaseUrl=()=>A,exports.getCustomHeaders=()=>_,exports.getDefaultThemeStyles=re,exports.getErrorMessage=function(e,t="An unexpected error occurred."){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("data"in e){const t=e.data;if(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message)return t.message}}return t},exports.getInitials=(e,t)=>{if(e&&e.trim()){const t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.trim().slice(0,2).toUpperCase()}return t&&t.trim()?t.trim().slice(0,2).toUpperCase():"U"},exports.getPaymentId=function(e){if(e)return"moyasar"===e.provider?e.config?.given_id:e.payment_id},exports.getPaymentProviderHint=()=>O,exports.getSendDiagnostics=()=>L,exports.getStorageRef=pe,exports.getTimeUntilExpiry=e=>e?Math.max(0,e-Date.now()):0,exports.getTimeUntilRefresh=e=>e?Math.max(0,e-b.TOKEN_REFRESH_THRESHOLD_MS-Date.now()):0,exports.getTokenRefreshHandler=M,exports.handleSharedEvent=function(e,t){switch(e.kind){case"status_update":return t.setStatusText(e.statusText),t.setIsAgentWorking(!0),void t.onStatusActive?.(e.statusText);case"widget":return void t.pushWidget(e.widget,e.messageId);case"payment":return void t.onPayment(e.payment);case"sign_in":return void t.onSignIn?.(e.signIn);case"error":return void t.onError(e.error);case"text":return void t.appendStreamText(e.text,e.messageId);case"conversation_title":return void t.onConversationTitle?.(e.title);default:return}},exports.hasWidgets=e=>Array.isArray(e.widget)&&e.widget.length>0,exports.hexToRgba=function(e,t){let r=e.trim().replace(/^#/,"");if(3!==r.length&&4!==r.length||(r=r.split("").map(e=>e+e).join("")),!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(r))return e;const s=parseInt(r.slice(0,2),16),o=parseInt(r.slice(2,4),16),n=parseInt(r.slice(4,6),16),a=8===r.length?parseInt(r.slice(6,8),16)/255:1;return`rgba(${s}, ${o}, ${n}, ${Math.round(a*t*1e3)/1e3})`},exports.hydrateAppBoot=async e=>{const t=await e.getItem(w.SEND_DIAGNOSTICS);L=null===t||"true"===t},exports.hydrateSession=e=>async t=>{const[r,s,o,n]=await Promise.all([e.getItem(w.ACCESS_TOKEN),e.getItem(w.REFRESH_TOKEN),e.getItem(w.TOKEN_EXPIRES_AT),e.getItem(w.USER)]),a=o?parseInt(o,10):null;if((!r||!a||V(a))&&!s)return void(r&&await Promise.all([e.removeItem(w.ACCESS_TOKEN),e.removeItem(w.REFRESH_TOKEN),e.removeItem(w.TOKEN_EXPIRES_AT),e.removeItem(w.USER)]));let i=null;if(n)try{i=JSON.parse(n)}catch(e){d.error({message:"Failed to parse stored user during session hydration",component:"sessionSlice",error_message:e instanceof Error?e.message:String(e)})}t(Fe({user:i,accessToken:r,refreshToken:s,expiresIn:null!=a?a/1e3:null}))},exports.indicatorReducer=Ce,exports.initLogger=T,exports.initializeChatConfig=e=>{A=e.baseUrl,_=e.customHeaders||{},O=e.paymentProvider},exports.isDevMode=()=>C,exports.isTokenAboutToExpire=j,exports.isTokenExpired=V,exports.joinOrgMountBase=(e,t)=>t?`${e}/${encodeURIComponent(t)}/${v}`:`${e}/${v}`,exports.logger=d,exports.logout=ye,exports.parseJwtPayload=z,exports.parseOrgFromJwt=X,exports.readAccessToken=()=>R(),exports.readTokenExpiresAt=D,exports.registerEventListener=function(e,t){return J.on(e,t)},exports.registerLoggerContextProvider=c,exports.registerLoggerSink=u,exports.removeSpecialCharsAndSpaces=e=>e?e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g,"").trim():"",exports.resetLoggerForTests=async function(){n=null,a=null,i.length=0,(await Promise.resolve().then(()=>y)).resetInitLoggerStateForTests()},exports.sanitizeExpiryDate=s,exports.sessionExpired=Se,exports.sessionListenerMiddleware=Oe,exports.sessionReducer=Ae,exports.setAccessTokenReader=e=>{R=e},exports.setCredentials=Te,exports.setIsDev=e=>{C=e},exports.setLastResponseTime=Re,exports.setModuleStorage=function(e){de=e},exports.setNetworkLoggingEnabled=h,exports.setSelectedOrgId=he,exports.setSession=Fe,exports.setTokenExpiresAtReader=e=>{N=e},exports.setTokenRefreshHandler=e=>{I=e},exports.showErrorToast=(e="Please try again")=>$({title:"Error",description:e,variant:"destructive"}),exports.showSuccessToast=(e="Successfully")=>$({title:"Success",description:e,variant:"default"}),exports.showToast=e=>$(e),exports.truncateWordLimit=(e,t)=>{if(!e)return"";const r=e.split(" ");return r.length>t?r.slice(0,t).join(" "):e},exports.updateUser=fe,exports.useBranding=function(){const e=t.useContext(ce);if(!e)throw new Error("useBranding must be used within a BrandingProvider");return e},exports.useNetworkState=()=>{const e=t.useContext(ge),r=t.useCallback(t=>e?e.subscribe(t):()=>{},[e]),s=t.useCallback(()=>e?e.getState():Ee,[e]);return t.useSyncExternalStore(r,s,s)},exports.useStorage=()=>{const e=t.useContext(le);if(!e)throw new Error("useStorage must be called inside a <StorageProvider>. Wrap your app's root with <StorageProvider value={browserLocalStorageAdapter}> (or an RN equivalent).");return e},exports.validateExpiryDate=r,exports.writeOrgToStorage=function(e,t){try{t.setItem(w.SELECTED_ORG_ID,e),t.setItem(w.SELECTED_ORG_NAME,e)}catch{}};
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{createSlice as e,createListenerMiddleware as t,isAnyOf as r}from"@reduxjs/toolkit";import{createContext as s,useContext as n,useCallback as o,useSyncExternalStore as i}from"react";const a=(e,t)=>{if(!e)return"";const r=e.split(" ");return r.length>t?r.slice(0,t).join(" "):e},u=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),c=(e,t=new Date)=>{if(!e)return"";const r=new Date(e);if(isNaN(r.getTime()))return"";const s=t.getTime()-r.getTime(),n=Math.floor(s/6e4),o=Math.floor(s/36e5),i=Math.floor(s/864e5);return n<1?"Just now":n<60?`${n}m ago`:o<24?`${o}h ago`:i<7?`${i}d ago`:new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(r)},l=e=>e?e.split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"",d=e=>e?e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/^(.)/,e=>e.toUpperCase()).split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ").trim():"",g=e=>e?e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g,"").trim():"",p=e=>e.replace(/\D/g,"").slice(0,16).replace(/(.{4})/g,"$1 ").trim(),E=e=>{const t=e.match(/^(\d{2})\/(\d{2})$/);if(!t)return!1;const r=Number(t[1]),s=Number(t[2]);if(r<1||r>12)return!1;const n=new Date,o=n.getFullYear()%100,i=n.getMonth()+1;return!(s<o||s===o&&r<i||r>12)},F=e=>{if(!e)return"";if(!E(e)){const t=e.match(/^(\d{2})\/(\d{2})$/);if(t){const e=Number(t[1]),r=Number(t[2]),s=new Date,n=s.getFullYear()%100,o=s.getMonth()+1;if(r<n||r===n&&e<o||e>12)return""}}return e},m=e=>{const t=e.replace(/\D/g,"").slice(0,4);if(4===t.length){const e=t.slice(0,2)+"/"+t.slice(2);return F(e)}return t.length>=3?`${t.slice(0,2)}/${t.slice(2)}`:t.length>=1?t:""},f=e=>e.replace(/\D/g,"").slice(0,4);function h(e){return Array.isArray(e)&&Array.isArray(e[0])?e.flat():e}const S=(e,t)=>{if(e&&e.trim()){const t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.trim().slice(0,2).toUpperCase()}return t&&t.trim()?t.trim().slice(0,2).toUpperCase():"U"},T=e=>Array.isArray(e.widget)&&e.widget.length>0;function y(e,t="An unexpected error occurred."){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("data"in e){const t=e.data;if(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message)return t.message}}return t}const _={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"};let O=null,A=null;const I=[];function R(e){if(O=e,I.length>0){const t=I.splice(0,I.length);for(const r of t)e.emit(r)}}function N(e){A=e}async function x(){O=null,A=null,I.length=0,(await Promise.resolve().then(()=>H)).resetInitLoggerStateForTests()}function C(e,t){const r=A?function(e){try{return e()??{}}catch{return{}}}(A):{},{message:s,...n}=t,o={...r,...n,level:e,message:s,timestamp:(new Date).toISOString()};O?O.emit(o):(I.length>=200&&I.shift(),I.push(o))}const M={debug(e){C(_.DEBUG,e)},info(e){C(_.INFO,e)},warn(e){C(_.WARN,e)},error(e){C(_.ERROR,e)},flush:()=>O?.flush?.()},D={[_.DEBUG]:0,[_.INFO]:1,[_.WARN]:2,[_.ERROR]:3};function B(e={}){const t=D[e.minLevel??_.DEBUG];return{emit(e){D[e.level]<t||(e.level===_.ERROR?console.error:e.level===_.WARN?console.warn:e.level===_.DEBUG?console.debug:console.info)(e)}}}const v={[_.DEBUG]:5,[_.INFO]:9,[_.WARN]:13,[_.ERROR]:17};function b(e){if(null===e)return"null";const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Error)return JSON.stringify({name:e.name,message:e.message,stack:e.stack});try{return JSON.stringify(e)}catch{return String(e)}}function w(e){const t={};for(const[r,s]of Object.entries(e))void 0!==s&&(t[r]=b(s));return t}let k=!1,P=null,L=!0;function U(e){L=e}function G(e){k||(k=!0,N(function(e){const t={app_name:e.appName,app_version:e.appVersion,environment:e.environment};return()=>({...t,...e.getContext()})}(e)),R(function(e){const t=[B({minLevel:e.consoleMinLevel??(e.isDev?_.DEBUG:_.WARN)})];if(e.otlpEndpoint&&!e.isDev){const r="otel"===(e.logTransport??"otel")?function(e){let t=!1,r=null,s=null;const n=[];function o(){s||(s=async function(){const[t,s,o,i]=await Promise.all([import("@opentelemetry/api-logs"),import("@opentelemetry/sdk-logs"),import("@opentelemetry/exporter-logs-otlp-http"),import("@opentelemetry/resources")]),a=i.resourceFromAttributes(e.resourceAttrs),u=new o.OTLPLogExporter({url:e.endpoint}),c=new s.LoggerProvider({resource:a,processors:[new s.BatchLogRecordProcessor(u)]});t.logs.setGlobalLoggerProvider(c);const l=t.logs.getLogger(e.resourceAttrs["service.name"]??"app");if(r={emit(e){const{level:t,message:r,timestamp:s,...n}=e;l.emit({severityNumber:v[t],severityText:t,body:JSON.stringify(e),attributes:w(n),timestamp:new Date(s)})},async flush(){await c.forceFlush()}},n.length>0){const e=n.splice(0,n.length);for(const t of e)r.emit(t)}}().catch(()=>{n.length=0,r=null,t=!0}))}return{emit(e){t||(r?r.emit(e):(o(),n.length>=200&&n.shift(),n.push(e)))},async flush(){(s||r)&&(o(),await s,r&&await r.flush())}}}({endpoint:e.otlpEndpoint,resourceAttrs:{"service.name":e.appName,"service.version":e.appVersion,"deployment.environment":e.environment}}):function(e){const t=e.maxBatchSize??50,r=e.scheduledDelayMs??5e3,s=e.maxQueueSize??2048,n=e.wrapBatch??(e=>e),o=[];let i=null;function a(){return null!==i&&(clearTimeout(i),i=null),0===o.length||0===(t=o.splice(0,o.length)).length?Promise.resolve():fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n(t)),keepalive:!0}).then(()=>{}).catch(()=>{});var t}return{emit(e){o.length>=s&&o.shift(),o.push(e),o.length>=t?a():null===i&&(i=setTimeout(()=>{i=null,a()},r))},async flush(){await a()}}}({endpoint:e.otlpEndpoint});t.push({emit(e){L&&r.emit(e)},flush:r.flush.bind(r)})}return e.extraSinks?.length&&t.push(...e.extraSinks),1===t.length?t[0]:function(e){return{emit(t){for(const r of e)try{r.emit(t)}catch{}},async flush(){await Promise.all(e.map(e=>e.flush?Promise.resolve(e.flush()).catch(()=>{}):Promise.resolve()))}}}(t)}(e)),!1!==e.flushOnAppHide&&P?.())}const H=Object.freeze(Object.defineProperty({__proto__:null,initLogger:G,registerPlatformFlushAttacher:function(e){P=e},resetInitLoggerStateForTests:function(){k=!1,P=null,L=!0},setNetworkLoggingEnabled:U},Symbol.toStringTag,{value:"Module"}));let K,$="",W={},j=null,V=()=>null,X=()=>null,z=!1;const Y=e=>{$=e.baseUrl,W=e.customHeaders||{},K=e.paymentProvider},J=()=>$,Z=()=>K,q=()=>W,Q=e=>{j=e},ee=()=>j,te=e=>{V=e},re=()=>V(),se=e=>{X=e},ne=()=>X(),oe=e=>{z=e},ie=()=>z,ae=e=>{const t=e.startsWith("/")?e:`/${e}`;return`${$}/api${t}`},ue="chat",ce=(e,t)=>t?`${e}/${encodeURIComponent(t)}/${ue}`:`${e}/${ue}`,le={CONVERSATIONS:()=>ae("/conversations"),CONVERSATION_STREAM:e=>ae(`/conversations/${e}`),CONVERSATION_START:e=>ae(`/conversations/${e}/start`),get TRANSCRIBE(){return ae("/transcribe")},get BRANDING(){return ae("/branding")},get CONFIG(){return ae("/config")},get PROFILE(){return ae("/profile")},get AUTH_ME(){return ae("/auth/me")},get ORGANIZATIONS_EXISTS(){return ae("/organizations/exists")},get DEBUG(){return ae("/debug")},get TOOL_SERVERS(){return ae("/tool-servers")},TOOL_SERVER_AUTH_START:e=>ae(`/tool-servers/${e}/auth/start`),TOOL_SERVER_AUTH_CONNECTION:e=>ae(`/tool-servers/${e}/auth/connection`),get TOOL_SERVERS_SIGN_IN_EXCHANGE(){return ae("/tool-servers/auth/exchange")},get LOG(){return ae("/log")}},de={SSO:"sso"},ge={TOKEN_REFRESH_THRESHOLD_MS:6e5,TOKEN_CLOCK_SKEW_MS:3e4,TOKEN_DEFAULT_EXPIRY_MS:36e5,THINKING_STATE_TIMEOUT_MS:600,MESSAGE_WARNING_TIMEOUT_MS:1e4,TOAST_DURATION_MS:5e3,TOAST_ERROR_DURATION_MS:7e3,INPUT_DEBOUNCE_MS:300,SEARCH_DEBOUNCE_MS:500,CONFIG_TIMEOUT_MS:5e3},pe={ACCESS_TOKEN:"accessToken",REFRESH_TOKEN:"refreshToken",TOKEN_EXPIRES_AT:"tokenExpiresAt",USER:"user",SELECTED_ORG_ID:"selectedOrgId",SELECTED_ORG_NAME:"selectedOrgName",APPEARANCE_MODE_KEY:"1interface_appearance_mode",LOCATION_ENABLED:"1interface_location_enabled",LOCATION_CACHE:"1interface_cached_location",DEBUG_MODE:"1interface_debug_mode",STT_AUTO_SEND:"1interface_stt_auto_send",STT_IMPLEMENTATION:"1interface_stt_implementation",SEND_DIAGNOSTICS:"1interface_send_diagnostics",ACTIVE_CONVERSATION_ID:"1interface_active_conversation_id"},Ee={ONLINE:"online",DEVICE:"device"},Fe=e=>e?`${pe.APPEARANCE_MODE_KEY}:${e}`:pe.APPEARANCE_MODE_KEY,me="https://one-interface-assets.nyc3.cdn.digitaloceanspaces.com/Orb.mp4",fe={ACCESS_TOKEN:"x-access-token",REFRESH_TOKEN:"x-refresh-token"},he={LOGIN:"/auth/login",SIGNUP:"/auth/signup",LOGOUT:"/auth/logout",REFRESH:"/auth/refresh",FORGOT_PASSWORD:"/auth/forgot-password",RESET_PASSWORD:"/auth/reset-password",SSO_START:"/auth/sso/start",SSO_EXCHANGE:"/auth/sso/exchange",ORGANIZATIONS:"/organizations"},Se={EMAIL:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,NON_DIGIT:/\D/g,PHONE_E164:/^\+[1-9]\d{1,14}$/},Te={NAME_MAX_LENGTH:64,PHONE_MIN_LENGTH:8,PHONE_MAX_LENGTH:16};let ye=!0;const _e=async e=>{const t=await e.getItem(pe.SEND_DIAGNOSTICS);ye=null===t||"true"===t},Oe=()=>ye,Ae=3,Ie=500,Re=e=>{const t=e?.status;return"FETCH_ERROR"===t||"TIMEOUT_ERROR"===t||("number"==typeof t?t>=500:(M.warn({message:"unknown error shape; treating as transient",api_name:"auth-refresh",error_message:e instanceof Error?e.message:String(e)}),!0))};function Ne(e){const{performRefresh:t,isTransient:r=Re,maxAttempts:s=Ae,backoffBaseMs:n=Ie}=e;let o=null;return function(){return o||(o=(async()=>{for(let e=0;e<s;e++)try{return await t()}catch(t){if(!r(t))return null;if(e===s-1)break;const o=n*2**e+250*Math.random();await new Promise(e=>setTimeout(e,o))}return null})().finally(()=>{o=null}),o)}}const xe="bridge-toast";function Ce(e){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent(xe,{detail:e}))}const Me=e=>Ce(e),De=(e="Please try again")=>Ce({title:"Error",description:e,variant:"destructive"}),Be=(e="Successfully")=>Ce({title:"Success",description:e,variant:"default"}),ve=xe,be=e=>!!e&&Date.now()>=e-ge.TOKEN_CLOCK_SKEW_MS,we=e=>!e||Date.now()>=e-ge.TOKEN_REFRESH_THRESHOLD_MS,ke=async()=>we(ne())?await(ee()?.())??null:null,Pe=e=>e?Math.max(0,e-Date.now()):0,Le=e=>e?Math.max(0,e-ge.TOKEN_REFRESH_THRESHOLD_MS-Date.now()):0,Ue=e=>{const t=Math.floor(e/6e4),r=Math.floor(e%6e4/1e3);return t>0?`${t}m ${r}s`:`${r}s`};function Ge(e){const t=e.headers.get(fe.ACCESS_TOKEN),r=e.headers.get(fe.REFRESH_TOKEN);if(!t)throw new Error(`Missing ${fe.ACCESS_TOKEN} header in response`);if(!r)throw new Error(`Missing ${fe.REFRESH_TOKEN} header in response`);return{accessToken:t,refreshToken:r}}function He(e){if(!e)return null;const t=e.split(".");if(3!==t.length)return null;try{const e=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=e+"=".repeat((4-e.length%4)%4),s=atob(r),n=JSON.parse(s);return n&&"object"==typeof n&&!Array.isArray(n)?n:null}catch{return null}}function Ke(e){const t=He(e),r=t?.org_id;return"string"==typeof r&&r.length>0?r:null}function $e(e,t){try{const r=t.getItem(pe.SELECTED_ORG_ID);if(r&&r!==e)return"storage";const s=Ke(t.getItem(pe.ACCESS_TOKEN));return s&&s!==e?"jwt":null}catch{return null}}function We(e){try{e.removeItem(pe.ACCESS_TOKEN),e.removeItem(pe.REFRESH_TOKEN),e.removeItem(pe.TOKEN_EXPIRES_AT),e.removeItem(pe.USER)}catch{}}function je(e,t){try{t.setItem(pe.SELECTED_ORG_ID,e),t.setItem(pe.SELECTED_ORG_NAME,e)}catch{}}class Ve{static instance;events={};constructor(){}static getInstance(){return Ve.instance||(Ve.instance=new Ve),Ve.instance}on(e,t,r){const s="function"==typeof t?t:r;return this.events[e]||(this.events[e]=[]),this.events[e].push(s),()=>{this.off(e,s)}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(e=>e!==t))}emit(e,t){this.events[e]&&this.events[e].forEach(r=>{try{r(t)}catch(t){M.error({message:`Error in event handler for "${e}"`,api_name:"event-emitter",event:e,error_message:t instanceof Error?t.message:String(t)})}})}clear(e){e?delete this.events[e]:this.events={}}}const Xe=Ve.getInstance();function ze(e,t){return Xe.on(e,t)}const Ye={LIGHT:"light",DARK:"dark",SYSTEM:"system"},Je=[Ye.LIGHT,Ye.DARK,Ye.SYSTEM],Ze={FOREGROUND:"foreground",BACKGROUND:"background"},qe={PILL:"pill",ROUNDED:"rounded",SHARP:"sharp"},Qe={bgColor:"linear-gradient(281.8deg, #061522 6.7%, #101F2F 59.64%, #3C3B4F 76.85%, #5D4C63 88.46%, #755770 99.24%)",inputBgColor:"#222D34",sidebarBg:"#0F1419",sidebarBorderColor:"#8F8F8F",widgetBg:"#222D34",settingsGroupBg:"#272626",inputBorderStyle:"solid",inputBorderColor:"#FFFFFF80",inputBorderWidth:"1px",inputBorderOpacity:50,widgetBorderStyle:"solid",widgetBorderColor:"#FFFFFF1A",widgetBorderWidth:"1px",widgetBorderOpacity:10,placeholderColor:"#8F8F8F",primaryText:"#FFFFFF",secondaryText:"#AFAFAF",tertiaryText:"#8F8F8F",userMsgBg:"#90629F",userMsgText:"#FFFFFF",userMsgBorderStyle:"none",userMsgBorderColor:"#FFFFFFFF",userMsgBorderWidth:"1px",userMsgBorderOpacity:100,sideMenuHeadings:"#FFFFFF",sideMenuText:"#AFAFAF",sideMenuIcon:"#8F8F8F",sideMenuProfile:"#FFFFFF",statusPrimary:{solid:"#90629F",background:"#90629F",text:"#FFFFFF"},statusSecondary:{solid:"#5D5D5D",background:"#F3F3F3",text:"#0D0D0D"},statusSuccess:{solid:"#00A240",background:"#D9F4E4",text:"#FFFFFF"},statusDanger:{solid:"#E02E2A",background:"#FFD9D9",text:"#FFFFFF"},statusWarning:{solid:"#E25507",background:"#FFE7D9",text:"#FFFFFF"},statusInfo:{solid:"#0285FF",background:"#E5F3FF",text:"#FFFFFF"},statusDiscovery:{solid:"#924FF7",background:"#EFE5FE",text:"#FFFFFF"},switchCheckedColor:"#90629F",switchUncheckedColor:"#222D34",fontFamily:"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif",fontFamilyMono:'"SF Mono", ui-monospace, monospace',fontSize:14,borderRadius:16,cornerRadiusMode:qe.PILL,chatInputPlaceholder:"Type anything..."},et={bgColor:"linear-gradient(281.8deg, #EEF2FF 6.7%, #E2E8FD 59.64%, #E8DFF4 76.85%, #F4DBE6 88.46%, #FFE1D0 99.24%)",inputBgColor:"#F4F4F5",sidebarBg:"#FFFFFF",sidebarBorderColor:"#9B9B9B",widgetBg:"#FFFFFF",settingsGroupBg:"#1A1A1A10",inputBorderStyle:"solid",inputBorderColor:"#0000001A",inputBorderWidth:"1px",inputBorderOpacity:10,widgetBorderStyle:"solid",widgetBorderColor:"#0000001A",widgetBorderWidth:"1px",widgetBorderOpacity:10,placeholderColor:"#9B9B9B",primaryText:"#1A1A1A",secondaryText:"#6B6B6B",tertiaryText:"#9B9B9B",userMsgBg:"#90629F",userMsgText:"#FFFFFF",userMsgBorderStyle:"none",userMsgBorderColor:"#000000FF",userMsgBorderWidth:"1px",userMsgBorderOpacity:100,sideMenuHeadings:"#1A1A1A",sideMenuText:"#6B6B6B",sideMenuIcon:"#9B9B9B",sideMenuProfile:"#1A1A1A",statusPrimary:{solid:"#90629F",background:"#90629F",text:"#FFFFFF"},statusSecondary:{solid:"#5D5D5D",background:"#F3F3F3",text:"#0D0D0D"},statusSuccess:{solid:"#00A240",background:"#D9F4E4",text:"#FFFFFF"},statusDanger:{solid:"#E02E2A",background:"#FFD9D9",text:"#FFFFFF"},statusWarning:{solid:"#E25507",background:"#FFE7D9",text:"#FFFFFF"},statusInfo:{solid:"#0285FF",background:"#E5F3FF",text:"#FFFFFF"},statusDiscovery:{solid:"#924FF7",background:"#EFE5FE",text:"#FFFFFF"},switchCheckedColor:"#90629F",switchUncheckedColor:"#F4F4F5",fontFamily:"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif",fontFamilyMono:'"SF Mono", ui-monospace, monospace',fontSize:14,borderRadius:16,cornerRadiusMode:qe.PILL,chatInputPlaceholder:"Type anything..."};function tt(e){return e===Ye.LIGHT?et:Qe}const rt=Qe;function st(e,t){const r=e.replace("#","");let s;s=3===r.length?r.split("").map(e=>e+e).join(""):6===r.length?r:"000000";const n=Math.max(0,Math.min(100,t));return`#${s}${Math.round(n/100*255).toString(16).padStart(2,"0")}`.toUpperCase()}function nt(e,t){if(!e)return t.fontFamily;switch(e){case"Inter":return"'Inter', sans-serif";case"System":return"system-ui, -apple-system, sans-serif";default:return"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif"}}function ot(e,t){return e?`"${e}", ui-monospace, monospace`:t.fontFamilyMono}function it(e,t){if(!e)return t.borderRadius;switch(e){case"none":return 0;case"sm":return 8;case"md":return 12;case"pill":return 16;default:const r=parseInt(e,10);return isNaN(r)?t.borderRadius:r}}function at(e){switch(e){case"pill":return qe.PILL;case"none":return qe.SHARP;default:return 0===parseInt(e??"",10)?qe.SHARP:qe.ROUNDED}}function ut(e,t,r=Ye.DARK){const s=tt(r);if(!e||!t)return s;const n=t.surface?.chatInput?.border||t.surface?.input?.border,o=t.surface?.userMessage?.border,i=t.surface?.widget?.border;return{bgColor:t.surface?.chat?.background||s.bgColor,inputBgColor:t.surface?.chatInput?.background||t.surface?.input?.background||s.inputBgColor,sidebarBg:t.surface?.sideMenu?.background||s.sidebarBg,sidebarBorderColor:t.surface?.sideMenu?.iconColor||t.surface?.sideMenu?.icons||s.sidebarBorderColor,widgetBg:t.surface?.widget?.background||s.widgetBg,settingsGroupBg:t.surface?.settings?.groupBackground||s.settingsGroupBg,inputBorderStyle:n?.style||s.inputBorderStyle,inputBorderColor:n?.color?st(n.color,n.opacity||100):s.inputBorderColor,inputBorderWidth:n?.width||s.inputBorderWidth,inputBorderOpacity:n?.opacity||100,widgetBorderStyle:i?.style||s.widgetBorderStyle,widgetBorderColor:i?.color?st(i.color,i.opacity||100):s.widgetBorderColor,widgetBorderWidth:i?.width||s.widgetBorderWidth,widgetBorderOpacity:i?.opacity??s.widgetBorderOpacity,placeholderColor:t.surface?.chatInput?.placeholderColor||t.surface?.input?.placeholderColor||s.placeholderColor,primaryText:t.text?.primary||s.primaryText,secondaryText:t.text?.secondary||s.secondaryText,tertiaryText:t.text?.tertiary||s.tertiaryText,userMsgBg:t.surface?.userMessage?.background||s.userMsgBg,userMsgText:t.surface?.userMessage?.textColor||s.userMsgText,userMsgBorderStyle:o?.style||s.userMsgBorderStyle,userMsgBorderColor:o?.color?st(o.color,o.opacity||100):s.userMsgBorderColor,userMsgBorderWidth:o?.width||s.userMsgBorderWidth,userMsgBorderOpacity:o?.opacity||0,sideMenuHeadings:t.surface?.sideMenu?.headingsColor||t.surface?.sideMenu?.headings||s.sideMenuHeadings,sideMenuText:t.surface?.sideMenu?.textContentColor||t.surface?.sideMenu?.textContent||s.sideMenuText,sideMenuIcon:t.surface?.sideMenu?.iconColor||t.surface?.sideMenu?.icons||s.sideMenuIcon,sideMenuProfile:t.surface?.sideMenu?.profileTextColor||t.surface?.sideMenu?.textProfile||s.sideMenuProfile,statusPrimary:{solid:t.status?.primary?.solid||s.statusPrimary.solid,background:t.status?.primary?.background||s.statusPrimary.background,text:t.status?.primary?.text||s.statusPrimary.text},statusSecondary:{solid:t.status?.secondary?.solid||s.statusSecondary.solid,background:t.status?.secondary?.background||s.statusSecondary.background,text:t.status?.secondary?.text||s.statusSecondary.text},statusSuccess:{solid:t.status?.success?.solid||s.statusSuccess.solid,background:t.status?.success?.background||s.statusSuccess.background,text:t.status?.success?.text||s.statusSuccess.text},statusDanger:{solid:t.status?.danger?.solid||s.statusDanger.solid,background:t.status?.danger?.background||s.statusDanger.background,text:t.status?.danger?.text||s.statusDanger.text},statusWarning:{solid:t.status?.warning?.solid||s.statusWarning.solid,background:t.status?.warning?.background||s.statusWarning.background,text:t.status?.warning?.text||s.statusWarning.text},statusInfo:{solid:t.status?.info?.solid||s.statusInfo.solid,background:t.status?.info?.background||s.statusInfo.background,text:t.status?.info?.text||s.statusInfo.text},statusDiscovery:{solid:t.status?.discovery?.solid||s.statusDiscovery.solid,background:t.status?.discovery?.background||s.statusDiscovery.background,text:t.status?.discovery?.text||s.statusDiscovery.text},switchCheckedColor:t.status?.primary?.solid||s.switchCheckedColor,switchUncheckedColor:t.surface?.chatInput?.background||s.switchUncheckedColor,fontFamily:nt(e.typography?.fontFamily,s),fontFamilyMono:ot(e.typography?.fontFamilyMono,s),fontSize:14,borderRadius:it(e.cornerRadius,s),cornerRadiusMode:at(e.cornerRadius),chatInputPlaceholder:e.startScreen.inputPlaceholder}}function ct(e,t){let r=e.trim().replace(/^#/,"");if(3!==r.length&&4!==r.length||(r=r.split("").map(e=>e+e).join("")),!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(r))return e;const s=parseInt(r.slice(0,2),16),n=parseInt(r.slice(2,4),16),o=parseInt(r.slice(4,6),16),i=8===r.length?parseInt(r.slice(6,8),16)/255:1;return`rgba(${s}, ${n}, ${o}, ${Math.round(i*t*1e3)/1e3})`}const lt=s(void 0);function dt(){const e=n(lt);if(!e)throw new Error("useBranding must be used within a BrandingProvider");return e}const gt=s(null),pt=()=>{const e=n(gt);if(!e)throw new Error("useStorage must be called inside a <StorageProvider>. Wrap your app's root with <StorageProvider value={browserLocalStorageAdapter}> (or an RN equivalent).");return e};let Et=null;function Ft(e){Et=e}const mt=()=>Et,ft=s(null),ht={isConnected:!0,isInternetReachable:!0},St=()=>{const e=n(ft),t=o(t=>e?e.subscribe(t):()=>{},[e]),r=o(()=>e?e.getState():ht,[e]);return i(t,r,r)},Tt=e({name:"auth",initialState:{user:null,accessToken:null,refreshToken:null,tokenExpiresAt:null,selectedOrgId:null,isAuthenticated:!1,isLoading:!1},reducers:{setSession:(e,t)=>{const{user:r,accessToken:s,refreshToken:n,expiresIn:o}=t.payload;void 0!==r&&(e.user=r),void 0!==s&&(e.accessToken=s),void 0!==n&&(e.refreshToken=n),void 0!==o?e.tokenExpiresAt=null===o?null:1e3*o:s&&(e.tokenExpiresAt=Date.now()+ge.TOKEN_DEFAULT_EXPIRY_MS),e.isAuthenticated=Boolean(e.accessToken),e.isLoading=!1},updateUser:(e,t)=>{e.user={...e.user||{},...t.payload}},clearSession:e=>{e.user=null,e.accessToken=null,e.refreshToken=null,e.tokenExpiresAt=null,e.isAuthenticated=!1,e.isLoading=!1},sessionExpired:e=>{e.user=null,e.accessToken=null,e.refreshToken=null,e.tokenExpiresAt=null,e.isAuthenticated=!1,e.isLoading=!1},setSelectedOrgId:(e,t)=>{e.selectedOrgId=t.payload??null}}}),{setSession:yt,updateUser:_t,clearSession:Ot,sessionExpired:At,setSelectedOrgId:It}=Tt.actions,Rt=yt,Nt=Ot,xt=e=>async t=>{const[r,s,n,o]=await Promise.all([e.getItem(pe.ACCESS_TOKEN),e.getItem(pe.REFRESH_TOKEN),e.getItem(pe.TOKEN_EXPIRES_AT),e.getItem(pe.USER)]),i=n?parseInt(n,10):null;if((!r||!i||be(i))&&!s)return void(r&&await Promise.all([e.removeItem(pe.ACCESS_TOKEN),e.removeItem(pe.REFRESH_TOKEN),e.removeItem(pe.TOKEN_EXPIRES_AT),e.removeItem(pe.USER)]));let a=null;if(o)try{a=JSON.parse(o)}catch(e){M.error({message:"Failed to parse stored user during session hydration",component:"sessionSlice",error_message:e instanceof Error?e.message:String(e)})}t(yt({user:a,accessToken:r,refreshToken:s,expiresIn:null!=i?i/1e3:null}))},Ct=t();Ct.startListening({matcher:r(yt,_t,Ot,At),effect:async(e,t)=>{const r=mt();if(!r)return;const{auth:s}=t.getState(),n=[];n.push(s.accessToken?r.setItem(pe.ACCESS_TOKEN,s.accessToken):r.removeItem(pe.ACCESS_TOKEN)),n.push(s.refreshToken?r.setItem(pe.REFRESH_TOKEN,s.refreshToken):r.removeItem(pe.REFRESH_TOKEN)),n.push(null!=s.tokenExpiresAt?r.setItem(pe.TOKEN_EXPIRES_AT,String(s.tokenExpiresAt)):r.removeItem(pe.TOKEN_EXPIRES_AT)),n.push(s.user?r.setItem(pe.USER,JSON.stringify(s.user)):r.removeItem(pe.USER)),(Ot.match(e)||At.match(e))&&n.push(r.removeItem(pe.LOCATION_CACHE),r.removeItem(pe.DEBUG_MODE),r.removeItem(pe.APPEARANCE_MODE_KEY),r.removeItem(pe.LOCATION_ENABLED),r.removeItem(pe.STT_AUTO_SEND),r.removeItem(pe.STT_IMPLEMENTATION),r.removeItem(pe.SEND_DIAGNOSTICS),r.removeItem(pe.ACTIVE_CONVERSATION_ID)),await Promise.all(n)}});const Mt=Tt.reducer,Dt={lastResponseTime:null},Bt=e({name:"indicator",initialState:Dt,reducers:{setLastResponseTime(e,t){e.lastResponseTime=t.payload},clearLastResponseTime(e){e.lastResponseTime=null}},extraReducers:e=>{e.addMatcher(r(Ot,At),()=>Dt)}}),{setLastResponseTime:vt,clearLastResponseTime:bt}=Bt.actions,wt=Bt.reducer;function kt(e,t){switch(e.kind){case"status_update":return t.setStatusText(e.statusText),t.setIsAgentWorking(!0),void t.onStatusActive?.(e.statusText);case"widget":return void t.pushWidget(e.widget,e.messageId);case"payment":return void t.onPayment(e.payment);case"sign_in":return void t.onSignIn?.(e.signIn);case"error":return void t.onError(e.error);case"text":return void t.appendStreamText(e.text,e.messageId);case"conversation_title":return void t.onConversationTitle?.(e.title);default:return}}const Pt={GOOGLE:"google",APPLE:"apple",MICROSOFT:"microsoft"},Lt={KEEP:"keep",FINALIZE:"finalize",CANCEL:"cancel"};function Ut(e){if(e)return"moyasar"===e.provider?e.config?.given_id:e.payment_id}export{le as API_ENDPOINTS,Ye as APPEARANCE_MODES,Je as APPEARANCE_MODE_VALUES,fe as AUTH_HEADERS,he as AUTH_PATHS,ve as BRIDGE_TOAST_EVENT_NAME,lt as BrandingContext,qe as CORNER_RADIUS_MODES,Ve as EventEmitter,de as FEATURE_FLAGS,Pt as IDP_HINTS,Lt as INDICATOR_TIMER_ACTIONS,_ as LOG_LEVELS,ft as NetworkContext,Ze as ORB_POSITIONS,me as ORB_URL,ue as ORG_MOUNT_SUFFIX,Se as PATTERNS,Te as PROFILE_LIMITS,pe as STORAGE_KEYS,Ee as STT_IMPLEMENTATIONS,gt as StorageContext,ge as TIMING,ut as brandingToThemeStyles,l as capitalizeFirst,We as clearAuthTokens,bt as clearLastResponseTime,Ot as clearSession,Ne as createTokenRefresher,rt as defaultChatThemeStyles,Qe as defaultDarkThemeStyles,Re as defaultIsTransient,et as defaultLightThemeStyles,$e as detectOrgSwitch,ke as ensureFreshToken,Xe as eventEmitter,Ge as extractTokens,f as formatCVC,d as formatCamelCaseToTitle,p as formatCardNumber,m as formatExpiryDate,Ue as formatTimeRemaining,c as formatTimestamp,u as generateUniqueId,ae as getApiUrl,Fe as getAppearanceModeStorageKey,h as getArrayOfObjects,J as getBaseUrl,q as getCustomHeaders,tt as getDefaultThemeStyles,y as getErrorMessage,S as getInitials,Ut as getPaymentId,Z as getPaymentProviderHint,Oe as getSendDiagnostics,mt as getStorageRef,Pe as getTimeUntilExpiry,Le as getTimeUntilRefresh,ee as getTokenRefreshHandler,kt as handleSharedEvent,T as hasWidgets,ct as hexToRgba,_e as hydrateAppBoot,xt as hydrateSession,wt as indicatorReducer,G as initLogger,Y as initializeChatConfig,ie as isDevMode,we as isTokenAboutToExpire,be as isTokenExpired,ce as joinOrgMountBase,M as logger,Nt as logout,He as parseJwtPayload,Ke as parseOrgFromJwt,re as readAccessToken,ne as readTokenExpiresAt,ze as registerEventListener,N as registerLoggerContextProvider,R as registerLoggerSink,g as removeSpecialCharsAndSpaces,x as resetLoggerForTests,F as sanitizeExpiryDate,At as sessionExpired,Ct as sessionListenerMiddleware,Mt as sessionReducer,te as setAccessTokenReader,Rt as setCredentials,oe as setIsDev,vt as setLastResponseTime,Ft as setModuleStorage,U as setNetworkLoggingEnabled,It as setSelectedOrgId,yt as setSession,se as setTokenExpiresAtReader,Q as setTokenRefreshHandler,De as showErrorToast,Be as showSuccessToast,Me as showToast,a as truncateWordLimit,_t as updateUser,dt as useBranding,St as useNetworkState,pt as useStorage,E as validateExpiryDate,je as writeOrgToStorage};
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@1interface/shared-core",
3
+ "version": "0.1.0",
4
+ "license": "UNLICENSED",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/aiatcore/1interface-chat.git",
23
+ "directory": "packages/shared-core"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "dependencies": {
29
+ "@opentelemetry/api-logs": "^0.218.0",
30
+ "@opentelemetry/exporter-logs-otlp-http": "^0.218.0",
31
+ "@opentelemetry/resources": "^2.7.1",
32
+ "@opentelemetry/sdk-logs": "^0.218.0"
33
+ },
34
+ "peerDependencies": {
35
+ "@reduxjs/toolkit": "^2.0.0",
36
+ "react": "^18.0.0 || ^19.0.0",
37
+ "react-dom": "^18.0.0 || ^19.0.0",
38
+ "react-redux": "^9.0.0",
39
+ "react-native": ">=0.73.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "react-native": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "devDependencies": {
47
+ "@rollup/plugin-terser": "^1.0.0",
48
+ "@testing-library/jest-dom": "^6.9.1",
49
+ "@testing-library/react": "^16.3.2",
50
+ "@types/node": "^24.12.4",
51
+ "@types/react": "^19.2.15",
52
+ "@types/react-dom": "^19.2.3",
53
+ "@vitejs/plugin-react": "5.1.1",
54
+ "@vitest/ui": "4.1.0",
55
+ "jsdom": "^27.4.0",
56
+ "terser": "5.46.1",
57
+ "typescript": "~5.9.3",
58
+ "vite": "7.3.2",
59
+ "vite-plugin-dts": "^4.5.4",
60
+ "vitest": "4.1.0"
61
+ },
62
+ "scripts": {
63
+ "build": "vite build",
64
+ "dev": "vite build --watch",
65
+ "test": "vitest",
66
+ "test:ui": "vitest --ui",
67
+ "postinstall": "rm -rf node_modules/react node_modules/react-dom 2>/dev/null || true"
68
+ }
69
+ }