@retrivora-ai/rag-engine 2.2.9 → 2.3.1

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,394 @@
1
+ import { NextRequest } from 'next/server';
2
+ import { i as RagConfig, I as ILLMProvider, C as ChatMessage, c as ChatResponse, f as IngestDocument } from './ILLMProvider-teTNQ1lh.mjs';
3
+
4
+ interface ValidationError {
5
+ field: string;
6
+ message: string;
7
+ suggestion?: string;
8
+ severity: 'error' | 'warning';
9
+ }
10
+ /**
11
+ * ConfigValidator.ts — Comprehensive configuration validation.
12
+ * Uses a pluggable architecture to delegate provider-specific checks.
13
+ */
14
+ declare class ConfigValidator {
15
+ /**
16
+ * Validates the entire RagConfig object.
17
+ */
18
+ static validate(config: RagConfig): Promise<ValidationError[]>;
19
+ private static validateVectorDbConfig;
20
+ private static validateLLMConfig;
21
+ private static validateEmbeddingConfig;
22
+ /**
23
+ * Temporary fallbacks for providers not yet migrated to the pluggable architecture.
24
+ */
25
+ private static fallbackVectorValidation;
26
+ private static fallbackLLMValidation;
27
+ private static fallbackEmbeddingValidation;
28
+ private static validateUIConfig;
29
+ private static validateRAGConfig;
30
+ private static isValidCSSColor;
31
+ static validateAndThrow(config: RagConfig): Promise<void>;
32
+ }
33
+
34
+ /**
35
+ * Interface for provider-specific configuration validation logic.
36
+ */
37
+ interface IProviderValidator {
38
+ /**
39
+ * Validates the configuration for a specific provider.
40
+ * @param config - The configuration object to validate.
41
+ * @returns An array of validation errors (empty if valid).
42
+ */
43
+ validate(config: Record<string, unknown>): ValidationError[];
44
+ }
45
+ /**
46
+ * Result of a provider health check.
47
+ */
48
+ interface HealthCheckResult {
49
+ healthy: boolean;
50
+ provider: string;
51
+ version?: string;
52
+ capabilities?: Record<string, unknown>;
53
+ error?: string;
54
+ timestamp: number;
55
+ }
56
+ /**
57
+ * Interface for provider-specific health checking logic.
58
+ */
59
+ interface IProviderHealthChecker {
60
+ /**
61
+ * Performs a health check for a specific provider.
62
+ * @param config - The configuration object used to connect to the provider.
63
+ * @returns A promise that resolves to the health check result.
64
+ */
65
+ check(config: Record<string, unknown>): Promise<HealthCheckResult>;
66
+ }
67
+
68
+ /**
69
+ * VectorPlugin — main orchestrator class.
70
+ * This is the primary interface for host applications.
71
+ *
72
+ * Features:
73
+ * - Configuration resolution from host + environment
74
+ * - Configuration validation with detailed error messages
75
+ * - Provider health checks before initialization
76
+ * - Multi-provider support (Vector DBs & LLMs)
77
+ * - Per-tenant data isolation via namespacing
78
+ */
79
+ declare class VectorPlugin {
80
+ private config;
81
+ private pipeline;
82
+ private validationPromise;
83
+ constructor(hostConfig?: Partial<RagConfig>);
84
+ /**
85
+ * Get the current resolved configuration.
86
+ */
87
+ getConfig(): RagConfig;
88
+ /**
89
+ * Get the initialized LLM provider (available after the first request).
90
+ * Used by handlers to pass to UITransformer.analyzeAndDecide() for
91
+ * LLM-driven visualization decisions.
92
+ */
93
+ getLLMProvider(): ILLMProvider | undefined;
94
+ /**
95
+ * Perform pre-flight health checks on all configured providers.
96
+ * Useful to verify connectivity before running operations.
97
+ *
98
+ * @returns Health status for vector DB, LLM, and embedding providers
99
+ */
100
+ checkHealth(): Promise<{
101
+ vectorDb: HealthCheckResult;
102
+ llm: HealthCheckResult;
103
+ embedding?: HealthCheckResult;
104
+ allHealthy: boolean;
105
+ }>;
106
+ private estimateInputTokens;
107
+ /**
108
+ * Run a chat query.
109
+ */
110
+ chat(message: string, history?: ChatMessage[], namespace?: string): Promise<ChatResponse>;
111
+ /**
112
+ * Run a streaming chat query.
113
+ */
114
+ chatStream(message: string, history?: ChatMessage[], namespace?: string): AsyncGenerator<string | ChatResponse, void, unknown>;
115
+ /**
116
+ * Ingest documents into the vector database.
117
+ */
118
+ ingest(documents: IngestDocument[], namespace?: string): Promise<Array<{
119
+ docId: string | number;
120
+ chunksIngested: number;
121
+ }>>;
122
+ /**
123
+ * Get auto-suggestions based on a query prefix.
124
+ */
125
+ getSuggestions(query: string, namespace?: string): Promise<string[]>;
126
+ }
127
+
128
+ /**
129
+ * Shared options accepted by every handler factory.
130
+ *
131
+ * Pass `onAuthorize` to plug in per-request auth rules; the callback is
132
+ * called before rate-limiting, license enforcement, or any business logic
133
+ * runs. Return `true` or the resolved promise `true` to allow, `false`
134
+ * to get a 401, or return a `Response` to fully control the denial (for
135
+ * example redirecting an OAuth-style flow to a login page).
136
+ */
137
+ interface HandlerOptions {
138
+ /** Optional synchronous or asynchronous authorization gate. */
139
+ onAuthorize?: (req: NextRequest) => boolean | Response | Promise<boolean | Response>;
140
+ /**
141
+ * Optional scope resolver for multi-tenant deployments.
142
+ *
143
+ * Returns an allow-list of project ids that the caller is authorized to
144
+ * access on the `sessions`, `history`, and `feedback` endpoints. When
145
+ * the callback returns a non-empty array, server-side filtering is
146
+ * applied to every `listSessions`, `getHistory`, `clearHistory`,
147
+ * `listFeedback`, and `getFeedback` call so the caller can never leak
148
+ * another tenant's data even when client-side filters are tampered with.
149
+ */
150
+ onResolveScope?: (req: NextRequest) => string[] | undefined | Promise<string[] | undefined>;
151
+ }
152
+ /**
153
+ * Encode a payload as a Server-Sent Events frame.
154
+ * data: <json>\n\n
155
+ */
156
+ declare function sseFrame(payload: unknown): string;
157
+ /** Encode a plain text chunk as an SSE frame. */
158
+ declare function sseTextFrame(text: string): string;
159
+ /** Encode the retrieval metadata with UI transformation as an SSE frame. */
160
+ declare function sseMetaFrame(meta: unknown): string;
161
+ /** Encode the UI transformation result as an SSE frame. */
162
+ declare function sseUIFrame(uiTransformation: unknown): string;
163
+ /** Encode the observability trace as an SSE frame. */
164
+ declare function sseObservabilityFrame(trace: unknown): string;
165
+ /** Encode a stream error as an SSE frame. */
166
+ declare function sseErrorFrame(message: string): string;
167
+ /**
168
+ * Build a Next.js App Router POST handler for **synchronous** RAG chat.
169
+ *
170
+ * Pipeline (in execution order):
171
+ * 1. `options.onAuthorize` — custom authorization gate (optional)
172
+ * 2. In-memory IP rate limiter (30 req / 60 s sliding window)
173
+ * 3. JSON body parse → `enforceLicense()` RSA signature validation
174
+ * 4. Input sanitization + length / toxicity / PII / prompt-injection heuristics
175
+ * 5. User-message persistence via `DatabaseStorage`
176
+ * 6. LLM-driven RAG retrieval via `plugin.chat()`
177
+ * 7. Observability UI transformation + response persistence
178
+ * 8. JSON response (`ChatResponse` shape)
179
+ *
180
+ * Use this handler when you don't need streaming (e.g. server-side SDKs).
181
+ * For streaming use `createStreamHandler` — the same pipeline but with
182
+ * Server-Sent Events for incremental tokens.
183
+ *
184
+ * @param configOrPlugin - Either a partial `RagConfig` (a plugin will be
185
+ * created or reused for you) or an already-constructed
186
+ * `VectorPlugin` instance.
187
+ * @param options - See `HandlerOptions`. `onAuthorize` is recommended
188
+ * for multi-tenant deployments to gate access.
189
+ * @returns An async `POST(req, ctx)` function suitable for being the default
190
+ * export of a Next.js route file.
191
+ */
192
+ declare function createChatHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: any, context?: any) => Promise<any>;
193
+ /**
194
+ * Build a Next.js App Router POST handler for **streaming** RAG chat via SSE.
195
+ *
196
+ * Same pipeline as `createChatHandler`, but the `plugin.chat()` call is run
197
+ * in streaming mode and every token is immediately emitted as a Server-Sent
198
+ * Event frame. The stream contains frames for `text`, `thinking`,
199
+ * `metadata`, `ui_transformation`, `observability`, and a terminal `done`.
200
+ *
201
+ * Multipart upload short-circuit: When the request `Content-Type` is
202
+ * `multipart/form-data` the request is transparently delegated to
203
+ * `createUploadHandler` (which also runs its own `enforceLicense()` gate).
204
+ *
205
+ * Pipeline (in execution order):
206
+ * 1. `options.onAuthorize` — custom authorization gate (optional)
207
+ * 2. In-memory IP rate limiter (30 req / 60 s sliding window)
208
+ * 3. JSON body parse (or form-data upload delegation)
209
+ * 4. `enforceLicense()` RSA signature validation — 403 if missing / terminated
210
+ * 5. Input sanitization + length / toxicity / PII / prompt-injection heuristics
211
+ * 6. User-message persistence via `DatabaseStorage`
212
+ * 7. Streaming RAG retrieval via `plugin.chat({ stream: true })`
213
+ * 8. Persist assistant message + emit SSE frames
214
+ *
215
+ * @param configOrPlugin - Partial `RagConfig` or an existing `VectorPlugin`.
216
+ * @param options - See `HandlerOptions`.
217
+ * @returns Async `POST(req, ctx)` function for `app/.../route.ts`.
218
+ */
219
+ declare function createStreamHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: any, context?: any) => Promise<any>;
220
+ /**
221
+ * Build a POST handler that ingests raw pre-parsed documents into the vector DB.
222
+ *
223
+ * Unlike `createUploadHandler` (which takes files and does parsing/splitting),
224
+ * this endpoint expects the caller to supply `documents[]` already split and
225
+ * prepared. This is useful for bulk backfill jobs, migrations, or programmatic
226
+ * sync pipelines.
227
+ *
228
+ * Security: Requires a valid license (RSA signature check via `enforceLicense`)
229
+ * AFTER JSON body parse so the optional `body.licenseKey` override is read.
230
+ *
231
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
232
+ * @param options - Optional `onAuthorize` gate.
233
+ * @returns Async POST handler.
234
+ */
235
+ declare function createIngestHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: any, context?: any) => Promise<any>;
236
+ /**
237
+ * Build a GET handler that returns health / readiness status.
238
+ *
239
+ * Response shape (200 OK):
240
+ * ```json
241
+ * {
242
+ * "ok": true,
243
+ * "status": "healthy",
244
+ * "sdkVersion": "x.y.z",
245
+ * "timestamp": "ISO string",
246
+ * "embedding": { "provider": "...", "ok": true },
247
+ * "vectorStore": { "provider": "...", "ok": true }
248
+ * }
249
+ * ```
250
+ *
251
+ * License check: This endpoint is intentionally **NOT** license-gated so
252
+ * orchestrators (Kubernetes, uptime probes, Vercel cron pings) can use it
253
+ * to assert the process is alive even when no license has been configured
254
+ * yet during deploy.
255
+ *
256
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
257
+ * @param options - Optional `onAuthorize` gate (rarely used here).
258
+ * @returns Async GET handler.
259
+ */
260
+ declare function createHealthHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req?: NextRequest) => Promise<any>;
261
+ /**
262
+ * Build a POST handler for the SDK-facing `/v1/license/validate` endpoint.
263
+ *
264
+ * Client flow: `LicenseValidator.validate()` calls this URL, receives
265
+ * authoritative DB-backed status (ACTIVE / TERMINATED / SUSPENDED / EXPIRED /
266
+ * REVOKED), and falls back to pure-local `LicenseVerifier.verify()` if the
267
+ * server is unreachable or returns an error.
268
+ *
269
+ * This handler does NOT enforce license — it is the verifier itself. It does,
270
+ * however, still apply rate limiting to mitigate abuse.
271
+ *
272
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
273
+ * @param options - Optional `onAuthorize` gate.
274
+ * @returns Async POST handler returning `LicenseValidationResponse` JSON.
275
+ */
276
+ declare function createLicenseHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: NextRequest) => Promise<any>;
277
+ /**
278
+ * Build a POST handler that accepts `multipart/form-data` file uploads.
279
+ *
280
+ * Workflow:
281
+ * 1. `onAuthorize` → license enforcement via `enforceLicense` (no JSON body,
282
+ * so the key must come from headers or the environment).
283
+ * 2. Read FormData files[] list → max 25 files per request, 100 MB each.
284
+ * 3. Per-file: use `DocumentParser` to extract raw text by MIME type (PDF,
285
+ * DOCX, TXT, MD, HTML, JSON, CSV, images via OCR fallback, etc.).
286
+ * 4. Chunk by the configured chunker (RecursiveCharacter, semantic, etc.).
287
+ * 5. Call `plugin.ingest()` to embed and insert into the vector store.
288
+ * 6. Return JSON summary per file (status, chunks ingested, docId).
289
+ *
290
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
291
+ * @param options - Optional `onAuthorize` gate.
292
+ * @returns Async POST handler.
293
+ */
294
+ declare function createUploadHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: any, context?: any) => Promise<any>;
295
+ /**
296
+ * Build a GET/POST handler for auto-suggestions (used by ChatWidget prompt chips).
297
+ *
298
+ * Requests:
299
+ * - GET `?query=...&namespace=...`
300
+ * - POST `{ query: string, namespace?: string, licenseKey?: string }`
301
+ *
302
+ * Response (200 OK): `{ suggestions: string[] }`
303
+ *
304
+ * License enforcement: Runs BEFORE body parse on headers/env, and if the POST
305
+ * body contains a `licenseKey` override the check is repeated with the body
306
+ * key included so the per-request override is honored.
307
+ *
308
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
309
+ * @param options - Optional `onAuthorize` gate.
310
+ * @returns Async handler accepting both GET and POST methods.
311
+ */
312
+ declare function createSuggestionsHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: NextRequest) => Promise<any>;
313
+ /**
314
+ * Build a handler for chat-history listing and clearing.
315
+ *
316
+ * Routes dispatched by `createRagHandler`:
317
+ * - GET `/history?sessionId=...&limit=...` → returns `{ messages: HistoryMessage[] }`
318
+ * - POST `/history/clear` with `{ sessionId? }` JSON body → returns `{ ok: true }`
319
+ *
320
+ * Storage: Uses `DatabaseStorage` (default SQLite or custom configured driver).
321
+ * License enforcement is handled by the upstream `createRagHandler` router when
322
+ * this handler is composed through it; standalone usage is rare.
323
+ *
324
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
325
+ * @param options - Optional `onAuthorize` gate.
326
+ * @returns Async handler accepting GET (list) or POST (clear) methods.
327
+ */
328
+ declare function createHistoryHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: NextRequest) => Promise<any>;
329
+ /**
330
+ * Build a POST handler for collecting thumbs-up / thumbs-down user feedback.
331
+ *
332
+ * Request: `{ messageId, sessionId?, rating: 1 | -1, comment?, reason? }`
333
+ * Response: `{ ok: true, id: string }` (201 Created)
334
+ *
335
+ * Feedback is written to `DatabaseStorage.feedback` for RAG pipeline
336
+ * evaluation, offline fine-tuning dataset curation, and support triage.
337
+ *
338
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
339
+ * @param options - Optional `onAuthorize` gate.
340
+ * @returns Async POST handler.
341
+ */
342
+ declare function createFeedbackHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req: NextRequest) => Promise<any>;
343
+ /**
344
+ * Build a GET handler that lists the set of chat sessions.
345
+ *
346
+ * Response: `{ sessions: { id, title, lastMessageAt, preview }[] }`
347
+ *
348
+ * Sessions are read from `DatabaseStorage`. Combined with `createHistoryHandler`
349
+ * this enables a sidebar of prior conversations for custom UIs built on top of
350
+ * the `useRagChat` headless hook.
351
+ *
352
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
353
+ * @param options - Optional `onAuthorize` gate.
354
+ * @returns Async GET handler returning a session listing.
355
+ */
356
+ declare function createSessionsHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): (req?: NextRequest) => Promise<any>;
357
+ /**
358
+ * Build a Next.js catch-all route that dispatches to every sub-handler by path.
359
+ *
360
+ * Intended drop-in export:
361
+ * ```ts
362
+ * // app/api/retrivora/[[...retrivora]]/route.ts
363
+ * import { createRagHandler } from '@retrivora-ai/rag-engine';
364
+ * const { GET, POST } = createRagHandler({ /* RagConfig *\/ });
365
+ * export { GET, POST };
366
+ * ```
367
+ *
368
+ * Segments dispatched (POST unless marked GET):
369
+ * - `chat` → createStreamHandler (SSE streaming chat)
370
+ * - `upload` → createUploadHandler (file ingestion)
371
+ * - `suggestions` → createSuggestionsHandler (GET/POST)
372
+ * - `v1/license/validate` → createLicenseHandler
373
+ * - `health` → createHealthHandler (GET)
374
+ * - `feedback` → createFeedbackHandler
375
+ * - `history` → createHistoryHandler (GET/POST)
376
+ * - `sessions` → createSessionsHandler (GET)
377
+ * - Any other segment → 404 with a JSON error body
378
+ *
379
+ * This is the **recommended** way to mount the SDK in a Next.js app. Using
380
+ * any single handler individually without its license enforcement gate is a
381
+ * security anti-pattern — prefer `createRagHandler` unless you have a very
382
+ * specific reason to split routes up.
383
+ *
384
+ * @param configOrPlugin - Partial `RagConfig` or existing `VectorPlugin`.
385
+ * @param options - Optional `onAuthorize` gate (propagated to every
386
+ * sub-handler so auth rules apply uniformly).
387
+ * @returns An object `{ GET, POST }` to re-export as your route file defaults.
388
+ */
389
+ declare function createRagHandler(configOrPlugin?: Partial<RagConfig> | VectorPlugin, options?: HandlerOptions): {
390
+ GET: (req: any, context?: any) => Promise<any>;
391
+ POST: (req: any, context?: any) => Promise<any>;
392
+ };
393
+
394
+ export { ConfigValidator as C, type HealthCheckResult as H, type IProviderValidator as I, type ValidationError as V, type IProviderHealthChecker as a, type HandlerOptions as b, VectorPlugin as c, createChatHandler as d, createFeedbackHandler as e, createHealthHandler as f, createHistoryHandler as g, createIngestHandler as h, createRagHandler as i, createSessionsHandler as j, createStreamHandler as k, createUploadHandler as l, sseFrame as m, sseMetaFrame as n, sseTextFrame as o, createLicenseHandler as p, createSuggestionsHandler as q, sseObservabilityFrame as r, sseErrorFrame as s, sseUIFrame as t };
package/dist/index.css CHANGED
@@ -1869,6 +1869,9 @@
1869
1869
  .opacity-30 {
1870
1870
  opacity: 30%;
1871
1871
  }
