@retrivora-ai/rag-engine 2.6.2 → 2.6.3

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 (49) hide show
  1. package/dist/ChromaDBProvider-NDA2IBOH.mjs +8 -0
  2. package/dist/MilvusProvider-H6GGL5FQ.mjs +8 -0
  3. package/dist/MongoDBProvider-KC3GF3FH.mjs +8 -0
  4. package/dist/MultiTablePostgresProvider-6LJBFZL2.mjs +9 -0
  5. package/dist/PineconeProvider-22RF2QPF.mjs +10 -0
  6. package/dist/PineconeProvider-HBBIXLT3.mjs +10 -0
  7. package/dist/PostgreSQLProvider-VWFL4OIP.mjs +8 -0
  8. package/dist/QdrantProvider-UU7RGXBI.mjs +8 -0
  9. package/dist/RedisProvider-MIIPSAAE.mjs +8 -0
  10. package/dist/SimpleGraphProvider-HJIS4S7Y.mjs +70 -0
  11. package/dist/UniversalVectorProvider-NO3L255G.mjs +9 -0
  12. package/dist/WeaviateProvider-YRZDZFAC.mjs +8 -0
  13. package/dist/chunk-23PFNEBF.mjs +107 -0
  14. package/dist/chunk-3E4GZGDX.mjs +10851 -0
  15. package/dist/chunk-3SQ4DODU.mjs +238 -0
  16. package/dist/chunk-AHMMUZ4W.mjs +152 -0
  17. package/dist/chunk-ASBNNEVI.mjs +81 -0
  18. package/dist/chunk-AT4TFUQN.mjs +219 -0
  19. package/dist/chunk-BEPLYQBS.mjs +89 -0
  20. package/dist/chunk-G7MJRFCO.mjs +340 -0
  21. package/dist/chunk-IHWKVAUR.mjs +112 -0
  22. package/dist/chunk-IMP6FUCY.mjs +30 -0
  23. package/dist/chunk-LFNV6DEL.mjs +281 -0
  24. package/dist/chunk-MAXMVO7B.mjs +211 -0
  25. package/dist/chunk-MGJ6V2IT.mjs +203 -0
  26. package/dist/chunk-N3TI27LG.mjs +334 -0
  27. package/dist/chunk-NWYE4Q7B.mjs +334 -0
  28. package/dist/chunk-OJMAT4EG.mjs +219 -0
  29. package/dist/chunk-QKZM3RSJ.mjs +10851 -0
  30. package/dist/chunk-QUY3E6HJ.mjs +168 -0
  31. package/dist/chunk-SG6XYLQE.mjs +53 -0
  32. package/dist/chunk-UT6SZZEC.mjs +69 -0
  33. package/dist/chunk-VW3U4MMX.mjs +157 -0
  34. package/dist/chunk-WOJCOTXI.mjs +281 -0
  35. package/dist/chunk-XP6NJMX4.mjs +168 -0
  36. package/dist/chunk-XYBKDJDW.mjs +696 -0
  37. package/dist/handlers/index.d.mts +1 -1
  38. package/dist/handlers/index.d.ts +1 -1
  39. package/dist/handlers/index.js +56 -23
  40. package/dist/handlers/index.mjs +24 -14027
  41. package/dist/{index-D7FuQRSb.d.mts → index-BBbt5A2y.d.mts} +3 -1
  42. package/dist/{index-CFl4KrKq.d.ts → index-BZ_rR6V8.d.ts} +3 -1
  43. package/dist/index.js +12 -4
  44. package/dist/index.mjs +46 -1461
  45. package/dist/server.d.mts +2 -2
  46. package/dist/server.d.ts +2 -2
  47. package/dist/server.js +56 -23
  48. package/dist/server.mjs +377 -14573
  49. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,35 +1,41 @@
1
1
  "use client";
