@retrivora-ai/rag-engine 2.3.5 → 2.3.6

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 (36) hide show
  1. package/dist/{BatchProcessor-CQDtlggz.d.ts → BatchProcessor-ByBl-1MA.d.ts} +81 -3
  2. package/dist/{BatchProcessor-tVzb9CdE.d.mts → BatchProcessor-Dfn23VAd.d.mts} +81 -3
  3. package/dist/{ILLMProvider-CcJ5N6XD.d.mts → ILLMProvider-B8TAVx3j.d.mts} +63 -1
  4. package/dist/{ILLMProvider-CcJ5N6XD.d.ts → ILLMProvider-B8TAVx3j.d.ts} +63 -1
  5. package/dist/handlers/index.d.mts +2 -2
  6. package/dist/handlers/index.d.ts +2 -2
  7. package/dist/handlers/index.js +373 -155
  8. package/dist/handlers/index.mjs +373 -155
  9. package/dist/{index-BwmyPJHp.d.ts → index-ejOWsaqb.d.ts} +1 -1
  10. package/dist/{index-CL-zF6bD.d.mts → index-xxQOFx-u.d.mts} +1 -1
  11. package/dist/index.css +9 -0
  12. package/dist/index.d.mts +19 -5
  13. package/dist/index.d.ts +19 -5
  14. package/dist/index.js +636 -200
  15. package/dist/index.mjs +676 -245
  16. package/dist/server.d.mts +6 -6
  17. package/dist/server.d.ts +6 -6
  18. package/dist/server.js +413 -166
  19. package/dist/server.mjs +409 -166
  20. package/package.json +1 -1
  21. package/src/components/ChatWidget.tsx +44 -19
  22. package/src/components/ChatWindow.tsx +30 -14
  23. package/src/components/ConfigProvider.tsx +86 -6
  24. package/src/components/DocumentUpload.tsx +8 -2
  25. package/src/config/RagConfig.ts +4 -0
  26. package/src/core/ConfigFetcher.ts +10 -1
  27. package/src/core/ConfigResolver.ts +1 -0
  28. package/src/core/LicenseValidator.ts +21 -12
  29. package/src/core/LicenseVerifier.ts +0 -4
  30. package/src/core/ProjectSettings.ts +247 -0
  31. package/src/handlers/index.ts +61 -5
  32. package/src/hooks/useProjectSettings.ts +105 -0
  33. package/src/index.css +9 -0
  34. package/src/index.ts +28 -0
  35. package/src/server.ts +23 -1
  36. package/src/types/props.ts +14 -2