1872
+ .opacity-60 {
1873
+ opacity: 60%;
1874
+ }
1872
1875
  .opacity-100 {
1873
1876
  opacity: 100%;
1874
1877
  }
@@ -1928,6 +1931,10 @@
1928
1931
  --tw-drop-shadow: drop-shadow(var(--drop-shadow-2xl));
1929
1932
  filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);
1930
1933
  }
1934
+ .grayscale {
1935
+ --tw-grayscale: grayscale(100%);
1936
+ filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);
1937
+ }
1931
1938
  .filter {
1932
1939
  filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);
1933
1940
  }
@@ -2354,6 +2361,11 @@
2354
2361
  opacity: 30%;
2355
2362
  }
2356
2363
  }
2364
+ .disabled\:opacity-40 {
2365
+ &:disabled {
2366
+ opacity: 40%;
2367
+ }
2368
+ }
2357
2369
  .disabled\:opacity-50 {
2358
2370
  &:disabled {
2359
2371
  opacity: 50%;
@@ -2371,6 +2383,24 @@
2371
2383
  }
2372
2384
  }
2373
2385
  }
2386
+ .disabled\:hover\:text-slate-400 {
2387
+ &:disabled {
2388
+ &:hover {
2389
+ @media (hover: hover) {
2390
+ color: var(--color-slate-400);
2391
+ }
2392
+ }
2393
+ }
2394
+ }
2395
+ .disabled\:hover\:text-slate-600 {
2396
+ &:disabled {
2397
+ &:hover {
2398
+ @media (hover: hover) {
2399
+ color: var(--color-slate-600);
2400
+ }
2401
+ }
2402
+ }
2403
+ }
2374
2404
  .disabled\:active\:scale-100 {
2375
2405
  &:disabled {
2376
2406
  &:active {
@@ -3549,6 +3579,34 @@
3549
3579
  }
3550
3580
  }
3551
3581
  }