2
- var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __spreadValues = (a, b) => {
10
- for (var prop in b || (b = {}))
11
- if (__hasOwnProp.call(b, prop))
12
- __defNormalProp(a, prop, b[prop]);
13
- if (__getOwnPropSymbols)
14
- for (var prop of __getOwnPropSymbols(b)) {
15
- if (__propIsEnum.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- }
18
- return a;
19
- };
20
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
- var __objRest = (source, exclude) => {
22
- var target = {};
23
- for (var prop in source)
24
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
25
- target[prop] = source[prop];
26
- if (source != null && __getOwnPropSymbols)
27
- for (var prop of __getOwnPropSymbols(source)) {
28
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
29
- target[prop] = source[prop];
30
- }
31
- return target;
32
- };
2
+ import {
3
+ LicenseValidator
4
+ } from "./chunk-AT4TFUQN.mjs";
5
+ import {
6
+ AuthenticationException,
7
+ BatchProcessor,
8
+ ConfigurationException,
9
+ EmbeddingFailedException,
10
+ LicenseValidationError,
11
+ ProviderNotFoundException,
12
+ RateLimitException,
13
+ RetrievalException,
14
+ RetrivoraError,
15
+ SDKVersionUnsupportedError,
16
+ isTransientError
17
+ } from "./chunk-XYBKDJDW.mjs";
18
+ import {
19
+ mergeDefined
20
+ } from "./chunk-SG6XYLQE.mjs";
21
+ import {
22
+ ConfigFetcher,
23
+ createDefaultProjectSettings,
24
+ normalizeProjectSettings,
25
+ projectSettingsToUiConfig
26
+ } from "./chunk-N3TI27LG.mjs";
27
+ import {
28
+ SDK_VERSION
29
+ } from "./chunk-XP6NJMX4.mjs";
30
+ import {
31
+ addSynonyms,
32
+ resolveMetadataValue
33
+ } from "./chunk-BEPLYQBS.mjs";
34
+ import {
35
+ __objRest,
36
+ __spreadProps,
37
+ __spreadValues
38
+ } from "./chunk-UT6SZZEC.mjs";
33
39
 
34
40
  // #style-inject:#style-inject
35
41
  function styleInject(css, { insertAt } = {}) {
@@ -90,20 +96,6 @@ import { Upload, File, X, AlertCircle, CheckCircle2, Sparkles, Files, RefreshCw
90
96
  // src/components/ConfigProvider.tsx
91
97
  import { createContext, useContext, useEffect, useMemo, useState } from "react";
92
98
 
93
- // src/utils/templateUtils.ts
94
- function mergeDefined(base, override) {
95
- const merged = __spreadValues({}, base || {});
96
- if (!override) {
97
- return merged;
98
- }
99
- for (const [key, value] of Object.entries(override)) {
100
- if (value !== void 0 && value !== null && value !== "") {
101
- merged[key] = value;
102
- }
103
- }
104
- return merged;
105
- }
106
-
107
99
  // src/config/uiConstants.ts
108
100
  var DEFAULT_CONFIG = {
109
101
  projectId: "default",
@@ -140,1022 +132,6 @@ var CHAT_SUGGESTIONS = [
140
132
  "Show me an example"
141
133
  ];
142
134
 
143
- // src/core/ProjectSettings.ts
144
- var DEFAULT_LIFECYCLE_HOOKS = [
145
- "beforeInitialize",
146
- "afterInitialize",
147
- "beforeSend",
148
- "afterResponse",
149
- "onMessage",
150
- "onCitationClick",
151
- "onFeedback",
152
- "onError",
153
- "onReconnect",
154
- "onFileUpload"
155
- ];
156
- var DEFAULT_CONVERSATION_FEATURES = [
157
- "History",
158
- "Resume",
159
- "Search",
160
- "Export",
161
- "Rename",
162
- "Delete",
163
- "Tags",
164
- "Pinned",
165
- "Unread",
166
- "Ratings"
167
- ];
168
- function createDefaultProjectSettings(projectId) {
169
- return {
170
- projectId,
171
- branding: {
172
- companyName: "Retrivora AI",
173
- botName: "Retrivora Assistant",
174
- welcomeMessage: "Hi, I can help you search your knowledge base.",
175
- primaryColor: "#6366f1",
176
- secondaryColor: "#8b5cf6",
177
- fontFamily: "Inter",
178
- borderRadius: 14,
179
- logoUrl: "",
180
- avatarUrl: "",
181
- customCss: ""
182
- },
183
- ai: {
184
- defaultModel: "llama-3.1-8b-instant",
185
- embeddingModel: "text-embedding-3-small",
186
- systemPrompt: "Answer using the connected knowledge base. Cite sources when available.",
187
- memoryEnabled: true,
188
- multiModelEnabled: true,
189
- citationsEnabled: true,
190
- fileUploadEnabled: true
191
- },
192
- auth: {
193
- mode: "public",
194
- allowedOrigins: [],
195
- requireVerifiedEmail: false,
196
- sessionTtlMinutes: 1440
197
- },
198
- widget: {
199
- position: "bottom-right",
200
- theme: "light",
201
- lazyLoad: true,
202
- autoReconnect: true,
203
- persistConversations: true,
204
- showRetrivoraBranding: false
205
- },
206
- telemetry: {
207
- enabled: true,
208
- collectBrowser: true,
209
- collectCountry: false,
210
- redactPii: true,
211
- retentionDays: 30
212
- },
213
- lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
214
- conversationFeatures: DEFAULT_CONVERSATION_FEATURES
215
- };
216
- }
217
- function cleanString(value, fallback, maxLength = 2e3) {
218
- if (typeof value !== "string") return fallback;
219
- return value.trim().slice(0, maxLength);
220
- }
221
- function cleanBoolean(value, fallback) {
222
- return typeof value === "boolean" ? value : fallback;
223
- }
224
- function cleanNumber(value, fallback, min, max) {
225
- const num = typeof value === "number" ? value : Number(value);
226
- if (!Number.isFinite(num)) return fallback;
227
- return Math.min(Math.max(Math.round(num), min), max);
228
- }
229
- function cleanEnum(value, fallback, allowed) {
230
- return typeof value === "string" && allowed.includes(value) ? value : fallback;
231
- }
232
- function cleanStringList(value, fallback, maxItems = 20) {
233
- if (!Array.isArray(value)) return fallback;
234
- const cleaned = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, maxItems);
235
- return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
236
- }
237
- function normalizeProjectSettings(projectId, input) {
238
- const defaults = createDefaultProjectSettings(projectId);
239
- const branding = (input == null ? void 0 : input.branding) || {};
240
- const ai = (input == null ? void 0 : input.ai) || {};
241
- const auth = (input == null ? void 0 : input.auth) || {};
242
- const widget = (input == null ? void 0 : input.widget) || {};
243
- const telemetry = (input == null ? void 0 : input.telemetry) || {};
244
- return {
245
- projectId,
246
- branding: {
247
- companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
248
- botName: cleanString(branding.botName, defaults.branding.botName, 120),
249
- welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
250
- primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
251
- secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
252
- fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
253
- borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
254
- logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
255
- avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
256
- customCss: cleanString(branding.customCss, defaults.branding.customCss, 5e3)
257
- },
258
- ai: {
259
- defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
260
- embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
261
- systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5e3),
262
- memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
263
- multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
264
- citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
265
- fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled)
266
- },
267
- auth: {
268
- mode: cleanEnum(auth.mode, defaults.auth.mode, ["public", "anonymous", "jwt", "oauth", "okta", "auth0", "supabase", "firebase", "sso", "custom_token"]),
269
- allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
270
- requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
271
- sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200)
272
- },
273
- widget: {
274
- position: cleanEnum(widget.position, defaults.widget.position, ["bottom-right", "bottom-left", "top-right", "top-left"]),
275
- theme: cleanEnum(widget.theme, defaults.widget.theme, ["light", "dark", "system"]),
276
- lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
277
- autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
278
- persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
279
- showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding)
280
- },
281
- telemetry: {
282
- enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
283
- collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
284
- collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
285
- redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
286
- retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365)
287
- },
288
- lifecycleHooks: cleanStringList(input == null ? void 0 : input.lifecycleHooks, defaults.lifecycleHooks, 30),
289
- conversationFeatures: cleanStringList(input == null ? void 0 : input.conversationFeatures, defaults.conversationFeatures, 30),
290
- updatedAt: input == null ? void 0 : input.updatedAt
291
- };
292
- }
293
- function projectSettingsToUiConfig(settings) {
294
- return {
295
- title: settings.branding.botName,
296
- subtitle: settings.branding.companyName,
297
- primaryColor: settings.branding.primaryColor,
298
- accentColor: settings.branding.secondaryColor,
299
- logoUrl: settings.branding.logoUrl || settings.branding.avatarUrl,
300
- welcomeMessage: settings.branding.welcomeMessage,
301
- poweredBy: settings.widget.showRetrivoraBranding ? "Retrivora AI" : "",
302
- allowUpload: settings.ai.fileUploadEnabled,
303
- showSources: settings.ai.citationsEnabled,
304
- borderRadius: settings.branding.borderRadius <= 4 ? "sm" : settings.branding.borderRadius <= 8 ? "md" : settings.branding.borderRadius <= 16 ? "xl" : "full"
305
- };
306
- }
307
-
308
- // package.json
309
- var package_default = {
310
- name: "@retrivora-ai/rag-engine",
311
- version: "2.6.2",
312
- description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
313
- author: "Abhinav Alkuchi",
314
- license: "UNLICENSED",
315
- keywords: [
316
- "rag",
317
- "retrieval-augmented-generation",
318
- "chatbot",
319
- "vector-database",
320
- "pinecone",
321
- "pgvector",
322
- "postgresql",
323
- "milvus",
324
- "qdrant",
325
- "chromadb",
326
- "redis",
327
- "weaviate",
328
- "mongodb",
329
- "openai",
330
- "anthropic",
331
- "ollama",
332
- "nextjs",
333
- "react",
334
- "ai",
335
- "llm",
336
- "embeddings"
337
- ],
338
- main: "dist/index.js",
339
- module: "dist/index.mjs",
340
- types: "dist/index.d.ts",
341
- exports: {
342
- ".": {
343
- types: "./dist/index.d.ts",
344
- require: "./dist/index.js",
345
- import: "./dist/index.mjs"
346
- },
347
- "./style.css": "./dist/index.css",
348
- "./style.min.css": "./dist/index.min.css",
349
- "./index.css": "./dist/index.css",
350
- "./index.min.css": "./dist/index.min.css",
351
- "./styles.css": "./dist/index.css",
352
- "./styles.min.css": "./dist/index.min.css",
353
- "./handlers": {
354
- types: "./dist/handlers/index.d.ts",
355
- require: "./dist/handlers/index.js",
356
- import: "./dist/handlers/index.mjs"
357
- },
358
- "./server": {
359
- types: "./dist/server.d.ts",
360
- require: "./dist/server.js",
361
- import: "./dist/server.mjs"
362
- }
363
- },
364
- browser: {
365
- child_process: false,
366
- fs: false,
367
- net: false,
368
- tls: false,
369
- crypto: false,
370
- os: false,
371
- path: false,
372
- stream: false,
373
- http: false,
374
- https: false,
375
- zlib: false,
376
- mongodb: false,
377
- pg: false,
378
- "pdf-parse": false,
379
- mammoth: false
380
- },
381
- files: [
382
- "dist",
383
- "README.md",
384
- "FREE_TIER_ARCHITECTURE.md"
385
- ],
386
- scripts: {
387
- dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
388
- build: "npm run build:pkg",
389
- "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.min.css --minify",
390
- lint: "eslint",
391
- typecheck: "tsc --noEmit -p tsconfig.build.json",
392
- test: "jest",
393
- clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`
394
- },
395
- peerDependencies: {
396
- axios: ">=1.0.0",
397
- next: ">=15.0.0",
398
- react: ">=18.0.0",
399
- "react-dom": ">=18.0.0"
400
- },
401
- peerDependenciesMeta: {
402
- axios: {
403
- optional: true
404
- },
405
- next: {
406
- optional: true
407
- }
408
- },
409
- dependencies: {
410
- "@anthropic-ai/sdk": "^0.95.1",
411
- "@google/genai": "^0.8.0",
412
- "@google/generative-ai": "^0.24.1",
413
- "@pinecone-database/pinecone": "^7.2.0",
414
- "@retrivora-ai/billing-guards": "file:../billing-guards",
415
- "@types/papaparse": "^5.5.2",
416
- exceljs: "^4.4.0",
417
- "framer-motion": "^13.1.0",
418
- jszip: "^3.10.1",
419
- katex: "^0.18.4",
420
- "lucide-react": "^1.8.0",
421
- "next-themes": "^0.4.6",
422
- openai: "^6.34.0",
423
- papaparse: "^5.5.3",
424
- "react-is": "^18.3.1",
425
- "react-markdown": "^10.1.0",
426
- "react-syntax-highlighter": "^16.1.1",
427
- recharts: "^3.8.1",
428
- "rehype-katex": "^7.0.1",
429
- "remark-gfm": "^4.0.1",
430
- "remark-math": "^6.0.0",
431
- xlsx: "^0.18.5",
432
- zod: "^4.4.3"
433
- },
434
- optionalDependencies: {
435
- "@langchain/core": "^1.1.42",
436
- "@langchain/openai": "^1.4.5",
437
- langchain: "^1.3.5",
438
- llamaindex: "^0.11.9",
439
- mammoth: "^1.8.0",
440
- mongodb: "^7.1.1",
441
- "pdf-parse": "^1.1.1",
442
- pg: "^8.20.0"
443
- },
444
- devDependencies: {
445
- "@tailwindcss/cli": "^4",
446
- "@tailwindcss/postcss": "^4",
447
- "@types/estree": "^1.0.9",
448
- "@types/jest": "^30.0.0",
449
- "@types/jszip": "^3.4.1",
450
- "@types/katex": "^0.16.8",
451
- "@types/node": "^20",
452
- "@types/pdf-parse": "^1.1.5",
453
- "@types/pg": "^8.20.0",
454
- "@types/react": "^19.2.14",
455
- "@types/react-dom": "^19.2.3",
456
- "@types/react-syntax-highlighter": "^15.5.13",
457
- axios: "^1.15.0",
458
- dotenv: "^17.4.2",
459
- eslint: "^9",
460
- "eslint-config-next": "16.3.2",
461
- jest: "^30.4.2",
462
- next: "^16.3.2",
463
- tailwindcss: "^4",
464
- "ts-jest": "^29.4.12",
465
- tsup: "^8.5.1",
466
- typescript: "^5"
467
- }
468
- };
469
-
470
- // src/version.ts
471
- var SDK_VERSION = package_default.version || "2.1.3";
472
-
473
- // src/core/ConfigFetcher.ts
474
- var CONTROL_PLANE_URL = "https://www.retrivora.com";
475
- var LLM_PROXY_BASE_URL = "https://llm.retrivora.com/api/v1";
476
- var ConfigFetcher = class {
477
- // 5-minute in-memory session cache
478
- /**
479
- * Fetch full project configuration (vectorDb + embedding + llm + workspace) from Retrivora Control Plane.
480
- *
481
- * The SDK calls https://www.retrivora.com/api/v1/config with the project ID and license key.
482
- * The server validates the license against the database and returns:
483
- * - validity (tier, isActive, expiresAt)
484
- * - LLM model info
485
- * - embedding model info
486
- * - Pinecone index name and workspace/namespace
487
- *
488
- * The Pinecone API key is NOT returned (server-only). The SDK uses local
489
- * PINECONE_API_KEY if available, or vector operations are handled server-side.
490
- */
491
- static async fetchRemoteConfig(projectId, licenseKey) {
492
- const cacheKey = `${projectId}:${licenseKey || ""}`;
493
- const now = Date.now();
494
- const cached = this.cache.get(cacheKey);
495
- if (cached && now - cached.cachedAt < this.TTL_MS) {
496
- return cached.config;
497
- }
498
- const existingInflight = this.inflight.get(cacheKey);
499
- if (existingInflight) {
500
- return existingInflight;
501
- }
502
- const promise = this._doFetch(projectId, licenseKey, cacheKey, now);
503
- this.inflight.set(cacheKey, promise);
504
- try {
505
- return await promise;
506
- } finally {
507
- this.inflight.delete(cacheKey);
508
- }
509
- }
510
- /** Internal: performs the actual HTTP fetch. Shared by all callers via inflight dedup. */
511
- static async _doFetch(projectId, licenseKey, cacheKey, now) {
512
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
513
- const controlPlaneUrls = [
514
- process.env.RETRIVORA_CONTROL_PLANE_URL,
515
- process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
516
- CONTROL_PLANE_URL
517
- ].filter((url) => {
518
- if (!url) return false;
519
- const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
520
- if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
521
- return true;
522
- }).map((url) => url.replace(/\/$/, ""));
523
- for (const baseUrl of controlPlaneUrls) {
524
- try {
525
- const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
526
- const res = await fetch(url, {
527
- method: "GET",
528
- headers: __spreadValues(__spreadValues({
529
- "Content-Type": "application/json",
530
- "x-sdk-version": SDK_VERSION
531
- }, licenseKey ? { "x-license-key": licenseKey } : {}), projectId ? { "x-project-id": projectId } : {})
532
- });
533
- if (!res.ok) {
534
- console.warn(`[ConfigFetcher] Error text: ${await res.text()}`);
535
- }
536
- if (res.ok) {
537
- const data = await res.json();
538
- if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
539
- const fetchedProjectId = data.projectId || projectId;
540
- const config = {
541
- projectId: fetchedProjectId,
542
- tier: data.tier,
543
- isActive: data.isActive,
544
- expiresAt: data.expiresAt,
545
- vectorDb: {
546
- // Fetch apiKey from credentials API if available, else fallback to empty
547
- apiKey: data.vectorDb.apiKey || "",
548
- indexName: data.vectorDb.indexName || "retrivora-free",
549
- provider: data.vectorDb.provider || "pinecone",
550
- projectId: fetchedProjectId,
551
- namespace: ((_a = data.workspace) == null ? void 0 : _a.namespace) || data.vectorDb.namespace || fetchedProjectId
552
- },
553
- embedding: {
554
- provider: ((_b = data.embedding) == null ? void 0 : _b.provider) || "universal_rest",
555
- model: ((_c = data.embedding) == null ? void 0 : _c.model) || "text-embedding-004",
556
- // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
557
- baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || LLM_PROXY_BASE_URL,
558
- apiKey: ((_e = data.embedding) == null ? void 0 : _e.apiKey) || licenseKey || "",
559
- profile: ((_f = data.embedding) == null ? void 0 : _f.profile) || "litellm"
560
- },
561
- llm: {
562
- provider: ((_g = data.llm) == null ? void 0 : _g.provider) || "universal_rest",
563
- model: ((_h = data.llm) == null ? void 0 : _h.model) || "llama-3.1-8b-instant",
564
- // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
565
- baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || LLM_PROXY_BASE_URL,
566
- apiKey: ((_j = data.llm) == null ? void 0 : _j.apiKey) || licenseKey || "",
567
- profile: ((_k = data.llm) == null ? void 0 : _k.profile) || "litellm"
568
- },
569
- workspace: data.workspace || {
570
- namespace: fetchedProjectId,
571
- indexName: data.vectorDb.indexName || "retrivora-free"
572
- },
573
- projectSettings: normalizeProjectSettings(
574
- fetchedProjectId,
575
- data.projectSettings || data.settings
576
- )
577
- };
578
- if (licenseKey) {
579
- try {
580
- const credUrl = `${baseUrl}/api/v1/credentials`;
581
- const credRes = await fetch(credUrl, {
582
- method: "POST",
583
- headers: __spreadValues(__spreadValues({
584
- "Content-Type": "application/json"
585
- }, licenseKey ? { "x-license-key": licenseKey } : {}), fetchedProjectId ? { "x-project-id": fetchedProjectId } : {}),
586
- body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
587
- });
588
- if (credRes.ok) {
589
- const credData = await credRes.json();
590
- if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
591
- if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
592
- config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
593
- }
594
- if (credData.credentials.litellmApiKey) {
595
- config.llm.apiKey = credData.credentials.litellmApiKey;
596
- config.embedding.apiKey = credData.credentials.litellmApiKey;
597
- }
598
- }
599
- }
600
- } catch (e) {
601
- console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
602
- }
603
- }
604
- this.cache.set(cacheKey, { config, cachedAt: now });
605
- return config;
606
- }
607
- }
608
- } catch (err) {
609
- console.warn(
610
- `[ConfigFetcher] Failed to fetch config from ${baseUrl}:`,
611
- err instanceof Error ? err.message : String(err)
612
- );
613
- }
614
- }
615
- return null;
616
- }
617
- /** Convenience: fetch only vector DB config (backwards compat). */
618
- static async fetchRemoteVectorConfig(projectId, licenseKey) {
619
- var _a;
620
- const config = await this.fetchRemoteConfig(projectId, licenseKey);
621
- return (_a = config == null ? void 0 : config.vectorDb) != null ? _a : null;
622
- }
623
- };
624
- ConfigFetcher.cache = /* @__PURE__ */ new Map();
625
- /** In-flight deduplication: concurrent callers for the same key share one network request */
626
- ConfigFetcher.inflight = /* @__PURE__ */ new Map();
627
- ConfigFetcher.TTL_MS = 5 * 60 * 1e3;
628
-
629
- // src/exceptions/index.ts
630
- var RetrivoraError = class extends Error {
631
- constructor(message, code, details) {
632
- super(message);
633
- this.name = new.target.name;
634
- this.code = code;
635
- this.details = details;
636
- }
637
- };
638
- var ProviderNotFoundException = class extends RetrivoraError {
639
- constructor(providerType, provider, details) {
640
- super(`Unsupported ${providerType} provider: ${provider}`, "PROVIDER_NOT_FOUND", details);
641
- }
642
- };
643
- var EmbeddingFailedException = class extends RetrivoraError {
644
- constructor(message = "Embedding generation failed", details) {
645
- super(message, "EMBEDDING_FAILED", details);
646
- }
647
- };
648
- var RetrievalException = class extends RetrivoraError {
649
- constructor(message = "Retrieval failed", details) {
650
- super(message, "RETRIEVAL_FAILED", details);
651
- }
652
- };
653
- var RateLimitException = class extends RetrivoraError {
654
- constructor(message = "Provider rate limit exceeded", details) {
655
- super(message, "RATE_LIMITED", details);
656
- }
657
- };
658
- var ConfigurationException = class extends RetrivoraError {
659
- constructor(message, details) {
660
- super(message, "CONFIGURATION_ERROR", details);
661
- }
662
- };
663
- var AuthenticationException = class extends RetrivoraError {
664
- constructor(message = "Provider authentication failed", details) {
665
- super(message, "AUTHENTICATION_ERROR", details);
666
- }
667
- };
668
- var SDKVersionUnsupportedError = class extends RetrivoraError {
669
- constructor(message = "This SDK version is no longer supported.", details) {
670
- super(message, "SDK_VERSION_UNSUPPORTED", details);
671
- }
672
- };
673
- var LicenseValidationError = class extends RetrivoraError {
674
- constructor(message = "License validation failed.", details) {
675
- super(message, "LICENSE_VALIDATION_ERROR", details);
676
- }
677
- };
678
-
679
- // src/core/LicenseVerifier.ts
680
- function decodeBase64UrlToUtf8(b64url) {
681
- const normalized = b64url.replace(/-/g, "+").replace(/_/g, "/");
682
- const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
683
- if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
684
- return Buffer.from(padded, "base64").toString("utf8");
685
- }
686
- if (typeof atob === "function") {
687
- const binary = atob(padded);
688
- const bytes = new Uint8Array(binary.length);
689
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
690
- return new TextDecoder().decode(bytes);
691
- }
692
- throw new Error("Base64 decoding is not supported in this environment.");
693
- }
694
- var _LicenseVerifier = class _LicenseVerifier {
695
- // Cache verified license for 5 minutes
696
- /**
697
- * Computes a deterministic hardware fingerprint to enforce node-locked licensing.
698
- */
699
- static async generateMachineFingerprint() {
700
- if (typeof window !== "undefined" && typeof navigator !== "undefined") {
701
- return "browser-client";
702
- }
703
- try {
704
- const os = await import("os");
705
- const crypto = await import("crypto");
706
- const interfaces = os.networkInterfaces();
707
- const macAddresses = [];
708
- for (const name of Object.keys(interfaces)) {
709
- for (const iface of interfaces[name] || []) {
710
- if (!iface.internal && iface.mac && iface.mac !== "00:00:00:00:00:00") {
711
- macAddresses.push(iface.mac);
712
- }
713
- }
714
- }
715
- const rawData = [
716
- macAddresses.sort().join(","),
717
- os.platform(),
718
- os.arch(),
719
- os.hostname()
720
- ].join("|");
721
- return crypto.createHash("sha256").update(rawData).digest("hex");
722
- } catch (err) {
723
- return "fallback-fingerprint-failed";
724
- }
725
- }
726
- /**
727
- * Validates the license key asynchronously by calling the Retrivora backend.
728
- *
729
- * @param licenseKey - Base64url signed JWT license key.
730
- * @param currentProjectId - Project namespace ID.
731
- * @param provider - Optional provider for tier checks.
732
- */
733
- static async verifyAsync(licenseKey, currentProjectId, provider) {
734
- const isProduction = process.env.NODE_ENV === "production";
735
- const now = Date.now();
736
- if (!licenseKey) {
737
- if (isProduction) {
738
- throw new ConfigurationException(
739
- "[Retrivora SDK] License key (licenseKey) is required in production environments."
740
- );
741
- }
742
- console.warn(
743
- `\x1B[33m[Retrivora SDK] WARNING: Running without a license key. This namespace (${currentProjectId}) is permitted for local development only.\x1B[0m`
744
- );
745
- return {
746
- projectId: currentProjectId,
747
- expiresAt: Math.floor(Date.now() / 1e3) + 86400,
748
- // Valid for 24h
749
- tier: "hobby"
750
- };
751
- }
752
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
753
- const cached = this.cache.get(cacheKey);
754
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
755
- const currentTimestampSec = Math.floor(now / 1e3);
756
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
757
- this.cache.delete(cacheKey);
758
- } else {
759
- return cached.payload;
760
- }
761
- }
762
- try {
763
- let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
764
- if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
765
- baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
766
- }
767
- const endpoint = `${baseUrl}/api/v1/license/validate`;
768
- let response;
769
- const machineFingerprint = await this.generateMachineFingerprint();
770
- try {
771
- response = await fetch(endpoint, {
772
- method: "POST",
773
- signal: AbortSignal.timeout(6e3),
774
- headers: {
775
- "Content-Type": "application/json",
776
- "x-license-key": licenseKey
777
- },
778
- body: JSON.stringify({
779
- licenseKey,
780
- projectId: currentProjectId,
781
- provider,
782
- machineFingerprint
783
- })
784
- });
785
- } catch (fetchErr) {
786
- if (!isProduction) {
787
- console.warn(
788
- `[Retrivora SDK] WARNING: License validation via API failed due to network error (${fetchErr.message}). Falling back to local development license.`
789
- );
790
- return {
791
- projectId: currentProjectId,
792
- expiresAt: Math.floor(Date.now() / 1e3) + 86400 * 365 * 10,
793
- // 10 years
794
- tier: "hobby"
795
- };
796
- }
797
- throw fetchErr;
798
- }
799
- if (!response.ok) {
800
- let errMessage = `HTTP ${response.status}`;
801
- try {
802
- const body = await response.json();
803
- if (body.message) errMessage = body.message;
804
- } catch (e) {
805
- }
806
- throw new Error(errMessage);
807
- }
808
- const data = await response.json();
809
- if (!data.valid) {
810
- throw new Error(data.message || "License validation failed by server.");
811
- }
812
- let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
813
- if (data.expiresAt) {
814
- expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
815
- }
816
- const tier = _LicenseVerifier.extractTier(licenseKey);
817
- const payload = {
818
- projectId: currentProjectId,
819
- expiresAt: expiresAtNum,
820
- tier,
821
- licenseStatus: data.licenseStatus,
822
- minimumSupportedVersion: data.minimumSupportedVersion,
823
- forceUpgrade: data.forceUpgrade
824
- };
825
- if (payload.expiresAt && Math.floor(Date.now() / 1e3) > payload.expiresAt) {
826
- throw new Error("License key has expired.");
827
- }
828
- if (isProduction && provider) {
829
- const normalizedProvider = provider.toLowerCase();
830
- if (tier === "hobby") {
831
- const allowedHobby = ["postgresql", "pgvector", "supabase"];
832
- if (!allowedHobby.includes(normalizedProvider)) {
833
- throw new Error(
834
- `The database provider "${provider}" is not allowed on the Hobby tier. Hobby tier is restricted to PostgreSQL and Supabase. Please upgrade to a Developer Pro or Enterprise plan.`
835
- );
836
- }
837
- } else if (tier === "pro" || tier === "developer_pro" || tier === "premium" || tier === "growth" || tier === "free_trial" || tier === "free_tier" || tier === "free") {
838
- const allowedPro = [
839
- "postgresql",
840
- "pgvector",
841
- "supabase",
842
- "pinecone",
843
- "qdrant",
844
- "mongodb",
845
- "milvus",
846
- "chroma",
847
- "chromadb"
848
- ];
849
- if (!allowedPro.includes(normalizedProvider)) {
850
- throw new Error(
851
- `The database provider "${provider}" is not allowed on the Developer Pro tier. Please upgrade to an Enterprise plan.`
852
- );
853
- }
854
- }
855
- }
856
- this.cache.set(cacheKey, { payload, cachedAt: now });
857
- return payload;
858
- } catch (err) {
859
- const message = err instanceof Error ? err.message : String(err);
860
- throw new ConfigurationException(
861
- `[Retrivora SDK] License key validation failed via API: ${message}`
862
- );
863
- }
864
- }
865
- static async verifyIP(licenseKey) {
866
- var _a, _b;
867
- if (!licenseKey) return;
868
- try {
869
- const parts = licenseKey.split(".");
870
- if (parts.length !== 3) return;
871
- const [, payloadB64] = parts;
872
- const payload = JSON.parse(
873
- decodeBase64UrlToUtf8(payloadB64)
874
- );
875
- const tier = (payload.tier || "").toLowerCase();
876
- if (tier === "enterprise" || tier === "custom" || !payload.ipv4 && !payload.ipv6) {
877
- return;
878
- }
879
- let currentIpv4 = "";
880
- let currentIpv6 = "";
881
- const now = Date.now();
882
- if (this.cachedIps && now - this.cachedIps.fetchedAt < 10 * 60 * 1e3) {
883
- currentIpv4 = this.cachedIps.ipv4;
884
- currentIpv6 = this.cachedIps.ipv6;
885
- } else {
886
- const [v4Result, v6Result] = await Promise.allSettled([
887
- fetch("https://api4.ipify.org?format=json", { signal: AbortSignal.timeout(2e3) }).then((r) => r.json()),
888
- fetch("https://api6.ipify.org?format=json", { signal: AbortSignal.timeout(2e3) }).then((r) => r.json())
889
- ]);
890
- if (v4Result.status === "fulfilled" && ((_a = v4Result.value) == null ? void 0 : _a.ip)) {
891
- currentIpv4 = v4Result.value.ip;
892
- }
893
- if (v6Result.status === "fulfilled" && ((_b = v6Result.value) == null ? void 0 : _b.ip)) {
894
- currentIpv6 = v6Result.value.ip;
895
- }
896
- this.cachedIps = { ipv4: currentIpv4, ipv6: currentIpv6, fetchedAt: now };
897
- }
898
- const localIps = [];
899
- try {
900
- const osModule = await import("os");
901
- const interfaces = osModule.networkInterfaces();
902
- for (const name of Object.keys(interfaces)) {
903
- for (const iface of interfaces[name] || []) {
904
- if (!iface.internal) {
905
- localIps.push(iface.address);
906
- }
907
- }
908
- }
909
- } catch (e) {
910
- }
911
- const isIpv4Match = payload.ipv4 && (currentIpv4 === payload.ipv4 || localIps.includes(payload.ipv4));
912
- const isIpv6Match = payload.ipv6 && (currentIpv6 === payload.ipv6 || localIps.includes(payload.ipv6));
913
- if (payload.ipv4 && payload.ipv6) {
914
- if (!isIpv4Match && !isIpv6Match) {
915
- throw new Error(
916
- `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}, IPv6: ${payload.ipv6}) and cannot be used on this machine.`
917
- );
918
- }
919
- } else if (payload.ipv4 && !isIpv4Match) {
920
- throw new Error(
921
- `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}) and cannot be used on this machine.`
922
- );
923
- } else if (payload.ipv6 && !isIpv6Match) {
924
- throw new Error(
925
- `License key access restricted. This license key was created for a different system (authorized IPv6: ${payload.ipv6}) and cannot be used on this machine.`
926
- );
927
- }
928
- } catch (err) {
929
- if (err.message.includes("License key access restricted")) {
930
- throw new ConfigurationException(`[Retrivora SDK] ${err.message}`);
931
- }
932
- }
933
- }
934
- static extractTier(licenseKey) {
935
- if (!licenseKey) return "hobby";
936
- try {
937
- const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
938
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
939
- const parts = rawToken.split(".");
940
- if (parts.length === 3) {
941
- const decodedPayload = JSON.parse(decodeBase64UrlToUtf8(parts[1]));
942
- if (decodedPayload.tier) return decodedPayload.tier;
943
- }
944
- } catch (e) {
945
- }
946
- return "hobby";
947
- }
948
- };
949
- // In-memory cache to save network overhead on hot paths.
950
- _LicenseVerifier.cache = /* @__PURE__ */ new Map();
951
- _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
952
- _LicenseVerifier.cachedIps = null;
953
- var LicenseVerifier = _LicenseVerifier;
954
-
955
- // src/core/LicenseValidator.ts
956
- function canUseLocalValidationFallback(baseUrl, status) {
957
- const explicitFallback = typeof process !== "undefined" && process.env.RETRIVORA_ALLOW_LOCAL_LICENSE_FALLBACK === "true";
958
- const isLocalSdkRoute = baseUrl.startsWith("/api/retrivora") || baseUrl.includes("/api/retrivora");
959
- if (status !== void 0) {
960
- return status === 404 && (explicitFallback || isLocalSdkRoute);
961
- }
962
- return explicitFallback || isLocalSdkRoute;
963
- }
964
- var _LicenseValidator = class _LicenseValidator {
965
- // 5-minute TTL for successful validation only
966
- constructor() {
967
- this.cache = /* @__PURE__ */ new Map();
968
- /** In-flight deduplication: concurrent calls for same key share one network request */
969
- this.inflight = /* @__PURE__ */ new Map();
970
- }
971
- /** @returns Singleton instance of the validator (shared cache across all consumers). */
972
- static getInstance() {
973
- if (!_LicenseValidator.instance) {
974
- _LicenseValidator.instance = new _LicenseValidator();
975
- }
976
- return _LicenseValidator.instance;
977
- }
978
- /**
979
- * Purge entries from the local success cache.
980
- *
981
- * @param licenseKey - Optional. If provided, only that key's cache entry is
982
- * removed. If omitted the entire cache is cleared.
983
- * Callers use this after any 401/403 to ensure the next
984
- * validate() call re-validates against the server.
985
- */
986
- purgeCache(licenseKey) {
987
- if (licenseKey) {
988
- this.cache.delete(licenseKey);
989
- } else {
990
- this.cache.clear();
991
- }
992
- }
993
- /**
994
- * Primary validation entry-point for UI / hook consumers.
995
- *
996
- * Resolves the license key, consults the local success cache, performs a
997
- * server POST for authoritative status, and falls back to `LicenseVerifier.verifyAsync()`
998
- * if the server can't be reached.
999
- *
1000
- * @throws LicenseValidationError - When no key is provided OR both the
1001
- * server call AND the fallback report an invalid/expired key.
1002
- * @throws SDKVersionUnsupportedError - When server reports forceUpgrade=true.
1003
- * @returns A `LicenseValidationResponse` that the UI can use to enable or
1004
- * lock the chat widget.
1005
- */
1006
- async validate(request) {
1007
- const {
1008
- licenseKey,
1009
- projectId,
1010
- sdkVersion = SDK_VERSION,
1011
- sdk = "@retrivora-ai/rag-engine",
1012
- platform = typeof window !== "undefined" ? "browser" : "node",
1013
- retrivoraApiBase,
1014
- headers: customHeaders
1015
- } = request;
1016
- const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
1017
- const getHeader = (name) => {
1018
- if (!customHeaders) return void 0;
1019
- const target = name.toLowerCase();
1020
- for (const [k, v] of Object.entries(customHeaders)) {
1021
- if (k.toLowerCase() === target) return v;
1022
- }
1023
- return void 0;
1024
- };
1025
- const authHeader = getHeader("authorization");
1026
- let authHeaderKey = "";
1027
- if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
1028
- authHeaderKey = authHeader.replace(/^Bearer\s+/i, "");
1029
- if (authHeaderKey) {
1030
- console.warn(
1031
- '[Retrivora SDK] DEPRECATION WARNING (SEC-7): Repurposing the standard "Authorization: Bearer" header to carry the license key is deprecated and will be removed in a future release. Please use the custom "x-license-key" header instead.'
1032
- );
1033
- }
1034
- }
1035
- const rawKey = licenseKey || getHeader("x-license-key") || authHeaderKey || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY : "") || "";
1036
- const effectiveLicenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
1037
- if (!effectiveLicenseKey) {
1038
- this.purgeCache(effectiveLicenseKey);
1039
- throw new LicenseValidationError("Missing RETRIVORA_LICENSE_KEY in request. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or pass licenseKey as a prop.");
1040
- }
1041
- const cached = this.cache.get(effectiveLicenseKey);
1042
- if (cached) {
1043
- const isFresh = Date.now() - cached.timestamp < _LicenseValidator.SUCCESS_CACHE_TTL_MS;
1044
- if (isFresh && cached.response.valid && cached.response.licenseStatus === "ACTIVE" && !cached.response.forceUpgrade) {
1045
- return cached.response;
1046
- } else {
1047
- this.cache.delete(effectiveLicenseKey);
1048
- }
1049
- }
1050
- const existing = this.inflight.get(effectiveLicenseKey);
1051
- if (existing) return existing;
1052
- const inflightPromise = this._doNetworkValidate(
1053
- effectiveLicenseKey,
1054
- effectiveProjectId,
1055
- sdkVersion,
1056
- sdk,
1057
- platform,
1058
- retrivoraApiBase,
1059
- customHeaders
1060
- );
1061
- this.inflight.set(effectiveLicenseKey, inflightPromise);
1062
- try {
1063
- return await inflightPromise;
1064
- } finally {
1065
- this.inflight.delete(effectiveLicenseKey);
1066
- }
1067
- }
1068
- /** Performs the actual network request. Called once; result shared by in-flight dedup. */
1069
- async _doNetworkValidate(effectiveLicenseKey, effectiveProjectId, sdkVersion, sdk, platform, retrivoraApiBase, customHeaders) {
1070
- const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "https://www.retrivora.com/api";
1071
- const validateUrl = `${base.replace(/\/$/, "")}/v1/license/validate`;
1072
- let res = null;
1073
- try {
1074
- res = await fetch(validateUrl, {
1075
- method: "POST",
1076
- cache: "no-store",
1077
- headers: __spreadValues({
1078
- "Content-Type": "application/json",
1079
- "x-license-key": effectiveLicenseKey,
1080
- "x-sdk-version": sdkVersion
1081
- }, customHeaders || {}),
1082
- body: JSON.stringify({
1083
- licenseKey: effectiveLicenseKey,
1084
- projectId: effectiveProjectId,
1085
- sdkVersion,
1086
- sdk,
1087
- platform
1088
- })
1089
- });
1090
- } catch (err) {
1091
- try {
1092
- if (!canUseLocalValidationFallback(base)) {
1093
- throw err;
1094
- }
1095
- const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
1096
- const fallbackResp = {
1097
- valid: true,
1098
- licenseStatus: "ACTIVE",
1099
- minimumSupportedVersion: "2.1.0",
1100
- latestVersion: SDK_VERSION,
1101
- forceUpgrade: false,
1102
- expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
1103
- message: "Local license verification active."
1104
- };
1105
- this.cache.set(effectiveLicenseKey, { response: fallbackResp, timestamp: Date.now() });
1106
- return fallbackResp;
1107
- } catch (e) {
1108
- this.purgeCache(effectiveLicenseKey);
1109
- throw new LicenseValidationError(`License validation request failed: ${(err == null ? void 0 : err.message) || "Network error"}`);
1110
- }
1111
- }
1112
- if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
1113
- try {
1114
- const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
1115
- const fallbackResp = {
1116
- valid: true,
1117
- licenseStatus: "ACTIVE",
1118
- minimumSupportedVersion: "2.1.0",
1119
- latestVersion: SDK_VERSION,
1120
- forceUpgrade: false,
1121
- expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
1122
- message: "Local license verification active."
1123
- };
1124
- this.cache.set(effectiveLicenseKey, { response: fallbackResp, timestamp: Date.now() });
1125
- return fallbackResp;
1126
- } catch (e) {
1127
- }
1128
- }
1129
- const data = await res.json().catch(() => ({
1130
- valid: false,
1131
- licenseStatus: "REVOKED",
1132
- minimumSupportedVersion: "2.1.0",
1133
- latestVersion: SDK_VERSION,
1134
- forceUpgrade: false,
1135
- expiresAt: null,
1136
- message: "Failed to parse license validation response."
1137
- }));
1138
- if (!res.ok || !data.valid || data.licenseStatus !== "ACTIVE" || data.forceUpgrade) {
1139
- this.purgeCache(effectiveLicenseKey);
1140
- if (data.forceUpgrade || res.status === 426) {
1141
- throw new SDKVersionUnsupportedError(
1142
- data.message || `This SDK version (${sdkVersion}) is no longer supported. Upgrade to version ${data.latestVersion || "2.2.6"} or later.`,
1143
- data
1144
- );
1145
- }
1146
- const errMsg = data.message || `License validation failed with status: ${data.licenseStatus}. Access denied.`;
1147
- throw new LicenseValidationError(errMsg, data);
1148
- }
1149
- this.cache.set(effectiveLicenseKey, {
1150
- response: data,
1151
- timestamp: Date.now()
1152
- });
1153
- return data;
1154
- }
1155
- };
1156
- _LicenseValidator.SUCCESS_CACHE_TTL_MS = 5 * 60 * 1e3;
1157
- var LicenseValidator = _LicenseValidator;
1158
-
1159
135
  // src/components/ConfigProvider.tsx
1160
136
  import { jsx } from "react/jsx-runtime";
1161
137
  var ConfigContext = createContext(DEFAULT_CONFIG);
@@ -2796,90 +1772,6 @@ function ObservabilityPanel({ trace, primaryColor = "#6366f1" }) {
2796
1772
  ] });
2797
1773
  }
2798
1774
 
2799
- // src/utils/synonyms.ts
2800
- var FIELD_SYNONYMS = {
2801
- name: ["product", "item", "title", "label", "heading", "subject", "product name", "item name"],
2802
- price: ["cost", "amount", "msrp", "price", "rate", "value", "price_usd", "variant price"],
2803
- brand: ["manufacturer", "vendor", "make", "company", "brand_name", "supplier"],
2804
- image: [
2805
- "imageUrl",
2806
- "thumbnail",
2807
- "img",
2808
- "url",
2809
- "photo",
2810
- "picture",
2811
- "media",
2812
- "image_url",
2813
- "main_image",
2814
- "product_image",
2815
- "thumb",
2816
- "image src",
2817
- "variant image"
2818
- ],
2819
- stock: [
2820
- "inventory",
2821
- "quantity",
2822
- "count",
2823
- "availability",
2824
- "stock_level",
2825
- "inStock",
2826
- "is_available",
2827
- "in stock",
2828
- "status",
2829
- "variant inventory qty"
2830
- ],
2831
- category: [
2832
- "product_category",
2833
- "product category",
2834
- "category_name",
2835
- "category name",
2836
- "department",
2837
- "collection",
2838
- "type"
2839
- ],
2840
- description: ["summary", "content", "body", "text", "info", "details", "body (html)", "seo description"],
2841
- link: ["url", "href", "product_url", "page_url", "link"]
2842
- };
2843
- function addSynonyms(customSynonyms) {
2844
- for (const [key, aliases] of Object.entries(customSynonyms)) {
2845
- if (!FIELD_SYNONYMS[key]) {
2846
- FIELD_SYNONYMS[key] = [];
2847
- }
2848
- const existing = new Set(FIELD_SYNONYMS[key].map((s) => s.toLowerCase()));
2849
- for (const alias of aliases) {
2850
- if (!existing.has(alias.toLowerCase())) {
2851
- FIELD_SYNONYMS[key].push(alias);
2852
- existing.add(alias.toLowerCase());
2853
- }
2854
- }
2855
- }
2856
- }
2857
- function resolveMetadataValue(meta, uiKey) {
2858
- var _a;
2859
- const synonyms = (_a = FIELD_SYNONYMS[uiKey]) != null ? _a : [];
2860
- const keys = Object.keys(meta);
2861
- const systemKeys = ["namespace", "filename", "filesize", "filetype", "docid", "uploadedat", "dimension", "chunkindex"];
2862
- let match = keys.find((k) => k.toLowerCase() === uiKey.toLowerCase());
2863
- if (match !== void 0) return meta[match];
2864
- match = keys.find((k) => synonyms.map((s) => s.toLowerCase()).includes(k.toLowerCase()));
2865
- if (match !== void 0) return meta[match];
2866
- const isBlacklisted = (kl) => {
2867
- return systemKeys.includes(kl) || kl.startsWith("option1") || kl.startsWith("option2") || kl.startsWith("option3");
2868
- };
2869
- match = keys.find((k) => {
2870
- const kl = k.toLowerCase();
2871
- if (isBlacklisted(kl)) return false;
2872
- return kl.includes(uiKey.toLowerCase());
2873
- });
2874
- if (match !== void 0) return meta[match];
2875
- match = keys.find((k) => {
2876
- const kl = k.toLowerCase();
2877
- if (isBlacklisted(kl)) return false;
2878
- return synonyms.some((sk) => kl.includes(sk.toLowerCase()) || sk.toLowerCase().includes(kl));
2879
- });
2880
- return match !== void 0 ? meta[match] : void 0;
2881
- }
2882
-
2883
1775
  // src/utils/ProductExtractor.ts
2884
1776
  function sanitizeJson(raw) {
2885
1777
  let s = raw.trim();
@@ -4413,7 +3305,8 @@ function useRagChat(projectId, options = {}) {
4413
3305
  signal: controller.signal,
4414
3306
  body: payloadBody
4415
3307
  });
4416
- if (response.status === 404 && !apiUrl && primaryUrl !== "/api/chat") {
3308
+ const canFallbackLocal = typeof window === "undefined" || window.location.protocol.startsWith("http");
3309
+ if (response.status === 404 && !apiUrl && primaryUrl !== "/api/chat" && canFallbackLocal) {
4417
3310
  console.warn(`[Retrivora SDK] Chat endpoint "${primaryUrl}" returned 404. Retrying fallback to "/api/chat"...`);
4418
3311
  response = await fetch("/api/chat", {
4419
3312
  method: "POST",
@@ -4554,6 +3447,10 @@ function useRagChat(projectId, options = {}) {
4554
3447
  if (msg.toLowerCase().includes("license_revoked") || msg.toLowerCase().includes("key has been revoked") || msg.toLowerCase().includes("key has been terminated") || msg.toLowerCase().includes("key has been suspended")) {
4555
3448
  msg = "Your Retrivora license key has been terminated, suspended, or revoked. Access denied.";
4556
3449
  }
3450
+ setMessages((prev) => prev.filter((msg2) => {
3451
+ var _a2;
3452
+ return !(msg2.role === "assistant" && !((_a2 = msg2.content) == null ? void 0 : _a2.trim()));
3453
+ }));
4557
3454
  setTemporaryError(msg);
4558
3455
  onError == null ? void 0 : onError(msg);
4559
3456
  } finally {
@@ -5145,13 +4042,15 @@ function ChatWindow({
5145
4042
  headers: suggestionHeaders,
5146
4043
  body: JSON.stringify({ query: input, namespace: projectId })
5147
4044
  });
5148
- if (!response.ok) {
4045
+ const canFallbackLocal = typeof window !== "undefined" && window.location.protocol.startsWith("http") && !effectiveApiBase;
4046
+ if (response.status === 404 && canFallbackLocal) {
5149
4047
  response = await fetch("/api/suggestions", {
5150
4048
  method: "POST",
5151
4049
  headers: suggestionHeaders,
5152
4050
  body: JSON.stringify({ query: input, namespace: projectId })
5153
4051
  });
5154
4052
  }
4053
+ if (!response.ok) return;
5155
4054
  const data = await response.json();
5156
4055
  if (data.suggestions) {
5157
4056
  setSuggestions(data.suggestions);
@@ -6282,320 +5181,6 @@ var CircuitBreaker = class {
6282
5181
  this.halfOpenCalls = 0;
6283
5182
  }
6284
5183
  };
6285
-
6286
- // src/utils/logger.ts
6287
- var Logger = class {
6288
- static format(level, message, meta) {
6289
- if (this.isProduction) {
6290
- return JSON.stringify(__spreadValues({
6291
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
6292
- level,
6293
- message
6294
- }, meta));
6295
- }
6296
- const metaString = meta ? `
6297
- ${JSON.stringify(meta, null, 2)}` : "";
6298
- return `[${(/* @__PURE__ */ new Date()).toISOString()}] [${level}] ${message}${metaString}`;
6299
- }
6300
- static info(message, meta) {
6301
- console.log(this.format("INFO", message, meta));
6302
- }
6303
- static warn(message, meta) {
6304
- console.warn(this.format("WARN", message, meta));
6305
- }
6306
- static error(message, error, meta) {
6307
- const errorMeta = error instanceof Error ? { errorMessage: error.message, stack: error.stack } : { error: String(error) };
6308
- console.error(this.format("ERROR", message, __spreadValues(__spreadValues({}, meta), errorMeta)));
6309
- }
6310
- static debug(message, meta) {
6311
- if (process.env.DEBUG === "true") {
6312
- console.debug(this.format("DEBUG", message, meta));
6313
- }
6314
- }
6315
- };
6316
- Logger.isProduction = process.env.NODE_ENV === "production" || process.env.VERCEL_ENV === "production";
6317
-
6318
- // src/core/BatchProcessor.ts
6319
- function isTransientError(error) {
6320
- if (!(error instanceof Error)) return false;
6321
- const message = error.message.toLowerCase();
6322
- if (message.includes("econnrefused") || message.includes("econnreset") || message.includes("timeout") || message.includes("network") || message.includes("socket")) {
6323
- return true;
6324
- }
6325
- if (message.includes("429") || message.includes("503") || message.includes("502") || message.includes("rate limit") || message.includes("too many requests")) {
6326
- return true;
6327
- }
6328
- return false;
6329
- }
6330
- function calculateBackoffDelay(attempt, initialDelayMs, maxDelayMs, multiplier) {
6331
- const exponentialDelay = Math.min(
6332
- initialDelayMs * Math.pow(multiplier, attempt),
6333
- maxDelayMs
6334
- );
6335
- const jitter = exponentialDelay * 0.1 * (Math.random() * 2 - 1);
6336
- return Math.max(0, exponentialDelay + jitter);
6337
- }
6338
- function sleep(ms) {
6339
- return new Promise((resolve) => setTimeout(resolve, ms));
6340
- }
6341
- var BatchProcessor = class _BatchProcessor {
6342
- /**
6343
- * Execute a processor call, optionally through a caller-provided circuit
6344
- * breaker. Only transient failures count toward opening the circuit.
6345
- *
6346
- * Fix ARCH-3: removed the static module-level `cb` field. Callers must
6347
- * supply their own CircuitBreaker via BatchOptions.circuitBreaker.
6348
- * Fix TYPE-1: uses the public retryAfterMs() and incrementHalfOpen()
6349
- * API instead of accessing private fields via `as any`.
6350
- */
6351
- static async executeWithCircuitBreaker(processor, cb) {
6352
- if (!cb) {
6353
- return processor();
6354
- }
6355
- if (!cb.canExecute()) {
6356
- const retryAfterSec = Math.ceil(cb.retryAfterMs() / 1e3);
6357
- throw new Error(
6358
- `[BatchProcessor] Circuit breaker is open. Try again in ${retryAfterSec}s.`
6359
- );
6360
- }
6361
- cb.incrementHalfOpen();
6362
- try {
6363
- const result = await processor();
6364
- cb.record(true);
6365
- return result;
6366
- } catch (err) {
6367
- if (isTransientError(err)) {
6368
- cb.record(false);
6369
- }
6370
- throw err;
6371
- }
6372
- }
6373
- /**
6374
- * Processes an array of items in configurable batches with retry logic.
6375
- *
6376
- * @param items - Items to process
6377
- * @param processor - Async function that processes a batch of items
6378
- * @param options - Configuration for batch size, retries, etc.
6379
- * @returns Object with results, errors, and statistics
6380
- *
6381
- * @example
6382
- * const docs = [...];
6383
- * const result = await BatchProcessor.processBatch(
6384
- * docs,
6385
- * (batch) => vectorDB.batchUpsert(batch),
6386
- * { batchSize: 100, maxRetries: 3 }
6387
- * );
6388
- */
6389
- static async processBatch(items, processor, options) {
6390
- const {
6391
- batchSize = 100,
6392
- maxRetries = 3,
6393
- initialDelayMs = 100,
6394
- maxDelayMs = 1e4,
6395
- backoffMultiplier = 2,
6396
- throwOnPartialFailure = false
6397
- } = options != null ? options : {};
6398
- const results = [];
6399
- const errors = [];
6400
- const batches = [];
6401
- for (let i = 0; i < items.length; i += batchSize) {
6402
- batches.push(items.slice(i, i + batchSize));
6403
- }
6404
- if (batches.length === 0) {
6405
- return { results: [], errors: [], totalProcessed: 0, totalFailed: 0 };
6406
- }
6407
- for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
6408
- const batch = batches[batchIndex];
6409
- let success = false;
6410
- let lastError;
6411
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
6412
- try {
6413
- const result = await _BatchProcessor.executeWithCircuitBreaker(
6414
- () => processor(batch),
6415
- options == null ? void 0 : options.circuitBreaker
6416
- );
6417
- results.push(result);
6418
- success = true;
6419
- break;
6420
- } catch (err) {
6421
- lastError = err instanceof Error ? err : new Error(String(err));
6422
- if (!isTransientError(err) || attempt === maxRetries) {
6423
- break;
6424
- }
6425
- const delay = calculateBackoffDelay(
6426
- attempt,
6427
- initialDelayMs,
6428
- maxDelayMs,
6429
- backoffMultiplier
6430
- );
6431
- await sleep(delay);
6432
- }
6433
- }
6434
- if (!success && lastError) {
6435
- errors.push({
6436
- index: batchIndex,
6437
- error: lastError,
6438
- itemCount: batch.length
6439
- });
6440
- }
6441
- }
6442
- const totalProcessed = items.length - (errors.length > 0 ? errors.reduce((sum, e) => sum + (e.itemCount || 0), 0) : 0);
6443
- const totalFailed = errors.reduce((sum, e) => sum + (e.itemCount || 0), 0);
6444
- if (throwOnPartialFailure && errors.length > 0) {
6445
- const errorMessages = errors.map((e) => `Batch ${e.index} (${e.itemCount} items): ${e.error.message}`).join("\n");
6446
- throw new Error(
6447
- `[BatchProcessor] Batch processing failed:
6448
- ${errorMessages}`
6449
- );
6450
- }
6451
- return { results, errors, totalProcessed, totalFailed };
6452
- }
6453
- /**
6454
- * Processes items sequentially (one at a time) with retry logic.
6455
- * Useful for operations that don't support batching or when granular
6456
- * error tracking is needed.
6457
- */
6458
- static async processSequential(items, processor, options) {
6459
- const {
6460
- maxRetries = 3,
6461
- initialDelayMs = 100,
6462
- maxDelayMs = 1e4,
6463
- backoffMultiplier = 2,
6464
- throwOnPartialFailure = false
6465
- } = options != null ? options : {};
6466
- const results = [];
6467
- const errors = [];
6468
- for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
6469
- const item = items[itemIndex];
6470
- let success = false;
6471
- let lastError;
6472
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
6473
- try {
6474
- const result = await _BatchProcessor.executeWithCircuitBreaker(
6475
- () => processor(item),
6476
- options == null ? void 0 : options.circuitBreaker
6477
- );
6478
- results.push(result);
6479
- success = true;
6480
- break;
6481
- } catch (err) {
6482
- lastError = err instanceof Error ? err : new Error(String(err));
6483
- if (!isTransientError(err) || attempt === maxRetries) {
6484
- break;
6485
- }
6486
- const delay = calculateBackoffDelay(
6487
- attempt,
6488
- initialDelayMs,
6489
- maxDelayMs,
6490
- backoffMultiplier
6491
- );
6492
- await sleep(delay);
6493
- }
6494
- }
6495
- if (!success && lastError) {
6496
- errors.push({ index: itemIndex, error: lastError, itemCount: 1 });
6497
- }
6498
- }
6499
- const totalProcessed = items.length - errors.length;
6500
- const totalFailed = errors.length;
6501
- if (throwOnPartialFailure && errors.length > 0) {
6502
- const errorMessages = errors.map((e) => `Item ${e.index}: ${e.error.message}`).join("\n");
6503
- throw new Error(
6504
- `[BatchProcessor] Sequential processing failed:
6505
- ${errorMessages}`
6506
- );
6507
- }
6508
- return { results, errors, totalProcessed, totalFailed };
6509
- }
6510
- /**
6511
- * Maps over items with retry logic, returning results in order.
6512
- * Like Array.map() but with async processing and automatic retries.
6513
- */
6514
- static async mapWithRetry(items, mapper, options) {
6515
- const result = await this.processSequential(items, mapper, options);
6516
- if (result.errors.length > 0) {
6517
- Logger.warn(
6518
- `[BatchProcessor] mapWithRetry: ${result.errors.length} items failed`
6519
- );
6520
- }
6521
- const orderedResults = new Array(items.length);
6522
- let resultIndex = 0;
6523
- let errorIndex = 0;
6524
- for (let i = 0; i < items.length; i++) {
6525
- if (errorIndex < result.errors.length && result.errors[errorIndex].index === i) {
6526
- orderedResults[i] = void 0;
6527
- errorIndex++;
6528
- } else {
6529
- orderedResults[i] = result.results[resultIndex];
6530
- resultIndex++;
6531
- }
6532
- }
6533
- return orderedResults.filter((r) => r !== void 0);
6534
- }
6535
- /**
6536
- * Parallel processor with concurrency limit.
6537
- * Processes up to `concurrency` items at the same time.
6538
- */
6539
- static async processConcurrent(items, processor, concurrency = 5, options) {
6540
- var _a, _b, _c, _d;
6541
- const { throwOnPartialFailure = false } = options != null ? options : {};
6542
- const results = [];
6543
- const errors = [];
6544
- const maxRetries = (_a = options == null ? void 0 : options.maxRetries) != null ? _a : 3;
6545
- const initialDelayMs = (_b = options == null ? void 0 : options.initialDelayMs) != null ? _b : 100;
6546
- const maxDelayMs = (_c = options == null ? void 0 : options.maxDelayMs) != null ? _c : 1e4;
6547
- const backoffMultiplier = (_d = options == null ? void 0 : options.backoffMultiplier) != null ? _d : 2;
6548
- for (let i = 0; i < items.length; i += concurrency) {
6549
- const chunk = items.slice(i, i + concurrency).map((item, idx) => ({
6550
- item,
6551
- originalIndex: i + idx
6552
- }));
6553
- const chunkPromises = chunk.map(async ({ item, originalIndex }) => {
6554
- let lastErr;
6555
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
6556
- try {
6557
- const result = await _BatchProcessor.executeWithCircuitBreaker(
6558
- () => processor(item),
6559
- options == null ? void 0 : options.circuitBreaker
6560
- );
6561
- return { success: true, result, index: originalIndex };
6562
- } catch (err) {
6563
- lastErr = err instanceof Error ? err : new Error(String(err));
6564
- if (!isTransientError(err) || attempt === maxRetries) {
6565
- break;
6566
- }
6567
- const delay = calculateBackoffDelay(
6568
- attempt,
6569
- initialDelayMs,
6570
- maxDelayMs,
6571
- backoffMultiplier
6572
- );
6573
- await sleep(delay);
6574
- }
6575
- }
6576
- return { success: false, error: lastErr || new Error("Unknown error"), index: originalIndex };
6577
- });
6578
- const chunkResults = await Promise.all(chunkPromises);
6579
- for (const { success, result, error, index } of chunkResults) {
6580
- if (success) {
6581
- results.push(result);
6582
- } else {
6583
- errors.push({ index, error, itemCount: 1 });
6584
- }
6585
- }
6586
- }
6587
- const totalProcessed = items.length - errors.length;
6588
- const totalFailed = errors.length;
6589
- if (throwOnPartialFailure && errors.length > 0) {
6590
- const errorMessages = errors.map((e) => `Item ${e.index}: ${e.error.message}`).join("\n");
6591
- throw new Error(
6592
- `[BatchProcessor] Concurrent processing failed:
6593
- ${errorMessages}`
6594
- );
6595
- }
6596
- return { results, errors, totalProcessed, totalFailed };
6597
- }
6598
- };
6599
5184
  export {
6600
5185
  AuthenticationException,
6601
5186
  BatchProcessor,