@@ -0,0 +1,247 @@
1
+ import type { UIConfig } from '../config/RagConfig';
2
+
3
+ export type WidgetPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
4
+ export type ThemeMode = 'light' | 'dark' | 'system';
5
+ export type AuthMode = 'public' | 'anonymous' | 'jwt' | 'oauth' | 'okta' | 'auth0' | 'supabase' | 'firebase' | 'sso' | 'custom_token';
6
+
7
+ export interface ProjectBrandingSettings {
8
+ companyName: string;
9
+ botName: string;
10
+ welcomeMessage: string;
11
+ primaryColor: string;
12
+ secondaryColor: string;
13
+ fontFamily: string;
14
+ borderRadius: number;
15
+ logoUrl: string;
16
+ avatarUrl: string;
17
+ customCss: string;
18
+ }
19
+
20
+ export interface ProjectAiSettings {
21
+ defaultModel: string;
22
+ embeddingModel: string;
23
+ systemPrompt: string;
24
+ memoryEnabled: boolean;
25
+ multiModelEnabled: boolean;
26
+ citationsEnabled: boolean;
27
+ fileUploadEnabled: boolean;
28
+ }
29
+
30
+ export interface ProjectAuthSettings {
31
+ mode: AuthMode;
32
+ allowedOrigins: string[];
33
+ requireVerifiedEmail: boolean;
34
+ sessionTtlMinutes: number;
35
+ }
36
+
37
+ export interface ProjectWidgetSettings {
38
+ position: WidgetPosition;
39
+ theme: ThemeMode;
40
+ lazyLoad: boolean;
41
+ autoReconnect: boolean;
42
+ persistConversations: boolean;
43
+ showRetrivoraBranding: boolean;
44
+ }
45
+
46
+ export interface ProjectTelemetrySettings {
47
+ enabled: boolean;
48
+ collectBrowser: boolean;
49
+ collectCountry: boolean;
50
+ redactPii: boolean;
51
+ retentionDays: number;
52
+ }
53
+
54
+ export interface ProjectChatSettings {
55
+ projectId: string;
56
+ branding: ProjectBrandingSettings;
57
+ ai: ProjectAiSettings;
58
+ auth: ProjectAuthSettings;
59
+ widget: ProjectWidgetSettings;
60
+ telemetry: ProjectTelemetrySettings;
61
+ lifecycleHooks: string[];
62
+ conversationFeatures: string[];
63
+ updatedAt?: string;
64
+ }
65
+
66
+ export const DEFAULT_LIFECYCLE_HOOKS = [
67
+ 'beforeInitialize',
68
+ 'afterInitialize',
69
+ 'beforeSend',
70
+ 'afterResponse',
71
+ 'onMessage',
72
+ 'onCitationClick',
73
+ 'onFeedback',
74
+ 'onError',
75
+ 'onReconnect',
76
+ 'onFileUpload',
77
+ ];
78
+
79
+ export const DEFAULT_CONVERSATION_FEATURES = [
80
+ 'History',
81
+ 'Resume',
82
+ 'Search',
83
+ 'Export',
84
+ 'Rename',
85
+ 'Delete',
86
+ 'Tags',
87
+ 'Pinned',
88
+ 'Unread',
89
+ 'Ratings',
90
+ ];
91
+
92
+ export function createDefaultProjectSettings(projectId: string): ProjectChatSettings {
93
+ return {
94
+ projectId,
95
+ branding: {
96
+ companyName: 'Retrivora AI',
97
+ botName: 'Retrivora Assistant',
98
+ welcomeMessage: 'Hi, I can help you search your knowledge base.',
99
+ primaryColor: '#6366f1',
100
+ secondaryColor: '#8b5cf6',
101
+ fontFamily: 'Inter',
102
+ borderRadius: 14,
103
+ logoUrl: '',
104
+ avatarUrl: '',
105
+ customCss: '',
106
+ },
107
+ ai: {
108
+ defaultModel: 'llama-3.1-8b-instant',
109
+ embeddingModel: 'text-embedding-3-small',
110
+ systemPrompt: 'Answer using the connected knowledge base. Cite sources when available.',
111
+ memoryEnabled: true,
112
+ multiModelEnabled: true,
113
+ citationsEnabled: true,
114
+ fileUploadEnabled: true,
115
+ },
116
+ auth: {
117
+ mode: 'public',
118
+ allowedOrigins: [],
119
+ requireVerifiedEmail: false,
120
+ sessionTtlMinutes: 1440,
121
+ },
122
+ widget: {
123
+ position: 'bottom-right',
124
+ theme: 'light',
125
+ lazyLoad: true,
126
+ autoReconnect: true,
127
+ persistConversations: true,
128
+ showRetrivoraBranding: false,
129
+ },
130
+ telemetry: {
131
+ enabled: true,
132
+ collectBrowser: true,
133
+ collectCountry: false,
134
+ redactPii: true,
135
+ retentionDays: 30,
136
+ },
137
+ lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
138
+ conversationFeatures: DEFAULT_CONVERSATION_FEATURES,
139
+ };
140
+ }
141
+
142
+ function cleanString(value: unknown, fallback: string, maxLength = 2000) {
143
+ if (typeof value !== 'string') return fallback;
144
+ return value.trim().slice(0, maxLength);
145
+ }
146
+
147
+ function cleanBoolean(value: unknown, fallback: boolean) {
148
+ return typeof value === 'boolean' ? value : fallback;
149
+ }
150
+
151
+ function cleanNumber(value: unknown, fallback: number, min: number, max: number) {
152
+ const num = typeof value === 'number' ? value : Number(value);
153
+ if (!Number.isFinite(num)) return fallback;
154
+ return Math.min(Math.max(Math.round(num), min), max);
155
+ }
156
+
157
+ function cleanEnum<T extends string>(value: unknown, fallback: T, allowed: readonly T[]) {
158
+ return typeof value === 'string' && allowed.includes(value as T) ? value as T : fallback;
159
+ }
160
+
161
+ function cleanStringList(value: unknown, fallback: string[], maxItems = 20) {
162
+ if (!Array.isArray(value)) return fallback;
163
+ const cleaned = value
164
+ .filter((item): item is string => typeof item === 'string')
165
+ .map((item) => item.trim())
166
+ .filter(Boolean)
167
+ .slice(0, maxItems);
168
+ return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
169
+ }
170
+
171
+ export function normalizeProjectSettings(projectId: string, input: Partial<ProjectChatSettings> | null | undefined): ProjectChatSettings {
172
+ const defaults = createDefaultProjectSettings(projectId);
173
+ const branding: Partial<ProjectBrandingSettings> = input?.branding || {};
174
+ const ai: Partial<ProjectAiSettings> = input?.ai || {};
175
+ const auth: Partial<ProjectAuthSettings> = input?.auth || {};
176
+ const widget: Partial<ProjectWidgetSettings> = input?.widget || {};
177
+ const telemetry: Partial<ProjectTelemetrySettings> = input?.telemetry || {};
178
+
179
+ return {
180
+ projectId,
181
+ branding: {
182
+ companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
183
+ botName: cleanString(branding.botName, defaults.branding.botName, 120),
184
+ welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
185
+ primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
186
+ secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
187
+ fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
188
+ borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
189
+ logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
190
+ avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
191
+ customCss: cleanString(branding.customCss, defaults.branding.customCss, 5000),
192
+ },
193
+ ai: {
194
+ defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
195
+ embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
196
+ systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5000),
197
+ memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
198
+ multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
199
+ citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
200
+ fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled),
201
+ },
202
+ auth: {
203
+ mode: cleanEnum<AuthMode>(auth.mode, defaults.auth.mode, ['public', 'anonymous', 'jwt', 'oauth', 'okta', 'auth0', 'supabase', 'firebase', 'sso', 'custom_token']),
204
+ allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
205
+ requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
206
+ sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200),
207
+ },
208
+ widget: {
209
+ position: cleanEnum<WidgetPosition>(widget.position, defaults.widget.position, ['bottom-right', 'bottom-left', 'top-right', 'top-left']),
210
+ theme: cleanEnum<ThemeMode>(widget.theme, defaults.widget.theme, ['light', 'dark', 'system']),
211
+ lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
212
+ autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
213
+ persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
214
+ showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding),
215
+ },
216
+ telemetry: {
217
+ enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
218
+ collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
219
+ collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
220
+ redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
221
+ retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365),
222
+ },
223
+ lifecycleHooks: cleanStringList(input?.lifecycleHooks, defaults.lifecycleHooks, 30),
224
+ conversationFeatures: cleanStringList(input?.conversationFeatures, defaults.conversationFeatures, 30),
225
+ updatedAt: input?.updatedAt,
226
+ };
227
+ }
228
+
229
+ export function projectSettingsToUiConfig(settings: ProjectChatSettings): Partial<UIConfig> {
230
+ return {
231
+ title: settings.branding.botName,
232
+ subtitle: settings.branding.companyName,
233
+ primaryColor: settings.branding.primaryColor,
234
+ accentColor: settings.branding.secondaryColor,
235
+ logoUrl: settings.branding.logoUrl || settings.branding.avatarUrl,
236
+ welcomeMessage: settings.branding.welcomeMessage,
237
+ poweredBy: settings.widget.showRetrivoraBranding ? 'Retrivora AI' : '',
238
+ allowUpload: settings.ai.fileUploadEnabled,
239
+ borderRadius: settings.branding.borderRadius <= 4
240
+ ? 'sm'
241
+ : settings.branding.borderRadius <= 8
242
+ ? 'md'
243
+ : settings.branding.borderRadius <= 16
244
+ ? 'xl'
245
+ : 'full',
246
+ };
247
+ }
@@ -240,6 +240,48 @@ function enforceLicense(
240
240
  }