3582
+ .dark\:disabled\:hover\:text-white\/40 {
3583
+ @media (prefers-color-scheme: dark) {
3584
+ &:disabled {
3585
+ &:hover {
3586
+ @media (hover: hover) {
3587
+ color: color-mix(in srgb, #fff 40%, transparent);
3588
+ @supports (color: color-mix(in lab, red, red)) {
3589
+ color: color-mix(in oklab, var(--color-white) 40%, transparent);
3590
+ }
3591
+ }
3592
+ }
3593
+ }
3594
+ }
3595
+ }
3596
+ .dark\:disabled\:hover\:text-white\/60 {
3597
+ @media (prefers-color-scheme: dark) {
3598
+ &:disabled {
3599
+ &:hover {
3600
+ @media (hover: hover) {
3601
+ color: color-mix(in srgb, #fff 60%, transparent);
3602
+ @supports (color: color-mix(in lab, red, red)) {
3603
+ color: color-mix(in oklab, var(--color-white) 60%, transparent);
3604
+ }
3605
+ }
3606
+ }
3607
+ }
3608
+ }
3609
+ }
3552
3610
  }
3553
3611
  @layer base {
3554
3612
  :root {
package/dist/index.d.mts CHANGED
@@ -1,12 +1,48 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { C as ChatWidgetProps, a as ChatWindowProps, D as DocumentUploadProps, M as MessageBubbleProps, S as SourceCardProps, b as ConfigProviderProps, c as ClientConfig, P as ProductCardProps, d as ProductCarouselProps } from './LicenseValidator-CENvo9o2.mjs';
3
- export { A as AuthenticationException, e as ChartType, f as Chunk, g as ChunkOptions, h as ConfigurationException, i as DecisionContext, E as EmbeddingFailedException, I as IRenderRule, j as IRendererStrategy, k as IntentCategory, l as IntentClassifier, L as LicenseValidationError, m as LicenseValidationRequest, n as LicenseValidationResponse, o as LicenseValidator, p as ProviderNotFoundException, R as RateLimitException, q as RenderDecision, r as RenderType, s as RendererRegistry, t as RetrievalException, u as Retrivora, v as RetrivoraError, w as RetrivoraErrorCode, x as RuleEngine, y as SDKVersionUnsupportedError, z as SDK_VERSION, V as VisualizationDecisionEngine, B as decideVisualization } from './LicenseValidator-CENvo9o2.mjs';
2
+ import { C as ChatWidgetProps, a as ChatWindowProps, D as DocumentUploadProps, M as MessageBubbleProps, S as SourceCardProps, b as ConfigProviderProps, c as ClientConfig, P as ProductCardProps, d as ProductCarouselProps } from './BatchProcessor-7yV-UCHW.mjs';
3
+ export { A as AuthenticationException, B as BatchOptions, e as BatchProcessor, f as BatchResult, g as ChartType, h as Chunk, i as ChunkOptions, j as ConfigurationException, k as DecisionContext, E as EmbeddingFailedException, I as IRenderRule, l as IRendererStrategy, m as IntentCategory, n as IntentClassifier, L as LicenseValidationError, o as LicenseValidationRequest, p as LicenseValidationResponse, q as LicenseValidator, r as ProviderNotFoundException, R as RateLimitException, s as RenderDecision, t as RenderType, u as RendererRegistry, v as RetrievalException, w as Retrivora, x as RetrivoraError, y as RetrivoraErrorCode, z as RuleEngine, F as SDKVersionUnsupportedError, G as SDK_VERSION, V as VisualizationDecisionEngine, H as decideVisualization, J as isTransientError } from './BatchProcessor-7yV-UCHW.mjs';
4
4
  import { O as ObservabilityTrace, U as UseRagChatOptions, a as UseRagChatReturn } from './ILLMProvider-teTNQ1lh.mjs';
5
5
  export { C as ChatMessage, b as ChatOptions, c as ChatResponse, E as EmbedOptions, d as EmbeddingConfig, e as EmbeddingProvider, I as ILLMProvider, f as IngestDocument, L as LLMConfig, g as LLMProvider, h as LatencyBreakdown, R as RAGConfig, i as RagConfig, j as RagMessage, k as RetrievalConfig, l as RetrievedChunk, T as TokenUsage, m as UIConfig, n as UniversalRagConfig, o as UpsertDocument, V as VectorDBConfig, p as VectorDBProvider, q as VectorMatch, W as WorkflowConfig } from './ILLMProvider-teTNQ1lh.mjs';
6
6
  import 'react';
7
7
 
8
+ /**
9
+ * ChatWidget — Floating Action Button (FAB) that toggles the chat window.
10
+ *
11
+ * Responsibilities:
12
+ * - Validates the Retrivora license key BEFORE allowing the chat to open
13
+ * - Proactively validates on mount to visually lock the widget when no
14
+ * valid license is present (TERMINATED / SUSPENDED / missing)
15
+ * - Manages window resize, maximize, and visual positioning
16
+ * - Shows an error toast when license validation fails on user attempt
17
+ *
18
+ * License key resolution order (highest to lowest priority):
19
+ * 1. Explicit `licenseKey` prop
20
+ * 2. `x-license-key` header (from `headers` prop)
21
+ * 3. `Authorization: Bearer <key>` header (from `headers` prop)
22
+ * 4. Environment variables `NEXT_PUBLIC_RETRIVORA_LICENSE_KEY` / `RETRIVORA_LICENSE_KEY`
23
+ *
24
+ * @param props - Widget position, callbacks, API overrides, and license overrides
25
+ */
8
26
  declare function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, licenseKey: licenseKeyProp, headers }: ChatWidgetProps): react_jsx_runtime.JSX.Element | null;
9
27
 
28
+ /**
29
+ * ChatWindow component.
30
+ *
31
+ * @param className - Additional CSS class for the outer wrapper.
32
+ * @param style - Inline styles for the outer wrapper.
33
+ * @param onClose - Callback for the close (X) button (widget mode only).
34
+ * @param showClose - Whether to render the close button.
35
+ * @param onResizeStart - Callback fired when user begins dragging the resize handle.
36
+ * @param onResetResize - Callback fired when the reset-size button is clicked.
37
+ * @param isResized - True if the window has been resized away from defaults.
38
+ * @param onMaximize - Callback for the maximize/minimize toggle button.
39
+ * @param isMaximized - True if the window is currently maximized.
40
+ * @param onAddToCart - Callback fired when user clicks "Add to Cart" on a product card.
41
+ * @param apiUrl - Override URL for the chat endpoint (bypasses retrivoraApiBase).
42
+ * @param retrivoraApiBase - Base URL for Retrivora catch-all endpoints (chat/suggestions/history/etc).
43
+ * @param licenseKey - Override license key (highest priority; falls back to headers/env).
44
+ * @param headers - Custom headers forwarded with every network request.
45
+ */
10
46
  declare function ChatWindow({ className, style, onClose, showClose, onResizeStart, onResetResize, isResized, onMaximize, isMaximized, onAddToCart, apiUrl, retrivoraApiBase, licenseKey: licenseKeyProp, headers }: ChatWindowProps): react_jsx_runtime.JSX.Element;
11
47
 
12
48
  declare function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploadComplete, className }: DocumentUploadProps): react_jsx_runtime.JSX.Element;
