@retrivora-ai/rag-engine 2.3.4 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/{BatchProcessor-CQDtlggz.d.ts → BatchProcessor-ByBl-1MA.d.ts} +81 -3
  2. package/dist/{BatchProcessor-tVzb9CdE.d.mts → BatchProcessor-Dfn23VAd.d.mts} +81 -3
  3. package/dist/{ILLMProvider-CcJ5N6XD.d.mts → ILLMProvider-B8TAVx3j.d.mts} +63 -1
  4. package/dist/{ILLMProvider-CcJ5N6XD.d.ts → ILLMProvider-B8TAVx3j.d.ts} +63 -1
  5. package/dist/handlers/index.d.mts +2 -2
  6. package/dist/handlers/index.d.ts +2 -2
  7. package/dist/handlers/index.js +419 -169
  8. package/dist/handlers/index.mjs +419 -169
  9. package/dist/{index-BwmyPJHp.d.ts → index-ejOWsaqb.d.ts} +1 -1
  10. package/dist/{index-CL-zF6bD.d.mts → index-xxQOFx-u.d.mts} +1 -1
  11. package/dist/index.css +9 -0
  12. package/dist/index.d.mts +19 -5
  13. package/dist/index.d.ts +19 -5
  14. package/dist/index.js +638 -189
  15. package/dist/index.mjs +678 -234
  16. package/dist/server.d.mts +6 -6
  17. package/dist/server.d.ts +6 -6
  18. package/dist/server.js +461 -173
  19. package/dist/server.mjs +457 -173
  20. package/package.json +2 -2
  21. package/src/components/ChatWidget.tsx +44 -19
  22. package/src/components/ChatWindow.tsx +30 -14
  23. package/src/components/ConfigProvider.tsx +86 -6
  24. package/src/components/DocumentUpload.tsx +8 -2
  25. package/src/config/RagConfig.ts +4 -0
  26. package/src/core/ConfigFetcher.ts +73 -11
  27. package/src/core/ConfigResolver.ts +1 -0
  28. package/src/core/LicenseValidator.ts +31 -13
  29. package/src/core/ProjectSettings.ts +247 -0
  30. package/src/handlers/index.ts +63 -7
  31. package/src/hooks/useProjectSettings.ts +105 -0
  32. package/src/index.css +9 -0
  33. package/src/index.ts +28 -0
  34. package/src/providers/vectordb/PineconeProvider.ts +17 -4
  35. package/src/server.ts +23 -1
  36. package/src/types/props.ts +14 -2
@@ -139,15 +139,342 @@ var init_BaseVectorProvider = __esm({
139
139
  }
140
140
  });
141
141
 