241
241
  }
242
242
 
243
+ function getAllowedNamespaces(projectId: string): Set<string> {
244
+ const trimmed = projectId.trim();
245
+ const withoutPrefix = trimmed.startsWith('retrivora-')
246
+ ? trimmed.replace(/^retrivora-/, '')
247
+ : trimmed;
248
+
249
+ return new Set([
250
+ trimmed,
251
+ withoutPrefix,
252
+ `retrivora-${withoutPrefix}`,
253
+ ].filter(Boolean));
254
+ }
255
+
256
+ function resolveLicensedNamespace(
257
+ payload: LicensePayload,
258
+ requestedNamespace?: string
259
+ ): { ok: true; namespace: string } | { ok: false; response: Response } {
260
+ const allowed = getAllowedNamespaces(payload.projectId);
261
+ const requested = requestedNamespace?.trim();
262
+
263
+ if (requested && !allowed.has(requested)) {
264
+ return {
265
+ ok: false,
266
+ response: new Response(JSON.stringify({
267
+ error: {
268
+ code: 'NAMESPACE_FORBIDDEN',
269
+ message: 'Requested namespace is not authorized for this license.',
270
+ },
271
+ }), {
272
+ status: 403,
273
+ headers: { 'Content-Type': 'application/json' },
274
+ }),
275
+ };
276
+ }
277
+
278
+ const defaultNamespace = payload.projectId.startsWith('retrivora-')
279
+ ? payload.projectId
280
+ : `retrivora-${payload.projectId}`;
281
+
282
+ return { ok: true, namespace: requested || defaultNamespace };
283
+ }
284
+
243
285
  // ─── Input Sanitization ───────────────────────────────────────────────────────