@@ -48,4 +84,28 @@ declare function useRagChat(projectId: string, options?: UseRagChatOptions): Use
48
84
  */
49
85
  declare function addSynonyms(customSynonyms: Record<string, string[]>): void;
50
86
 
51
- export { ChatWidget, ChatWidgetProps, ChatWindow, ChatWindowProps, ClientConfig, CodeViewer, ConfigProvider, DocumentUpload, DocumentUploadProps, MessageBubble, MessageBubbleProps, ObservabilityPanel, ObservabilityTrace, ProductCard, ProductCardProps, ProductCarousel, ProductCarouselProps, SourceCard, SourceCardProps, UseRagChatOptions, UseRagChatReturn, addSynonyms, useConfig, useRagChat };
87
+ type CircuitState = 'closed' | 'open' | 'half-open';
88
+ interface CircuitBreakerOptions {
89
+ failureThreshold?: number;
90
+ resetTimeoutMs?: number;
91
+ halfOpenMaxCalls?: number;
92
+ }
93
+ declare class CircuitBreaker {
94
+ private state;
95
+ private failureCount;
96
+ private successCount;
97
+ private lastFailureAt;
98
+ private halfOpenCalls;
99
+ private readonly failureThreshold;
100
+ private readonly resetTimeoutMs;
101
+ private readonly halfOpenMaxCalls;
102
+ constructor(options?: CircuitBreakerOptions);
103
+ record(success: boolean): void;
104
+ canExecute(): boolean;
105
+ wrap<T>(fn: () => Promise<T>): Promise<T>;
106
+ getState(): CircuitState;
107
+ getFailureCount(): number;
108
+ reset(): void;
109
+ }
110
+
111
+ export { ChatWidget, ChatWidgetProps, ChatWindow, ChatWindowProps, CircuitBreaker, type CircuitBreakerOptions, ClientConfig, CodeViewer, ConfigProvider, DocumentUpload, DocumentUploadProps, MessageBubble, MessageBubbleProps, ObservabilityPanel, ObservabilityTrace, ProductCard, ProductCardProps, ProductCarousel, ProductCarouselProps, SourceCard, SourceCardProps, UseRagChatOptions, UseRagChatReturn, addSynonyms, useConfig, useRagChat };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,48 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { C as ChatWidgetProps, a as ChatWindowProps, D as DocumentUploadProps, M as MessageBubbleProps, S as SourceCardProps, b as ConfigProviderProps, c as ClientConfig, P as ProductCardProps, d as ProductCarouselProps } from './LicenseValidator-CsjJp2PP.js';
3
- export { A as AuthenticationException, e as ChartType, f as Chunk, g as ChunkOptions, h as ConfigurationException, i as DecisionContext, E as EmbeddingFailedException, I as IRenderRule, j as IRendererStrategy, k as IntentCategory, l as IntentClassifier, L as LicenseValidationError, m as LicenseValidationRequest, n as LicenseValidationResponse, o as LicenseValidator, p as ProviderNotFoundException, R as RateLimitException, q as RenderDecision, r as RenderType, s as RendererRegistry, t as RetrievalException, u as Retrivora, v as RetrivoraError, w as RetrivoraErrorCode, x as RuleEngine, y as SDKVersionUnsupportedError, z as SDK_VERSION, V as VisualizationDecisionEngine, B as decideVisualization } from './LicenseValidator-CsjJp2PP.js';
2
+ import { C as ChatWidgetProps, a as ChatWindowProps, D as DocumentUploadProps, M as MessageBubbleProps, S as SourceCardProps, b as ConfigProviderProps, c as ClientConfig, P as ProductCardProps, d as ProductCarouselProps } from './BatchProcessor-BfzuU4cK.js';
3
+ export { A as AuthenticationException, B as BatchOptions, e as BatchProcessor, f as BatchResult, g as ChartType, h as Chunk, i as ChunkOptions, j as ConfigurationException, k as DecisionContext, E as EmbeddingFailedException, I as IRenderRule, l as IRendererStrategy, m as IntentCategory, n as IntentClassifier, L as LicenseValidationError, o as LicenseValidationRequest, p as LicenseValidationResponse, q as LicenseValidator, r as ProviderNotFoundException, R as RateLimitException, s as RenderDecision, t as RenderType, u as RendererRegistry, v as RetrievalException, w as Retrivora, x as RetrivoraError, y as RetrivoraErrorCode, z as RuleEngine, F as SDKVersionUnsupportedError, G as SDK_VERSION, V as VisualizationDecisionEngine, H as decideVisualization, J as isTransientError } from './BatchProcessor-BfzuU4cK.js';
4
4
  import { O as ObservabilityTrace, U as UseRagChatOptions, a as UseRagChatReturn } from './ILLMProvider-teTNQ1lh.js';