142
+ // src/core/ProjectSettings.ts
143
+ function createDefaultProjectSettings(projectId) {
144
+ return {
145
+ projectId,
146
+ branding: {
147
+ companyName: "Retrivora AI",
148
+ botName: "Retrivora Assistant",
149
+ welcomeMessage: "Hi, I can help you search your knowledge base.",
150
+ primaryColor: "#6366f1",
151
+ secondaryColor: "#8b5cf6",
152
+ fontFamily: "Inter",
153
+ borderRadius: 14,
154
+ logoUrl: "",
155
+ avatarUrl: "",
156
+ customCss: ""
157
+ },
158
+ ai: {
159
+ defaultModel: "llama-3.1-8b-instant",
160
+ embeddingModel: "text-embedding-3-small",
161
+ systemPrompt: "Answer using the connected knowledge base. Cite sources when available.",
162
+ memoryEnabled: true,
163
+ multiModelEnabled: true,
164
+ citationsEnabled: true,
165
+ fileUploadEnabled: true
166
+ },
167
+ auth: {
168
+ mode: "public",
169
+ allowedOrigins: [],
170
+ requireVerifiedEmail: false,
171
+ sessionTtlMinutes: 1440
172
+ },
173
+ widget: {
174
+ position: "bottom-right",
175
+ theme: "light",
176
+ lazyLoad: true,
177
+ autoReconnect: true,
178
+ persistConversations: true,
179
+ showRetrivoraBranding: false
180
+ },
181
+ telemetry: {
182
+ enabled: true,
183
+ collectBrowser: true,
184
+ collectCountry: false,
185
+ redactPii: true,
186
+ retentionDays: 30
187
+ },
188
+ lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
189
+ conversationFeatures: DEFAULT_CONVERSATION_FEATURES
190
+ };
191
+ }
192
+ function cleanString(value, fallback, maxLength = 2e3) {
193
+ if (typeof value !== "string") return fallback;
194
+ return value.trim().slice(0, maxLength);
195
+ }
196
+ function cleanBoolean(value, fallback) {
197
+ return typeof value === "boolean" ? value : fallback;
198
+ }
199
+ function cleanNumber(value, fallback, min, max) {
200
+ const num = typeof value === "number" ? value : Number(value);
201
+ if (!Number.isFinite(num)) return fallback;
202
+ return Math.min(Math.max(Math.round(num), min), max);
203
+ }
204
+ function cleanEnum(value, fallback, allowed) {
205
+ return typeof value === "string" && allowed.includes(value) ? value : fallback;
206
+ }
207
+ function cleanStringList(value, fallback, maxItems = 20) {
208
+ if (!Array.isArray(value)) return fallback;
209
+ const cleaned = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, maxItems);
210
+ return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
211
+ }
212
+ function normalizeProjectSettings(projectId, input) {
213
+ const defaults = createDefaultProjectSettings(projectId);
214
+ const branding = (input == null ? void 0 : input.branding) || {};
215
+ const ai = (input == null ? void 0 : input.ai) || {};
216
+ const auth = (input == null ? void 0 : input.auth) || {};
217
+ const widget = (input == null ? void 0 : input.widget) || {};
218
+ const telemetry = (input == null ? void 0 : input.telemetry) || {};
219
+ return {
220
+ projectId,
221
+ branding: {
222
+ companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
223
+ botName: cleanString(branding.botName, defaults.branding.botName, 120),
224
+ welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
225
+ primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
226
+ secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
227
+ fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
228
+ borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
229
+ logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
230
+ avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
231
+ customCss: cleanString(branding.customCss, defaults.branding.customCss, 5e3)
232
+ },
233
+ ai: {
234
+ defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
235
+ embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
236
+ systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5e3),
237
+ memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
238
+ multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
239
+ citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
240
+ fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled)
241
+ },
242
+ auth: {
243
+ mode: cleanEnum(auth.mode, defaults.auth.mode, ["public", "anonymous", "jwt", "oauth", "okta", "auth0", "supabase", "firebase", "sso", "custom_token"]),
244
+ allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
245
+ requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
246
+ sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200)
247
+ },
248
+ widget: {
249
+ position: cleanEnum(widget.position, defaults.widget.position, ["bottom-right", "bottom-left", "top-right", "top-left"]),
250
+ theme: cleanEnum(widget.theme, defaults.widget.theme, ["light", "dark", "system"]),
251
+ lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
252
+ autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
253
+ persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
254
+ showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding)
255
+ },
256
+ telemetry: {
257
+ enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
258
+ collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
259
+ collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
260
+ redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
261
+ retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365)
262
+ },
263
+ lifecycleHooks: cleanStringList(input == null ? void 0 : input.lifecycleHooks, defaults.lifecycleHooks, 30),
264
+ conversationFeatures: cleanStringList(input == null ? void 0 : input.conversationFeatures, defaults.conversationFeatures, 30),
265
+ updatedAt: input == null ? void 0 : input.updatedAt
266
+ };
267
+ }
268
+ var DEFAULT_LIFECYCLE_HOOKS, DEFAULT_CONVERSATION_FEATURES;
269
+ var init_ProjectSettings = __esm({
270
+ "src/core/ProjectSettings.ts"() {
271
+ "use strict";
272
+ DEFAULT_LIFECYCLE_HOOKS = [
273
+ "beforeInitialize",
274
+ "afterInitialize",
275
+ "beforeSend",
276
+ "afterResponse",
277
+ "onMessage",
278
+ "onCitationClick",
279
+ "onFeedback",
280
+ "onError",
281
+ "onReconnect",
282
+ "onFileUpload"
283
+ ];
284
+ DEFAULT_CONVERSATION_FEATURES = [
285
+ "History",
286
+ "Resume",
287
+ "Search",
288
+ "Export",
289
+ "Rename",
290
+ "Delete",
291
+ "Tags",
292
+ "Pinned",
293
+ "Unread",
294
+ "Ratings"
295
+ ];
296
+ }
297
+ });
298
+
299
+ // package.json
300
+ var package_default;
301
+ var init_package = __esm({
302
+ "package.json"() {
303
+ package_default = {
304
+ name: "@retrivora-ai/rag-engine",
305
+ version: "2.3.6",
306
+ description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
307
+ author: "Abhinav Alkuchi",
308
+ license: "UNLICENSED",
309
+ keywords: [
310
+ "rag",
311
+ "retrieval-augmented-generation",
312
+ "chatbot",
313
+ "vector-database",
314
+ "pinecone",
315
+ "pgvector",
316
+ "postgresql",
317
+ "milvus",
318
+ "qdrant",
319
+ "chromadb",
320
+ "redis",
321
+ "weaviate",
322
+ "mongodb",
323
+ "openai",
324
+ "anthropic",
325
+ "ollama",
326
+ "nextjs",
327
+ "react",
328
+ "ai",
329
+ "llm",
330
+ "embeddings"
331
+ ],
332
+ main: "dist/index.js",
333
+ module: "dist/index.mjs",
334
+ types: "dist/index.d.ts",
335
+ exports: {
336
+ ".": {
337
+ types: "./dist/index.d.ts",
338
+ require: "./dist/index.js",
339
+ import: "./dist/index.mjs"
340
+ },
341
+ "./style.css": "./dist/index.css",
342
+ "./index.css": "./dist/index.css",
343
+ "./styles.css": "./dist/index.css",
344
+ "./handlers": {
345
+ types: "./dist/handlers/index.d.ts",
346
+ require: "./dist/handlers/index.js",
347
+ import: "./dist/handlers/index.mjs"
348
+ },
349
+ "./server": {
350
+ types: "./dist/server.d.ts",
351
+ require: "./dist/server.js",
352
+ import: "./dist/server.mjs"
353
+ }
354
+ },
355
+ browser: {
356
+ child_process: false,
357
+ fs: false,
358
+ net: false,
359
+ tls: false,
360
+ crypto: false,
361
+ os: false,
362
+ path: false,
363
+ stream: false,
364
+ http: false,
365
+ https: false,
366
+ zlib: false,
367
+ mongodb: false,
368
+ pg: false,
369
+ "pdf-parse": false,
370
+ mammoth: false
371
+ },
372
+ files: [
373
+ "dist",
374
+ "src",
375
+ ".env.example",
376
+ "README.md",
377
+ "FREE_TIER_ARCHITECTURE.md"
378
+ ],
379
+ scripts: {
380
+ 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",
381
+ build: "npm run build:pkg",
382
+ "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",
383
+ lint: "eslint",
384
+ typecheck: "tsc --noEmit -p tsconfig.build.json",
385
+ clean: "rm -rf dist"
386
+ },
387
+ peerDependencies: {
388
+ next: ">=15.0.0",
389
+ react: ">=18.0.0",
390
+ "react-dom": ">=18.0.0"
391
+ },
392
+ peerDependenciesMeta: {
393
+ next: {
394
+ optional: true
395
+ }
396
+ },
397
+ dependencies: {
398
+ "@anthropic-ai/sdk": "^0.95.1",
399
+ "@google/genai": "^0.8.0",
400
+ "@google/generative-ai": "^0.24.1",
401
+ "@pinecone-database/pinecone": "^7.2.0",
402
+ "@types/papaparse": "^5.5.2",
403
+ axios: "^1.15.0",
404
+ "lucide-react": "^1.8.0",
405
+ "next-themes": "^0.4.6",
406
+ openai: "^6.34.0",
407
+ papaparse: "^5.5.3",
408
+ "react-is": "^18.3.1",
409
+ "react-markdown": "^10.1.0",
410
+ recharts: "^3.8.1",
411
+ "remark-gfm": "^4.0.1",
412
+ xlsx: "^0.18.5"
413
+ },
414
+ optionalDependencies: {
415
+ "@langchain/core": "^1.1.42",
416
+ "@langchain/openai": "^1.4.5",
417
+ langchain: "^1.3.5",
418
+ llamaindex: "^0.11.9",
419
+ mammoth: "^1.8.0",
420
+ mongodb: "^7.1.1",
421
+ "pdf-parse": "^1.1.1",
422
+ pg: "^8.20.0"
423
+ },
424
+ devDependencies: {
425
+ "@tailwindcss/cli": "^4",
426
+ "@tailwindcss/postcss": "^4",
427
+ "@types/estree": "^1.0.9",
428
+ "@types/node": "^20",
429
+ "@types/pdf-parse": "^1.1.5",
430
+ "@types/pg": "^8.20.0",
431
+ "@types/react": "^19.2.14",
432
+ "@types/react-dom": "^19.2.3",
433
+ dotenv: "^17.4.2",
434
+ eslint: "^9",
435
+ "eslint-config-next": "16.2.4",
436
+ next: "16.2.10",
437
+ tailwindcss: "^4",
438
+ tsup: "^8.5.1",
439
+ typescript: "^5"
440
+ }
441
+ };
442
+ }
443
+ });
444
+
445
+ // src/version.ts
446
+ var SDK_VERSION;
447
+ var init_version = __esm({
448
+ "src/version.ts"() {
449
+ "use strict";
450
+ init_package();
451
+ SDK_VERSION = package_default.version || "2.1.3";
452
+ }
453
+ });
454
+
142
455
  // src/core/ConfigFetcher.ts