244
286
 
245
287
  const MAX_MESSAGE_LENGTH = 8000;
@@ -483,6 +525,8 @@ export function createChatHandler(
483
525
  }
484
526
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
485
527
  const { namespace, sessionId = 'default', messageId, userMessageId } = bodyObj;
528
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
529
+ if (!namespaceCheck.ok) return namespaceCheck.response as any;
486
530
 
487
531
  // 3. Input sanitization
488
532
  const sanitized = sanitizeInput(rawMessage ?? '');
@@ -499,7 +543,7 @@ export function createChatHandler(
499
543
  content: message,
500
544
  }).catch(err => console.warn('[createChatHandler] Failed to save user message:', err));
501
545
 
502
- const result = await plugin.chat(message, history, namespace);
546
+ const result = await plugin.chat(message, history, namespaceCheck.namespace);
503
547
 
504
548
  // Save assistant message to history
505
549
  const assistantMsgId = messageId || `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
@@ -632,6 +676,8 @@ export function createStreamHandler(
632
676
  }
633
677
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
634
678
  const { namespace, sessionId = 'default', messageId, userMessageId } = bodyObj;
679
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
680
+ if (!namespaceCheck.ok) return namespaceCheck.response as any;
635
681
 
636
682
  // 3. Input sanitization
637
683
  const sanitized = sanitizeInput(rawMessage ?? '');
@@ -668,7 +714,7 @@ export function createStreamHandler(
668
714
  };
669
715
 
670
716
  try {
671
- const pipelineStream = plugin.chatStream(message, history, namespace);
717
+ const pipelineStream = plugin.chatStream(message, history, namespaceCheck.namespace);
672
718
  let fullReply = '';
673
719
 
674
720
  for await (const chunk of pipelineStream) {
@@ -807,6 +853,9 @@ export function createIngestHandler(
807
853
  return NextResponse.json({ error: 'documents array is required' }, { status: 400 });
808
854
  }
809
855
 
856
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
857
+ if (!namespaceCheck.ok) return namespaceCheck.response as any;
858
+
810
859
  // Free Tier ingestion limits check
811
860
  if (isFreeTier(licenseCheck.payload.tier)) {
812
861
  const totalIncomingBytes = documents.reduce(
@@ -830,7 +879,7 @@ export function createIngestHandler(
830
879
  }
831
880
  }
832
881
 
833
- const results = await plugin.ingest(documents, namespace);
882
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
834
883
  reportTelemetry(req, plugin, 'DOCUMENT_INGESTION', 'success', `Ingested ${documents.length} document(s)`);
835
884
  return NextResponse.json({ results });
836
885
  } catch (err) {
@@ -1004,6 +1053,8 @@ export function createUploadHandler(
1004
1053
  const namespace = (formData.get('namespace') as string) || undefined;
1005
1054
  const dimensionRaw = formData.get('dimension');
1006
1055
  const dimension = dimensionRaw ? parseInt(dimensionRaw as string, 10) : undefined;
1056
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
1057
+ if (!namespaceCheck.ok) return namespaceCheck.response as any;
1007
1058
 
1008
1059
  if (!files || files.length === 0) {
1009
1060
  return NextResponse.json({ error: 'No files provided' }, { status: 400 });
@@ -1143,7 +1194,7 @@ export function createUploadHandler(
1143
1194
  }
1144
1195
  }
1145
1196
 
1146
- const results = await plugin.ingest(documents, namespace);
1197
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
1147
1198
  reportTelemetry(req, plugin, 'DOCUMENT_INGESTION', 'success', `Uploaded & ingested ${files.length} file(s)`);
1148
1199
  return NextResponse.json({ message: 'Upload successful', results });
1149
1200
  } catch (err) {
@@ -1186,6 +1237,7 @@ export function createSuggestionsHandler(
1186
1237
  const config = plugin.getConfig();
1187
1238
  const licenseCheck = enforceLicense(req, config);
1188
1239
  if (!licenseCheck.ok) return licenseCheck.response as any;
1240
+ let effectiveLicensePayload = licenseCheck.payload;
1189
1241
 
1190
1242
  try {
1191
1243
  let query = '';
@@ -1201,6 +1253,7 @@ export function createSuggestionsHandler(
1201
1253
  if (bodyLicenseKey) {
1202
1254
  const recheck = enforceLicense(req, config, bodyLicenseKey);
1203
1255
  if (!recheck.ok) return recheck.response as any;
1256
+ effectiveLicensePayload = recheck.payload;
1204
1257
  }
1205
1258
  } else {
1206
1259
  const url = new URL(req.url);
@@ -1212,7 +1265,10 @@ export function createSuggestionsHandler(
1212
1265
  return NextResponse.json({ suggestions: [] });
1213
1266
  }
1214
1267
 
1215
- const suggestions = await plugin.getSuggestions(query, namespace);
1268
+ const namespaceCheck = resolveLicensedNamespace(effectiveLicensePayload, namespace);
1269
+ if (!namespaceCheck.ok) return namespaceCheck.response as any;
1270
+
1271
+ const suggestions = await plugin.getSuggestions(query, namespaceCheck.namespace);
1216
1272
  reportTelemetry(req, plugin, 'AUTO_SUGGESTIONS', 'success', `Fetched ${suggestions.length} suggestions for: ${query.slice(0, 30)}`);
1217
1273
  return NextResponse.json({ suggestions });
1218
1274
  } catch (err) {
@@ -0,0 +1,105 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useMemo, useState } from 'react';
4
+ import { ConfigFetcher, RemoteConfig } from '../core/ConfigFetcher';
5
+ import {
6
+ ProjectChatSettings,
7
+ createDefaultProjectSettings,
8
+ normalizeProjectSettings,
9
+ } from '../core/ProjectSettings';
10
+
11
+ export interface UseProjectSettingsOptions {
12
+ licenseKey?: string;
13
+ enabled?: boolean;
14
+ initialSettings?: Partial<ProjectChatSettings>;
15
+ }
16
+
17
+ export interface UseProjectSettingsReturn {
18
+ settings: ProjectChatSettings;
19
+ remoteConfig: RemoteConfig | null;
20
+ isLoading: boolean;
21
+ error: string | null;
22
+ reload: () => Promise<void>;
23
+ }
24
+
25
+ export function useProjectSettings(
26
+ projectId: string,
27
+ options: UseProjectSettingsOptions = {}
28
+ ): UseProjectSettingsReturn {
29
+ const initialSettings = useMemo(
30
+ () => normalizeProjectSettings(projectId, options.initialSettings || createDefaultProjectSettings(projectId)),
31
+ [options.initialSettings, projectId]
32
+ );
33
+ const [settings, setSettings] = useState<ProjectChatSettings>(initialSettings);
34
+ const [remoteConfig, setRemoteConfig] = useState<RemoteConfig | null>(null);
35
+ const [isLoading, setIsLoading] = useState(false);
36
+ const [error, setError] = useState<string | null>(null);
37
+
38
+ async function reload() {
39
+ if (options.enabled === false || !options.licenseKey) {
40
+ setSettings(initialSettings);
41
+ setRemoteConfig(null);
42
+ return;
43
+ }
44
+
45
+ setIsLoading(true);
46
+ setError(null);
47
+
48
+ try {
49
+ const config = await ConfigFetcher.fetchRemoteConfig(projectId, options.licenseKey);
50
+ setRemoteConfig(config);
51
+ setSettings(config?.projectSettings || initialSettings);
52
+ } catch (err) {
53
+ const message = err instanceof Error ? err.message : 'Failed to load project settings';
54
+ setError(message);
55
+ setSettings(initialSettings);
56
+ } finally {
57
+ setIsLoading(false);
58
+ }
59
+ }
60
+
61
+ useEffect(() => {
62
+ let cancelled = false;
63
+
64
+ async function load() {
65
+ if (options.enabled === false || !options.licenseKey) {
66
+ setSettings(initialSettings);
67
+ setRemoteConfig(null);
68
+ return;
69
+ }
70
+
71
+ setIsLoading(true);
72
+ setError(null);
73
+
74
+ try {
75
+ const config = await ConfigFetcher.fetchRemoteConfig(projectId, options.licenseKey);
76
+ if (!cancelled) {
77
+ setRemoteConfig(config);
78
+ setSettings(config?.projectSettings || initialSettings);
79
+ }
80
+ } catch (err) {
81
+ if (!cancelled) {
82
+ const message = err instanceof Error ? err.message : 'Failed to load project settings';
83
+ setError(message);
84
+ setSettings(initialSettings);
85
+ }
86
+ } finally {
87
+ if (!cancelled) setIsLoading(false);
88
+ }
89
+ }
90
+
91
+ load();
92
+
93
+ return () => {
94
+ cancelled = true;
95
+ };
96
+ }, [initialSettings, options.enabled, options.licenseKey, projectId]);
97
+
98
+ return {
99
+ settings,
100
+ remoteConfig,
101
+ isLoading,
102
+ error,
103
+ reload,
104
+ };
105
+ }
package/src/index.css CHANGED
@@ -346,6 +346,15 @@
346
346
  .top-4 {
347
347
  top: calc(var(--spacing) * 4);
348
348
  }
349
+ .top-6 {
350
+ top: calc(var(--spacing) * 6);
351
+ }
352
+ .top-20 {
353
+ top: calc(var(--spacing) * 20);
354
+ }
355
+ .top-24 {
356
+ top: calc(var(--spacing) * 24);
357
+ }
349
358
  .-right-4 {
350
359
  right: calc(var(--spacing) * -4);
351
360
  }
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ export { ProductCarousel } from './components/ProductCarousel';
22
22
 
23
23
  // ── Headless Hooks ────────────────────────────────────────────
24
24
  export { useRagChat } from './hooks/useRagChat';
25
+ export { useProjectSettings } from './hooks/useProjectSettings';
25
26
 
26
27
  // ── Utils ─────────────────────────────────────────────────────
27
28
  export { addSynonyms } from './utils/synonyms';
@@ -60,6 +61,12 @@ export type { Retrivora } from './core/Retrivora';
60
61
  export type { RetrivoraErrorCode } from './exceptions';
61
62
  export { LicenseValidator } from './core/LicenseValidator';
62
63
  export type { LicenseValidationRequest, LicenseValidationResponse } from './core/LicenseValidator';
64
+ export { ConfigFetcher } from './core/ConfigFetcher';
65
+ export {
66
+ createDefaultProjectSettings,
67
+ normalizeProjectSettings,
68
+ projectSettingsToUiConfig,
69
+ } from './core/ProjectSettings';
63
70
  export { CircuitBreaker } from './core/CircuitBreaker';
64
71
  export type { CircuitBreakerOptions } from './core/CircuitBreaker';
65
72
  export { BatchProcessor, isTransientError } from './core/BatchProcessor';
@@ -98,3 +105,24 @@ export type {
98
105
  TokenUsage,
99
106
  RetrievedChunk
100
107
  } from './types';
108
+ export type {
109
+ RemoteConfig,
110
+ RemoteVectorConfig,
111
+ RemoteEmbeddingConfig,
112
+ RemoteLLMConfig,
113
+ } from './core/ConfigFetcher';
114
+ export type {
115
+ AuthMode,
116
+ ProjectAiSettings,
117
+ ProjectAuthSettings,
118
+ ProjectBrandingSettings,
119
+ ProjectChatSettings,
120
+ ProjectTelemetrySettings,
121
+ ProjectWidgetSettings,
122
+ ThemeMode,
123
+ WidgetPosition,
124
+ } from './core/ProjectSettings';
125
+ export type {
126
+ UseProjectSettingsOptions,
127
+ UseProjectSettingsReturn,
128
+ } from './hooks/useProjectSettings';
package/src/server.ts CHANGED
@@ -40,6 +40,29 @@ export { LicenseVerifier } from './core/LicenseVerifier';
40
40
  export { SDK_VERSION } from './version';
41
41
  export { ProviderHealthCheck } from './core/ProviderHealthCheck';
42
42
  export { BatchProcessor } from './core/BatchProcessor';
43
+ export { ConfigFetcher } from './core/ConfigFetcher';
44
+ export {
45
+ createDefaultProjectSettings,
46
+ normalizeProjectSettings,
47
+ projectSettingsToUiConfig,
48
+ } from './core/ProjectSettings';
49
+ export type {
50
+ RemoteConfig,
51
+ RemoteVectorConfig,
52
+ RemoteEmbeddingConfig,
53
+ RemoteLLMConfig,
54
+ } from './core/ConfigFetcher';
55
+ export type {
56
+ AuthMode,
57
+ ProjectAiSettings,
58
+ ProjectAuthSettings,
59
+ ProjectBrandingSettings,
60
+ ProjectChatSettings,
61
+ ProjectTelemetrySettings,
62
+ ProjectWidgetSettings,
63
+ ThemeMode,
64
+ WidgetPosition,
65
+ } from './core/ProjectSettings';
43
66
 
44
67
  // ── Configuration Helpers ──────────────────────────────────────
45
68
  export { getRagConfig } from './config/serverConfig';
@@ -109,4 +132,3 @@ export {
109
132
  LicenseValidationError,
110
133
  wrapError,
111
134
  } from './exceptions';
112
-
@@ -2,6 +2,7 @@ import { ReactNode, CSSProperties, MouseEvent, ElementType } from 'react';
2
2
  import { Product, VectorMatch } from './index';
3
3
  import { RagMessage } from './chat';
4
4
  import { UIConfig } from '../config/RagConfig';
5
+ import { ProjectChatSettings, WidgetPosition } from '../core/ProjectSettings';
5
6
 
6
7
  export interface ArchitectureCardProps {
7
8
  icon: ReactNode;
@@ -69,7 +70,7 @@ export interface ChatWindowProps {
69
70
 
70
71
  export interface ChatWidgetProps {
71
72
  /** Position of the floating button. Defaults to bottom-right. */
72
- position?: 'bottom-right' | 'bottom-left';
73
+ position?: WidgetPosition;
73
74
  /** Called when the user clicks 'Add to Cart' on a product */
74
75
  onAddToCart?: (product: Product) => void;
75
76
  /** Optional custom API URL to send chat messages to */
@@ -134,13 +135,24 @@ export interface ClientConfig {
134
135
  model?: string;
135
136
  dimensions?: number;
136
137
  };
138
+ licenseKey?: string;
139
+ headers?: Record<string, string>;
140
+ retrivoraApiBase?: string;
141
+ projectSettings?: ProjectChatSettings;
142
+ autoLoadProjectSettings?: boolean;
143
+ isProjectSettingsLoading?: boolean;
137
144
  }
138
145
 
139
146
  export interface ConfigProviderProps {
140
147
  config?: {
141
148
  projectId?: string;
142
149
  ui?: Partial<UIConfig>;
143
- embedding?: { model?: string; dimensions?: number }
150
+ embedding?: { model?: string; dimensions?: number };
151
+ licenseKey?: string;
152
+ headers?: Record<string, string>;
153
+ retrivoraApiBase?: string;
154
+ projectSettings?: Partial<ProjectChatSettings>;
155
+ autoLoadProjectSettings?: boolean;
144
156
  };
145
157
  children: ReactNode;
146
158
  }