5
5
  export { C as ChatMessage, b as ChatOptions, c as ChatResponse, E as EmbedOptions, d as EmbeddingConfig, e as EmbeddingProvider, I as ILLMProvider, f as IngestDocument, L as LLMConfig, g as LLMProvider, h as LatencyBreakdown, R as RAGConfig, i as RagConfig, j as RagMessage, k as RetrievalConfig, l as RetrievedChunk, T as TokenUsage, m as UIConfig, n as UniversalRagConfig, o as UpsertDocument, V as VectorDBConfig, p as VectorDBProvider, q as VectorMatch, W as WorkflowConfig } from './ILLMProvider-teTNQ1lh.js';
6
6
  import 'react';
7
7
 
8
+ /**
9
+ * ChatWidget — Floating Action Button (FAB) that toggles the chat window.
10
+ *
11
+ * Responsibilities:
12
+ * - Validates the Retrivora license key BEFORE allowing the chat to open
13
+ * - Proactively validates on mount to visually lock the widget when no
14
+ * valid license is present (TERMINATED / SUSPENDED / missing)
15
+ * - Manages window resize, maximize, and visual positioning
16
+ * - Shows an error toast when license validation fails on user attempt
17
+ *
18
+ * License key resolution order (highest to lowest priority):
19
+ * 1. Explicit `licenseKey` prop
20
+ * 2. `x-license-key` header (from `headers` prop)
21
+ * 3. `Authorization: Bearer <key>` header (from `headers` prop)
22
+ * 4. Environment variables `NEXT_PUBLIC_RETRIVORA_LICENSE_KEY` / `RETRIVORA_LICENSE_KEY`
23
+ *
24
+ * @param props - Widget position, callbacks, API overrides, and license overrides
25
+ */
8
26
  declare function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, licenseKey: licenseKeyProp, headers }: ChatWidgetProps): react_jsx_runtime.JSX.Element | null;