143
- var ConfigFetcher;
456
+ var CONTROL_PLANE_URL, LLM_PROXY_BASE_URL, ConfigFetcher;
144
457
  var init_ConfigFetcher = __esm({
145
458
  "src/core/ConfigFetcher.ts"() {
146
459
  "use strict";
460
+ init_ProjectSettings();
461
+ init_version();
462
+ CONTROL_PLANE_URL = "https://www.retrivora.com";
463
+ LLM_PROXY_BASE_URL = "https://www.retrivora.com/api/v1";
147
464
  ConfigFetcher = class {
148
465
  // 5-minute in-memory session cache
149
466
  /**
150
- * Fetch full project configuration (vectorDb + embedding + llm) from Retrivora Control Plane.
467
+ * Fetch full project configuration (vectorDb + embedding + llm + workspace) from Retrivora Control Plane.
468
+ *
469
+ * The SDK calls https://www.retrivora.com/api/v1/config with the project ID and license key.
470
+ * The server validates the license against the database and returns:
471
+ * - validity (tier, isActive, expiresAt)
472
+ * - LLM model info
473
+ * - embedding model info
474
+ * - Pinecone index name and workspace/namespace
475
+ *
476
+ * The Pinecone API key is NOT returned (server-only). The SDK uses local
477
+ * PINECONE_API_KEY if available, or vector operations are handled server-side.
151
478
  */
152
479
  static async fetchRemoteConfig(projectId, licenseKey) {
153
480
  var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
@@ -160,46 +487,60 @@ var init_ConfigFetcher = __esm({
160
487
  const controlPlaneUrls = [
161
488
  process.env.RETRIVORA_CONTROL_PLANE_URL,
162
489
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
163
- "https://www.retrivora.com",
164
- "https://retrivora.com",
165
- "http://localhost:3000",
166
- "http://localhost:3001"
167
- ].filter(Boolean);
490
+ CONTROL_PLANE_URL
491
+ ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
168
492
  for (const baseUrl of controlPlaneUrls) {
169
493
  try {
170
- const url = `${baseUrl.replace(/\/$/, "")}/api/v1/config?projectId=${encodeURIComponent(projectId)}${licenseKey ? `&licenseKey=${encodeURIComponent(licenseKey)}` : ""}`;
494
+ const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
171
495
  const res = await fetch(url, {
172
496
  method: "GET",
173
497
  headers: __spreadValues({
174
- "Content-Type": "application/json"
498
+ "Content-Type": "application/json",
499
+ "x-sdk-version": SDK_VERSION
175
500
  }, licenseKey ? { "x-license-key": licenseKey } : {})
176
501
  });
177
502
  if (res.ok) {
178
503
  const data = await res.json();
179
- if ((data == null ? void 0 : data.success) && ((_a3 = data == null ? void 0 : data.vectorDb) == null ? void 0 : _a3.apiKey)) {
504
+ if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
180
505
  const fetchedProjectId = data.projectId || projectId;
181
506
  const config = {
182
507
  projectId: fetchedProjectId,
508
+ tier: data.tier,
509
+ isActive: data.isActive,
510
+ expiresAt: data.expiresAt,
183
511
  vectorDb: {
184
- apiKey: data.vectorDb.apiKey,
512
+ // apiKey is not returned by the config API — it's a server-only secret.
513
+ // The SDK uses local PINECONE_API_KEY if available.
514
+ apiKey: data.vectorDb.apiKey || "",
185
515
  indexName: data.vectorDb.indexName || "retrivora-free",
186
516
  provider: data.vectorDb.provider || "pinecone",
187
- projectId: fetchedProjectId
517
+ projectId: fetchedProjectId,
518
+ namespace: ((_a3 = data.workspace) == null ? void 0 : _a3.namespace) || data.vectorDb.namespace || fetchedProjectId
188
519
  },
189
520
  embedding: {
190
521
  provider: ((_b = data.embedding) == null ? void 0 : _b.provider) || "universal_rest",
191
522
  model: ((_c = data.embedding) == null ? void 0 : _c.model) || "text-embedding-004",
192
- baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || "https://llm.retrivora.com/api/v1",
523
+ // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
524
+ baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || LLM_PROXY_BASE_URL,
193
525
  apiKey: ((_e = data.embedding) == null ? void 0 : _e.apiKey) || licenseKey || "",
194
526
  profile: ((_f = data.embedding) == null ? void 0 : _f.profile) || "litellm"
195
527
  },
196
528
  llm: {
197
529
  provider: ((_g2 = data.llm) == null ? void 0 : _g2.provider) || "universal_rest",
198
530
  model: ((_h = data.llm) == null ? void 0 : _h.model) || "llama-3.1-8b-instant",
199
- baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || "https://llm.retrivora.com/api/v1",
531
+ // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
532
+ baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || LLM_PROXY_BASE_URL,
200
533
  apiKey: ((_j = data.llm) == null ? void 0 : _j.apiKey) || licenseKey || "",
201
534
  profile: ((_k = data.llm) == null ? void 0 : _k.profile) || "litellm"
202
- }
535
+ },
536
+ workspace: data.workspace || {
537
+ namespace: fetchedProjectId,
538
+ indexName: data.vectorDb.indexName || "retrivora-free"
539
+ },
540
+ projectSettings: normalizeProjectSettings(
541
+ fetchedProjectId,
542
+ data.projectSettings || data.settings
543
+ )
203
544
  };
204
545
  this.cache.set(cacheKey, { config, cachedAt: now });
205
546
  return config;
@@ -317,19 +658,26 @@ var init_PineconeProvider = __esm({
317
658
  })();
318
659
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
319
660
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
320
- if (remoteConfig == null ? void 0 : remoteConfig.apiKey) {
321
- key = remoteConfig.apiKey;
322
- this.apiKey = key;
661
+ if (remoteConfig) {
662
+ if (remoteConfig.apiKey) {
663
+ key = remoteConfig.apiKey;
664
+ this.apiKey = key;
665
+ }
323
666
  if (remoteConfig.indexName) {
324
667
  this.indexName = remoteConfig.indexName;
325
668
  }
326
669
  if (remoteConfig.projectId) {
327
670
  this.projectId = remoteConfig.projectId;
328
671
  }
672
+ if (remoteConfig.namespace) {
673
+ this.namespace = remoteConfig.namespace;
674
+ }
329
675
  }
330
676
  }
331
677
  if (!key) {
332
- console.warn("[PineconeProvider] Warning: No Pinecone API key available locally or remotely.");
678
+ console.warn(
679
+ "[PineconeProvider] Warning: No Pinecone API key available. Set PINECONE_API_KEY in your environment, or ensure the Retrivora Control Plane (https://www.retrivora.com) is reachable for proxy-based vector operations."
680
+ );
333
681
  return;
334
682
  }
335
683
  this.client = new Pinecone({ apiKey: key });
@@ -2768,6 +3116,7 @@ var ConfigResolver = class {
2768
3116
  options: __spreadValues(__spreadValues({}, envConfig.embedding.options || {}), hostConfig.embedding.options || {})
2769
3117
  }) : envConfig.embedding,
2770
3118
  ui: hostConfig.ui ? mergeDefined(envConfig.ui, hostConfig.ui) : envConfig.ui,
3119
+ projectSettings: hostConfig.projectSettings || envConfig.projectSettings,
2771
3120
  rag: hostConfig.rag ? __spreadValues(__spreadValues({}, envConfig.rag), hostConfig.rag) : envConfig.rag,
2772
3121
  telemetry: hostConfig.telemetry ? __spreadValues(__spreadValues({}, envConfig.telemetry), hostConfig.telemetry) : envConfig.telemetry
2773
3122
  });
@@ -4670,149 +5019,8 @@ var ConfigValidator = class {
4670
5019
  }
4671
5020
  };
4672
5021
 
4673
- // package.json
4674
- var package_default = {
4675
- name: "@retrivora-ai/rag-engine",
4676
- version: "2.3.4",
4677
- description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
4678
- author: "Abhinav Alkuchi",
4679
- license: "UNLICENSED",
4680
- keywords: [
4681
- "rag",
4682
- "retrieval-augmented-generation",
4683
- "chatbot",
4684
- "vector-database",
4685
- "pinecone",
4686
- "pgvector",
4687
- "postgresql",
4688
- "milvus",
4689
- "qdrant",
4690
- "chromadb",
4691
- "redis",
4692
- "weaviate",
4693
- "mongodb",
4694
- "openai",
4695
- "anthropic",
4696
- "ollama",
4697
- "nextjs",
4698
- "react",
4699
- "ai",
4700
- "llm",
4701
- "embeddings"
4702
- ],
4703
- main: "dist/index.js",
4704
- module: "dist/index.mjs",
4705
- types: "dist/index.d.ts",
4706
- exports: {
4707
- ".": {
4708
- types: "./dist/index.d.ts",
4709
- require: "./dist/index.js",
4710
- import: "./dist/index.mjs"
4711
- },
4712
- "./style.css": "./dist/index.css",
4713
- "./index.css": "./dist/index.css",
4714
- "./styles.css": "./dist/index.css",
4715
- "./handlers": {
4716
- types: "./dist/handlers/index.d.ts",
4717
- require: "./dist/handlers/index.js",
4718
- import: "./dist/handlers/index.mjs"
4719
- },
4720
- "./server": {
4721
- types: "./dist/server.d.ts",
4722
- require: "./dist/server.js",
4723
- import: "./dist/server.mjs"
4724
- }
4725
- },
4726
- browser: {
4727
- child_process: false,
4728
- fs: false,
4729
- net: false,
4730
- tls: false,
4731
- crypto: false,
4732
- os: false,
4733
- path: false,
4734
- stream: false,
4735
- http: false,
4736
- https: false,
4737
- zlib: false,
4738
- mongodb: false,
4739
- pg: false,
4740
- "pdf-parse": false,
4741
- mammoth: false
4742
- },
4743
- files: [
4744
- "dist",
4745
- "src",
4746
- ".env.example",
4747
- "README.md",
4748
- "FREE_TIER_ARCHITECTURE.md"
4749
- ],
4750
- scripts: {
4751
- 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",
4752
- build: "npm run build:pkg",
4753
- "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",
4754
- lint: "eslint",
4755
- typecheck: "tsc --noEmit -p tsconfig.build.json",
4756
- clean: "rm -rf dist"
4757
- },
4758
- peerDependencies: {
4759
- next: ">=15.0.0",
4760
- react: ">=18.0.0",
4761
- "react-dom": ">=18.0.0"
4762
- },
4763
- peerDependenciesMeta: {
4764
- next: {
4765
- optional: true
4766
- }
4767
- },
4768
- dependencies: {
4769
- "@anthropic-ai/sdk": "^0.95.1",
4770
- "@google/genai": "^0.8.0",
4771
- "@google/generative-ai": "^0.24.1",
4772
- "@pinecone-database/pinecone": "^7.2.0",
4773
- "@types/papaparse": "^5.5.2",
4774
- axios: "^1.15.0",
4775
- "lucide-react": "^1.8.0",
4776
- "next-themes": "^0.4.6",
4777
- openai: "^6.34.0",
4778
- papaparse: "^5.5.3",
4779
- "react-is": "^18.3.1",
4780
- "react-markdown": "^10.1.0",
4781
- recharts: "^3.8.1",
4782
- "remark-gfm": "^4.0.1",
4783
- xlsx: "^0.18.5"
4784
- },
4785
- optionalDependencies: {
4786
- "@langchain/core": "^1.1.42",
4787
- "@langchain/openai": "^1.4.5",
4788
- langchain: "^1.3.5",
4789
- llamaindex: "^0.11.9",
4790
- mammoth: "^1.8.0",
4791
- mongodb: "^7.1.1",
4792
- "pdf-parse": "^1.1.1",
4793
- pg: "^8.20.0"
4794
- },
4795
- devDependencies: {
4796
- "@tailwindcss/cli": "^4",
4797
- "@tailwindcss/postcss": "^4",
4798
- "@types/estree": "^1.0.9",
4799
- "@types/node": "^20",
4800
- "@types/pdf-parse": "^1.1.5",
4801
- "@types/pg": "^8.20.0",
4802
- "@types/react": "^19.2.14",
4803
- "@types/react-dom": "^19.2.3",
4804
- dotenv: "^17.4.2",
4805
- eslint: "^9",
4806
- "eslint-config-next": "16.2.4",
4807
- next: "16.2.10",
4808
- tailwindcss: "^4",
4809
- tsup: "^8.5.1",
4810
- typescript: "^5"
4811
- }
4812
- };
4813
-
4814
- // src/version.ts
4815
- var SDK_VERSION = package_default.version || "2.1.3";
5022
+ // src/core/Pipeline.ts
5023
+ init_version();
4816
5024
 
4817
5025
  // src/rag/DocumentChunker.ts
4818
5026
  var DocumentChunker = class {
@@ -10481,6 +10689,7 @@ var DatabaseStorage = class {
10481
10689
  };
10482
10690
 
10483
10691
  // src/handlers/index.ts
10692
+ init_version();
10484
10693
  async function checkAuth(req, onAuthorize) {
10485
10694
  if (!onAuthorize) return null;
10486
10695
  try {
@@ -10590,7 +10799,7 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
10590
10799
  function enforceLicense(req, config, bodyLicenseKey) {
10591
10800
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
10592
10801
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
10593
- const projectId = config.projectId || "my-rag-app";
10802
+ const projectId = config.projectId || "";
10594
10803
  try {
10595
10804
  const payload = LicenseVerifier.verify(licenseKey, projectId);
10596
10805
  return { ok: true, payload };
@@ -10612,6 +10821,35 @@ function enforceLicense(req, config, bodyLicenseKey) {
10612
10821
  };
10613
10822
  }
10614
10823
  }
10824
+ function getAllowedNamespaces(projectId) {
10825
+ const trimmed = projectId.trim();
10826
+ const withoutPrefix = trimmed.startsWith("retrivora-") ? trimmed.replace(/^retrivora-/, "") : trimmed;
10827
+ return new Set([
10828
+ trimmed,
10829
+ withoutPrefix,
10830
+ `retrivora-${withoutPrefix}`
10831
+ ].filter(Boolean));
10832
+ }
10833
+ function resolveLicensedNamespace(payload, requestedNamespace) {
10834
+ const allowed = getAllowedNamespaces(payload.projectId);
10835
+ const requested = requestedNamespace == null ? void 0 : requestedNamespace.trim();
10836
+ if (requested && !allowed.has(requested)) {
10837
+ return {
10838
+ ok: false,
10839
+ response: new Response(JSON.stringify({
10840
+ error: {
10841
+ code: "NAMESPACE_FORBIDDEN",
10842
+ message: "Requested namespace is not authorized for this license."
10843
+ }
10844
+ }), {
10845
+ status: 403,
10846
+ headers: { "Content-Type": "application/json" }
10847
+ })
10848
+ };
10849
+ }
10850
+ const defaultNamespace = payload.projectId.startsWith("retrivora-") ? payload.projectId : `retrivora-${payload.projectId}`;
10851
+ return { ok: true, namespace: requested || defaultNamespace };
10852
+ }
10615
10853
  var MAX_MESSAGE_LENGTH = 8e3;
10616
10854
  function sanitizeInput(raw) {
10617
10855
  const stripped = raw.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "");
@@ -10772,6 +11010,8 @@ function createChatHandler(configOrPlugin, options) {
10772
11010
  }
10773
11011
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
10774
11012
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11013
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11014
+ if (!namespaceCheck.ok) return namespaceCheck.response;
10775
11015
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
10776
11016
  if (!sanitized.ok) {
10777
11017
  return NextResponse.json({ error: { code: "INVALID_INPUT", message: sanitized.error } }, { status: 400 });
@@ -10783,7 +11023,7 @@ function createChatHandler(configOrPlugin, options) {
10783
11023
  role: "user",
10784
11024
  content: message
10785
11025
  }).catch((err) => console.warn("[createChatHandler] Failed to save user message:", err));
10786
- const result = await plugin.chat(message, history, namespace);
11026
+ const result = await plugin.chat(message, history, namespaceCheck.namespace);
10787
11027
  const assistantMsgId = messageId || `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10788
11028
  await storage.saveMessage(sessionId, {
10789
11029
  id: assistantMsgId,
@@ -10864,6 +11104,8 @@ function createStreamHandler(configOrPlugin, options) {
10864
11104
  }
10865
11105
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
10866
11106
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11107
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11108
+ if (!namespaceCheck.ok) return namespaceCheck.response;
10867
11109
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
10868
11110
  if (!sanitized.ok) {
10869
11111
  return new Response(
@@ -10893,7 +11135,7 @@ function createStreamHandler(configOrPlugin, options) {
10893
11135
  }
10894
11136
  };
10895
11137
  try {
10896
- const pipelineStream = plugin.chatStream(message, history, namespace);
11138
+ const pipelineStream = plugin.chatStream(message, history, namespaceCheck.namespace);
10897
11139
  let fullReply = "";
10898
11140
  try {
10899
11141
  for (var iter = __forAwait(pipelineStream), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
@@ -10999,6 +11241,8 @@ function createIngestHandler(configOrPlugin, options) {
10999
11241
  if (!Array.isArray(documents) || documents.length === 0) {
11000
11242
  return NextResponse.json({ error: "documents array is required" }, { status: 400 });
11001
11243
  }
11244
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11245
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11002
11246
  if (isFreeTier(licenseCheck.payload.tier)) {
11003
11247
  const totalIncomingBytes = documents.reduce(
11004
11248
  (sum, d) => sum + Buffer.byteLength(d.content || "", "utf8"),
@@ -11020,7 +11264,7 @@ function createIngestHandler(configOrPlugin, options) {
11020
11264
  );
11021
11265
  }
11022
11266
  }
11023
- const results = await plugin.ingest(documents, namespace);
11267
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11024
11268
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Ingested ${documents.length} document(s)`);
11025
11269
  return NextResponse.json({ results });
11026
11270
  } catch (err) {
@@ -11066,7 +11310,7 @@ function createLicenseHandler(configOrPlugin, options) {
11066
11310
  const config = plugin.getConfig();
11067
11311
  const rawKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || "";
11068
11312
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11069
- const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "my-rag-app";
11313
+ const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11070
11314
  const payload = LicenseVerifier.verify(licenseKey, projectId);
11071
11315
  return NextResponse.json({
11072
11316
  valid: true,
@@ -11108,6 +11352,8 @@ function createUploadHandler(configOrPlugin, options) {
11108
11352
  const namespace = formData.get("namespace") || void 0;
11109
11353
  const dimensionRaw = formData.get("dimension");
11110
11354
  const dimension = dimensionRaw ? parseInt(dimensionRaw, 10) : void 0;
11355
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11356
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11111
11357
  if (!files || files.length === 0) {
11112
11358
  return NextResponse.json({ error: "No files provided" }, { status: 400 });
11113
11359
  }
@@ -11224,7 +11470,7 @@ function createUploadHandler(configOrPlugin, options) {
11224
11470
  });
11225
11471
  }
11226
11472
  }
11227
- const results = await plugin.ingest(documents, namespace);
11473
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11228
11474
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Uploaded & ingested ${files.length} file(s)`);
11229
11475
  return NextResponse.json({ message: "Upload successful", results });
11230
11476
  } catch (err) {
@@ -11243,6 +11489,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11243
11489
  const config = plugin.getConfig();
11244
11490
  const licenseCheck = enforceLicense(req, config);
11245
11491
  if (!licenseCheck.ok) return licenseCheck.response;
11492
+ let effectiveLicensePayload = licenseCheck.payload;
11246
11493
  try {
11247
11494
  let query = "";
11248
11495
  let namespace = void 0;
@@ -11255,6 +11502,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11255
11502
  if (bodyLicenseKey) {
11256
11503
  const recheck = enforceLicense(req, config, bodyLicenseKey);
11257
11504
  if (!recheck.ok) return recheck.response;
11505
+ effectiveLicensePayload = recheck.payload;
11258
11506
  }
11259
11507
  } else {
11260
11508
  const url = new URL(req.url);
@@ -11264,7 +11512,9 @@ function createSuggestionsHandler(configOrPlugin, options) {
11264
11512
  if (!query || typeof query !== "string" || !query.trim()) {
11265
11513
  return NextResponse.json({ suggestions: [] });
11266
11514
  }
11267
- const suggestions = await plugin.getSuggestions(query, namespace);
11515
+ const namespaceCheck = resolveLicensedNamespace(effectiveLicensePayload, namespace);
11516
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11517
+ const suggestions = await plugin.getSuggestions(query, namespaceCheck.namespace);
11268
11518
  reportTelemetry(req, plugin, "AUTO_SUGGESTIONS", "success", `Fetched ${suggestions.length} suggestions for: ${query.slice(0, 30)}`);
11269
11519
  return NextResponse.json({ suggestions });
11270
11520
  } catch (err) {