9
27
 
28
+ /**
29
+ * ChatWindow component.
30
+ *
31
+ * @param className - Additional CSS class for the outer wrapper.
32
+ * @param style - Inline styles for the outer wrapper.
33
+ * @param onClose - Callback for the close (X) button (widget mode only).
34
+ * @param showClose - Whether to render the close button.
35
+ * @param onResizeStart - Callback fired when user begins dragging the resize handle.
36
+ * @param onResetResize - Callback fired when the reset-size button is clicked.
37
+ * @param isResized - True if the window has been resized away from defaults.
38
+ * @param onMaximize - Callback for the maximize/minimize toggle button.
39
+ * @param isMaximized - True if the window is currently maximized.
40
+ * @param onAddToCart - Callback fired when user clicks "Add to Cart" on a product card.
41
+ * @param apiUrl - Override URL for the chat endpoint (bypasses retrivoraApiBase).
42
+ * @param retrivoraApiBase - Base URL for Retrivora catch-all endpoints (chat/suggestions/history/etc).
43
+ * @param licenseKey - Override license key (highest priority; falls back to headers/env).
44
+ * @param headers - Custom headers forwarded with every network request.
45
+ */
10
46
  declare function ChatWindow({ className, style, onClose, showClose, onResizeStart, onResetResize, isResized, onMaximize, isMaximized, onAddToCart, apiUrl, retrivoraApiBase, licenseKey: licenseKeyProp, headers }: ChatWindowProps): react_jsx_runtime.JSX.Element;
11
47
 
12
48
  declare function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploadComplete, className }: DocumentUploadProps): react_jsx_runtime.JSX.Element;
@@ -48,4 +84,28 @@ declare function useRagChat(projectId: string, options?: UseRagChatOptions): Use
48
84
  */
49
85
  declare function addSynonyms(customSynonyms: Record<string, string[]>): void;
50
86
 
51
- export { ChatWidget, ChatWidgetProps, ChatWindow, ChatWindowProps, ClientConfig, CodeViewer, ConfigProvider, DocumentUpload, DocumentUploadProps, MessageBubble, MessageBubbleProps, ObservabilityPanel, ObservabilityTrace, ProductCard, ProductCardProps, ProductCarousel, ProductCarouselProps, SourceCard, SourceCardProps, UseRagChatOptions, UseRagChatReturn, addSynonyms, useConfig, useRagChat };
87
+ type CircuitState = 'closed' | 'open' | 'half-open';
88
+ interface CircuitBreakerOptions {
89
+ failureThreshold?: number;
90
+ resetTimeoutMs?: number;
91
+ halfOpenMaxCalls?: number;
92
+ }
93
+ declare class CircuitBreaker {
94
+ private state;
95
+ private failureCount;
96
+ private successCount;
97
+ private lastFailureAt;
98
+ private halfOpenCalls;
99
+ private readonly failureThreshold;
100
+ private readonly resetTimeoutMs;
101
+ private readonly halfOpenMaxCalls;
102
+ constructor(options?: CircuitBreakerOptions);
103
+ record(success: boolean): void;
104
+ canExecute(): boolean;
105
+ wrap<T>(fn: () => Promise<T>): Promise<T>;
106
+ getState(): CircuitState;
107
+ getFailureCount(): number;
108
+ reset(): void;
109
+ }
110
+
111
+ export { ChatWidget, ChatWidgetProps, ChatWindow, ChatWindowProps, CircuitBreaker, type CircuitBreakerOptions, ClientConfig, CodeViewer, ConfigProvider, DocumentUpload, DocumentUploadProps, MessageBubble, MessageBubbleProps, ObservabilityPanel, ObservabilityTrace, ProductCard, ProductCardProps, ProductCarousel, ProductCarouselProps, SourceCard, SourceCardProps, UseRagChatOptions, UseRagChatReturn, addSynonyms, useConfig, useRagChat };